Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / net / ipv6.c
1 /*
2  * Copyright (C) 2013 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <byteswap.h>
29 #include <ipxe/iobuf.h>
30 #include <ipxe/tcpip.h>
31 #include <ipxe/if_ether.h>
32 #include <ipxe/crc32.h>
33 #include <ipxe/fragment.h>
34 #include <ipxe/ipstat.h>
35 #include <ipxe/ndp.h>
36 #include <ipxe/ipv6.h>
37
38 /** @file
39  *
40  * IPv6 protocol
41  *
42  */
43
44 /* Disambiguate the various error causes */
45 #define EINVAL_LEN __einfo_error ( EINFO_EINVAL_LEN )
46 #define EINFO_EINVAL_LEN \
47         __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid length" )
48 #define ENOTSUP_VER __einfo_error ( EINFO_ENOTSUP_VER )
49 #define EINFO_ENOTSUP_VER \
50         __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported version" )
51 #define ENOTSUP_HDR __einfo_error ( EINFO_ENOTSUP_HDR )
52 #define EINFO_ENOTSUP_HDR \
53         __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported header type" )
54 #define ENOTSUP_OPT __einfo_error ( EINFO_ENOTSUP_OPT )
55 #define EINFO_ENOTSUP_OPT \
56         __einfo_uniqify ( EINFO_ENOTSUP, 0x03, "Unsupported option" )
57
58 /** List of IPv6 miniroutes */
59 struct list_head ipv6_miniroutes = LIST_HEAD_INIT ( ipv6_miniroutes );
60
61 /** IPv6 statistics */
62 static struct ip_statistics ipv6_stats;
63
64 /** IPv6 statistics family */
65 struct ip_statistics_family
66 ipv6_statistics_family __ip_statistics_family ( IP_STATISTICS_IPV6 ) = {
67         .version = 6,
68         .stats = &ipv6_stats,
69 };
70
71 /**
72  * Determine debugging colour for IPv6 debug messages
73  *
74  * @v in                IPv6 address
75  * @ret col             Debugging colour (for DBGC())
76  */
77 static uint32_t ipv6col ( struct in6_addr *in ) {
78         return crc32_le ( 0, in, sizeof ( *in ) );
79 }
80
81 /**
82  * Dump IPv6 routing table entry
83  *
84  * @v miniroute         Routing table entry
85  */
86 static inline __attribute__ (( always_inline )) void
87 ipv6_dump_miniroute ( struct ipv6_miniroute *miniroute ) {
88         struct net_device *netdev = miniroute->netdev;
89
90         DBGC ( netdev, "IPv6 %s has %s %s/%d", netdev->name,
91                ( ( miniroute->flags & IPV6_HAS_ADDRESS ) ?
92                  "address" : "prefix" ),
93                inet6_ntoa ( &miniroute->address ), miniroute->prefix_len );
94         if ( miniroute->flags & IPV6_HAS_ROUTER )
95                 DBGC ( netdev, " router %s", inet6_ntoa ( &miniroute->router ));
96         DBGC ( netdev, "\n" );
97 }
98
99 /**
100  * Check if network device has a specific IPv6 address
101  *
102  * @v netdev            Network device
103  * @v addr              IPv6 address
104  * @ret has_addr        Network device has this IPv6 address
105  */
106 int ipv6_has_addr ( struct net_device *netdev, struct in6_addr *addr ) {
107         struct ipv6_miniroute *miniroute;
108
109         list_for_each_entry ( miniroute, &ipv6_miniroutes, list ) {
110                 if ( ( miniroute->netdev == netdev ) &&
111                      ( miniroute->flags & IPV6_HAS_ADDRESS ) &&
112                      ( memcmp ( &miniroute->address, addr,
113                                 sizeof ( miniroute->address ) ) == 0 ) ) {
114                         /* Found matching address */
115                         return 1;
116                 }
117         }
118         return 0;
119 }
120
121 /**
122  * Check if IPv6 address is within a routing table entry's local network
123  *
124  * @v miniroute         Routing table entry
125  * @v address           IPv6 address
126  * @ret is_on_link      Address is within this entry's local network
127  */
128 static int ipv6_is_on_link ( struct ipv6_miniroute *miniroute,
129                              struct in6_addr *address ) {
130         unsigned int i;
131
132         for ( i = 0 ; i < ( sizeof ( address->s6_addr32 ) /
133                             sizeof ( address->s6_addr32[0] ) ) ; i++ ) {
134                 if ( (( address->s6_addr32[i] ^ miniroute->address.s6_addr32[i])
135                       & miniroute->prefix_mask.s6_addr32[i] ) != 0 )
136                         return 0;
137         }
138         return 1;
139 }
140
141 /**
142  * Find IPv6 routing table entry for a given address
143  *
144  * @v netdev            Network device
145  * @v address           IPv6 address
146  * @ret miniroute       Routing table entry, or NULL if not found
147  */
148 static struct ipv6_miniroute * ipv6_miniroute ( struct net_device *netdev,
149                                                 struct in6_addr *address ) {
150         struct ipv6_miniroute *miniroute;
151
152         list_for_each_entry ( miniroute, &ipv6_miniroutes, list ) {
153                 if ( ( miniroute->netdev == netdev ) &&
154                      ipv6_is_on_link ( miniroute, address ) ) {
155                         return miniroute;
156                 }
157         }
158         return NULL;
159 }
160
161 /**
162  * Add IPv6 routing table entry
163  *
164  * @v netdev            Network device
165  * @v address           IPv6 address (or prefix)
166  * @v prefix_len        Prefix length
167  * @v flags             Flags
168  * @ret miniroute       Routing table entry, or NULL on failure
169  */
170 static struct ipv6_miniroute * ipv6_add_miniroute ( struct net_device *netdev,
171                                                     struct in6_addr *address,
172                                                     unsigned int prefix_len,
173                                                     unsigned int flags ) {
174         struct ipv6_miniroute *miniroute;
175         uint8_t *prefix_mask;
176
177         /* Create routing table entry */
178         miniroute = zalloc ( sizeof ( *miniroute ) );
179         if ( ! miniroute )
180                 return NULL;
181         miniroute->netdev = netdev_get ( netdev );
182         memcpy ( &miniroute->address, address, sizeof ( miniroute->address ) );
183         miniroute->prefix_len = prefix_len;
184         assert ( prefix_len <= ( 8 * sizeof ( miniroute->prefix_mask ) ) );
185         for ( prefix_mask = miniroute->prefix_mask.s6_addr ; prefix_len >= 8 ;
186               prefix_mask++, prefix_len -= 8 ) {
187                 *prefix_mask = 0xff;
188         }
189         if ( prefix_len )
190                 *prefix_mask <<= ( 8 - prefix_len );
191         miniroute->flags = flags;
192         list_add ( &miniroute->list, &ipv6_miniroutes );
193         ipv6_dump_miniroute ( miniroute );
194
195         return miniroute;
196 }
197
198 /**
199  * Define IPv6 on-link prefix
200  *
201  * @v netdev            Network device
202  * @v prefix            IPv6 address prefix
203  * @v prefix_len        Prefix length
204  * @v router            Router address (or NULL)
205  * @ret rc              Return status code
206  */
207 int ipv6_set_prefix ( struct net_device *netdev, struct in6_addr *prefix,
208                       unsigned int prefix_len, struct in6_addr *router ) {
209         struct ipv6_miniroute *miniroute;
210         int changed;
211
212         /* Find or create routing table entry */
213         miniroute = ipv6_miniroute ( netdev, prefix );
214         if ( ! miniroute )
215                 miniroute = ipv6_add_miniroute ( netdev, prefix, prefix_len, 0);
216         if ( ! miniroute )
217                 return -ENOMEM;
218
219         /* Record router and add to start or end of list as appropriate */
220         list_del ( &miniroute->list );
221         if ( router ) {
222                 changed = ( ( ! ( miniroute->flags & IPV6_HAS_ROUTER ) ) ||
223                             ( memcmp ( &miniroute->router, router,
224                                        sizeof ( miniroute->router ) ) != 0 ) );
225                 miniroute->flags |= IPV6_HAS_ROUTER;
226                 memcpy ( &miniroute->router, router,
227                          sizeof ( miniroute->router ) );
228                 list_add_tail ( &miniroute->list, &ipv6_miniroutes );
229         } else {
230                 changed = ( miniroute->flags & IPV6_HAS_ROUTER );
231                 miniroute->flags &= ~IPV6_HAS_ROUTER;
232                 list_add ( &miniroute->list, &ipv6_miniroutes );
233         }
234         if ( changed )
235                 ipv6_dump_miniroute ( miniroute );
236
237         return 0;
238 }
239
240 /**
241  * Add IPv6 on-link address
242  *
243  * @v netdev            Network device
244  * @v address           IPv6 address
245  * @ret rc              Return status code
246  *
247  * An on-link prefix for the address must already exist.
248  */
249 int ipv6_set_address ( struct net_device *netdev, struct in6_addr *address ) {
250         struct ipv6_miniroute *miniroute;
251         int changed;
252
253         /* Find routing table entry */
254         miniroute = ipv6_miniroute ( netdev, address );
255         if ( ! miniroute )
256                 return -EADDRNOTAVAIL;
257
258         /* Record address */
259         changed = ( ( ! ( miniroute->flags & IPV6_HAS_ADDRESS ) ) ||
260                     ( memcmp ( &miniroute->address, address,
261                                sizeof ( miniroute->address ) ) != 0 ) );
262         memcpy ( &miniroute->address, address, sizeof ( miniroute->address ) );
263         miniroute->flags |= IPV6_HAS_ADDRESS;
264         if ( changed )
265                 ipv6_dump_miniroute ( miniroute );
266
267         return 0;
268 }
269
270 /**
271  * Perform IPv6 routing
272  *
273  * @v scope_id          Destination address scope ID (for link-local addresses)
274  * @v dest              Final destination address
275  * @ret dest            Next hop destination address
276  * @ret miniroute       Routing table entry to use, or NULL if no route
277  */
278 static struct ipv6_miniroute * ipv6_route ( unsigned int scope_id,
279                                             struct in6_addr **dest ) {
280         struct ipv6_miniroute *miniroute;
281
282         /* Find first usable route in routing table */
283         list_for_each_entry ( miniroute, &ipv6_miniroutes, list ) {
284
285                 /* Skip closed network devices */
286                 if ( ! netdev_is_open ( miniroute->netdev ) )
287                         continue;
288
289                 /* Skip routing table entries with no usable source address */
290                 if ( ! ( miniroute->flags & IPV6_HAS_ADDRESS ) )
291                         continue;
292
293                 if ( IN6_IS_ADDR_LINKLOCAL ( *dest ) ||
294                      IN6_IS_ADDR_MULTICAST ( *dest ) ) {
295
296                         /* If destination is non-global, and the scope ID
297                          * matches this network device, then use this route.
298                          */
299                         if ( miniroute->netdev->index == scope_id )
300                                 return miniroute;
301
302                 } else {
303
304                         /* If destination is an on-link global
305                          * address, then use this route.
306                          */
307                         if ( ipv6_is_on_link ( miniroute, *dest ) )
308                                 return miniroute;
309
310                         /* If destination is an off-link global
311                          * address, and we have a default gateway,
312                          * then use this route.
313                          */
314                         if ( miniroute->flags & IPV6_HAS_ROUTER ) {
315                                 *dest = &miniroute->router;
316                                 return miniroute;
317                         }
318                 }
319         }
320
321         return NULL;
322 }
323
324 /**
325  * Determine transmitting network device
326  *
327  * @v st_dest           Destination network-layer address
328  * @ret netdev          Transmitting network device, or NULL
329  */
330 static struct net_device * ipv6_netdev ( struct sockaddr_tcpip *st_dest ) {
331         struct sockaddr_in6 *sin6_dest = ( ( struct sockaddr_in6 * ) st_dest );
332         struct in6_addr *dest = &sin6_dest->sin6_addr;
333         struct ipv6_miniroute *miniroute;
334
335         /* Find routing table entry */
336         miniroute = ipv6_route ( sin6_dest->sin6_scope_id, &dest );
337         if ( ! miniroute )
338                 return NULL;
339
340         return miniroute->netdev;
341 }
342
343 /**
344  * Check that received options can be safely ignored
345  *
346  * @v iphdr             IPv6 header
347  * @v options           Options extension header
348  * @v len               Maximum length of header
349  * @ret rc              Return status code
350  */
351 static int ipv6_check_options ( struct ipv6_header *iphdr,
352                                 struct ipv6_options_header *options,
353                                 size_t len ) {
354         struct ipv6_option *option = options->options;
355         struct ipv6_option *end = ( ( ( void * ) options ) + len );
356
357         while ( option < end ) {
358                 if ( ! IPV6_CAN_IGNORE_OPT ( option->type ) ) {
359                         DBGC ( ipv6col ( &iphdr->src ), "IPv6 unrecognised "
360                                "option type %#02x:\n", option->type );
361                         DBGC_HDA ( ipv6col ( &iphdr->src ), 0,
362                                    options, len );
363                         return -ENOTSUP_OPT;
364                 }
365                 if ( option->type == IPV6_OPT_PAD1 ) {
366                         option = ( ( ( void * ) option ) + 1 );
367                 } else {
368                         option = ( ( ( void * ) option->value ) + option->len );
369                 }
370         }
371         return 0;
372 }
373
374 /**
375  * Check if fragment matches fragment reassembly buffer
376  *
377  * @v fragment          Fragment reassembly buffer
378  * @v iobuf             I/O buffer
379  * @v hdrlen            Length of non-fragmentable potion of I/O buffer
380  * @ret is_fragment     Fragment matches this reassembly buffer
381  */
382 static int ipv6_is_fragment ( struct fragment *fragment,
383                               struct io_buffer *iobuf, size_t hdrlen ) {
384         struct ipv6_header *frag_iphdr = fragment->iobuf->data;
385         struct ipv6_fragment_header *frag_fhdr =
386                 ( fragment->iobuf->data + fragment->hdrlen -
387                   sizeof ( *frag_fhdr ) );
388         struct ipv6_header *iphdr = iobuf->data;
389         struct ipv6_fragment_header *fhdr =
390                 ( iobuf->data + hdrlen - sizeof ( *fhdr ) );
391
392         return ( ( memcmp ( &iphdr->src, &frag_iphdr->src,
393                             sizeof ( iphdr->src ) ) == 0 ) &&
394                  ( fhdr->ident == frag_fhdr->ident ) );
395 }
396
397 /**
398  * Get fragment offset
399  *
400  * @v iobuf             I/O buffer
401  * @v hdrlen            Length of non-fragmentable potion of I/O buffer
402  * @ret offset          Offset
403  */
404 static size_t ipv6_fragment_offset ( struct io_buffer *iobuf, size_t hdrlen ) {
405         struct ipv6_fragment_header *fhdr =
406                 ( iobuf->data + hdrlen - sizeof ( *fhdr ) );
407
408         return ( ntohs ( fhdr->offset_more ) & IPV6_MASK_OFFSET );
409 }
410
411 /**
412  * Check if more fragments exist
413  *
414  * @v iobuf             I/O buffer
415  * @v hdrlen            Length of non-fragmentable potion of I/O buffer
416  * @ret more_frags      More fragments exist
417  */
418 static int ipv6_more_fragments ( struct io_buffer *iobuf, size_t hdrlen ) {
419         struct ipv6_fragment_header *fhdr =
420                 ( iobuf->data + hdrlen - sizeof ( *fhdr ) );
421
422         return ( fhdr->offset_more & htons ( IPV6_MASK_MOREFRAGS ) );
423 }
424
425 /** Fragment reassembler */
426 static struct fragment_reassembler ipv6_reassembler = {
427         .list = LIST_HEAD_INIT ( ipv6_reassembler.list ),
428         .is_fragment = ipv6_is_fragment,
429         .fragment_offset = ipv6_fragment_offset,
430         .more_fragments = ipv6_more_fragments,
431         .stats = &ipv6_stats,
432 };
433
434 /**
435  * Calculate IPv6 pseudo-header checksum
436  *
437  * @v iphdr             IPv6 header
438  * @v len               Payload length
439  * @v next_header       Next header type
440  * @v csum              Existing checksum
441  * @ret csum            Updated checksum
442  */
443 static uint16_t ipv6_pshdr_chksum ( struct ipv6_header *iphdr, size_t len,
444                                     int next_header, uint16_t csum ) {
445         struct ipv6_pseudo_header pshdr;
446
447         /* Build pseudo-header */
448         memcpy ( &pshdr.src, &iphdr->src, sizeof ( pshdr.src ) );
449         memcpy ( &pshdr.dest, &iphdr->dest, sizeof ( pshdr.dest ) );
450         pshdr.len = htonl ( len );
451         memset ( pshdr.zero, 0, sizeof ( pshdr.zero ) );
452         pshdr.next_header = next_header;
453
454         /* Update the checksum value */
455         return tcpip_continue_chksum ( csum, &pshdr, sizeof ( pshdr ) );
456 }
457
458 /**
459  * Transmit IPv6 packet
460  *
461  * @v iobuf             I/O buffer
462  * @v tcpip             Transport-layer protocol
463  * @v st_src            Source network-layer address
464  * @v st_dest           Destination network-layer address
465  * @v netdev            Network device to use if no route found, or NULL
466  * @v trans_csum        Transport-layer checksum to complete, or NULL
467  * @ret rc              Status
468  *
469  * This function expects a transport-layer segment and prepends the
470  * IPv6 header
471  */
472 static int ipv6_tx ( struct io_buffer *iobuf,
473                      struct tcpip_protocol *tcpip_protocol,
474                      struct sockaddr_tcpip *st_src,
475                      struct sockaddr_tcpip *st_dest,
476                      struct net_device *netdev,
477                      uint16_t *trans_csum ) {
478         struct sockaddr_in6 *sin6_src = ( ( struct sockaddr_in6 * ) st_src );
479         struct sockaddr_in6 *sin6_dest = ( ( struct sockaddr_in6 * ) st_dest );
480         struct ipv6_miniroute *miniroute;
481         struct ipv6_header *iphdr;
482         struct in6_addr *src = NULL;
483         struct in6_addr *next_hop;
484         uint8_t ll_dest_buf[MAX_LL_ADDR_LEN];
485         const void *ll_dest;
486         size_t len;
487         int rc;
488
489         /* Update statistics */
490         ipv6_stats.out_requests++;
491
492         /* Fill up the IPv6 header, except source address */
493         len = iob_len ( iobuf );
494         iphdr = iob_push ( iobuf, sizeof ( *iphdr ) );
495         memset ( iphdr, 0, sizeof ( *iphdr ) );
496         iphdr->ver_tc_label = htonl ( IPV6_VER );
497         iphdr->len = htons ( len );
498         iphdr->next_header = tcpip_protocol->tcpip_proto;
499         iphdr->hop_limit = IPV6_HOP_LIMIT;
500         memcpy ( &iphdr->dest, &sin6_dest->sin6_addr, sizeof ( iphdr->dest ) );
501
502         /* Use routing table to identify next hop and transmitting netdev */
503         next_hop = &iphdr->dest;
504         if ( ( miniroute = ipv6_route ( sin6_dest->sin6_scope_id,
505                                         &next_hop ) ) != NULL ) {
506                 src = &miniroute->address;
507                 netdev = miniroute->netdev;
508         }
509         if ( ! netdev ) {
510                 DBGC ( ipv6col ( &iphdr->dest ), "IPv6 has no route to %s\n",
511                        inet6_ntoa ( &iphdr->dest ) );
512                 ipv6_stats.out_no_routes++;
513                 rc = -ENETUNREACH;
514                 goto err;
515         }
516         if ( sin6_src && ! IN6_IS_ADDR_UNSPECIFIED ( &sin6_src->sin6_addr ) )
517                 src = &sin6_src->sin6_addr;
518         if ( src )
519                 memcpy ( &iphdr->src, src, sizeof ( iphdr->src ) );
520
521         /* Fix up checksums */
522         if ( trans_csum ) {
523                 *trans_csum = ipv6_pshdr_chksum ( iphdr, len,
524                                                   tcpip_protocol->tcpip_proto,
525                                                   *trans_csum );
526         }
527
528         /* Print IPv6 header for debugging */
529         DBGC2 ( ipv6col ( &iphdr->dest ), "IPv6 TX %s->",
530                 inet6_ntoa ( &iphdr->src ) );
531         DBGC2 ( ipv6col ( &iphdr->dest ), "%s len %zd next %d\n",
532                 inet6_ntoa ( &iphdr->dest ), len, iphdr->next_header );
533
534         /* Calculate link-layer destination address, if possible */
535         if ( IN6_IS_ADDR_MULTICAST ( next_hop ) ) {
536                 /* Multicast address */
537                 ipv6_stats.out_mcast_pkts++;
538                 if ( ( rc = netdev->ll_protocol->mc_hash ( AF_INET6, next_hop,
539                                                            ll_dest_buf ) ) !=0){
540                         DBGC ( ipv6col ( &iphdr->dest ), "IPv6 could not hash "
541                                "multicast %s: %s\n", inet6_ntoa ( next_hop ),
542                                strerror ( rc ) );
543                         goto err;
544                 }
545                 ll_dest = ll_dest_buf;
546         } else {
547                 /* Unicast address */
548                 ll_dest = NULL;
549         }
550
551         /* Update statistics */
552         ipv6_stats.out_transmits++;
553         ipv6_stats.out_octets += iob_len ( iobuf );
554
555         /* Hand off to link layer (via NDP if applicable) */
556         if ( ll_dest ) {
557                 if ( ( rc = net_tx ( iobuf, netdev, &ipv6_protocol, ll_dest,
558                                      netdev->ll_addr ) ) != 0 ) {
559                         DBGC ( ipv6col ( &iphdr->dest ), "IPv6 could not "
560                                "transmit packet via %s: %s\n",
561                                netdev->name, strerror ( rc ) );
562                         return rc;
563                 }
564         } else {
565                 if ( ( rc = ndp_tx ( iobuf, netdev, next_hop, &iphdr->src,
566                                      netdev->ll_addr ) ) != 0 ) {
567                         DBGC ( ipv6col ( &iphdr->dest ), "IPv6 could not "
568                                "transmit packet via %s: %s\n",
569                                netdev->name, strerror ( rc ) );
570                         return rc;
571                 }
572         }
573
574         return 0;
575
576  err:
577         free_iob ( iobuf );
578         return rc;
579 }
580
581 /**
582  * Process incoming IPv6 packets
583  *
584  * @v iobuf             I/O buffer
585  * @v netdev            Network device
586  * @v ll_dest           Link-layer destination address
587  * @v ll_source         Link-layer destination source
588  * @v flags             Packet flags
589  * @ret rc              Return status code
590  *
591  * This function expects an IPv6 network datagram. It processes the
592  * headers and sends it to the transport layer.
593  */
594 static int ipv6_rx ( struct io_buffer *iobuf, struct net_device *netdev,
595                      const void *ll_dest __unused,
596                      const void *ll_source __unused,
597                      unsigned int flags __unused ) {
598         struct ipv6_header *iphdr = iobuf->data;
599         union ipv6_extension_header *ext;
600         union {
601                 struct sockaddr_in6 sin6;
602                 struct sockaddr_tcpip st;
603         } src, dest;
604         uint16_t pshdr_csum;
605         size_t len;
606         size_t hdrlen;
607         size_t extlen;
608         int this_header;
609         int next_header;
610         int rc;
611
612         /* Update statistics */
613         ipv6_stats.in_receives++;
614         ipv6_stats.in_octets += iob_len ( iobuf );
615         if ( flags & LL_BROADCAST ) {
616                 ipv6_stats.in_bcast_pkts++;
617         } else if ( flags & LL_MULTICAST ) {
618                 ipv6_stats.in_mcast_pkts++;
619         }
620
621         /* Sanity check the IPv6 header */
622         if ( iob_len ( iobuf ) < sizeof ( *iphdr ) ) {
623                 DBGC ( ipv6col ( &iphdr->src ), "IPv6 packet too short at %zd "
624                        "bytes (min %zd bytes)\n", iob_len ( iobuf ),
625                        sizeof ( *iphdr ) );
626                 rc = -EINVAL_LEN;
627                 goto err_header;
628         }
629         if ( ( iphdr->ver_tc_label & htonl ( IPV6_MASK_VER ) ) !=
630              htonl ( IPV6_VER ) ) {
631                 DBGC ( ipv6col ( &iphdr->src ), "IPv6 version %#08x not "
632                        "supported\n", ntohl ( iphdr->ver_tc_label ) );
633                 rc = -ENOTSUP_VER;
634                 goto err_header;
635         }
636
637         /* Truncate packet to specified length */
638         len = ntohs ( iphdr->len );
639         if ( len > iob_len ( iobuf ) ) {
640                 DBGC ( ipv6col ( &iphdr->src ), "IPv6 length too long at %zd "
641                        "bytes (packet is %zd bytes)\n", len, iob_len ( iobuf ));
642                 ipv6_stats.in_truncated_pkts++;
643                 rc = -EINVAL_LEN;
644                 goto err_other;
645         }
646         iob_unput ( iobuf, ( iob_len ( iobuf ) - len - sizeof ( *iphdr ) ) );
647         hdrlen = sizeof ( *iphdr );
648
649         /* Print IPv6 header for debugging */
650         DBGC2 ( ipv6col ( &iphdr->src ), "IPv6 RX %s<-",
651                 inet6_ntoa ( &iphdr->dest ) );
652         DBGC2 ( ipv6col ( &iphdr->src ), "%s len %zd next %d\n",
653                 inet6_ntoa ( &iphdr->src ), len, iphdr->next_header );
654
655         /* Discard unicast packets not destined for us */
656         if ( ( ! ( flags & LL_MULTICAST ) ) &&
657              ( ! ipv6_has_addr ( netdev, &iphdr->dest ) ) ) {
658                 DBGC ( ipv6col ( &iphdr->src ), "IPv6 discarding non-local "
659                        "unicast packet for %s\n", inet6_ntoa ( &iphdr->dest ) );
660                 ipv6_stats.in_addr_errors++;
661                 rc = -EPIPE;
662                 goto err_other;
663         }
664
665         /* Process any extension headers */
666         next_header = iphdr->next_header;
667         while ( 1 ) {
668
669                 /* Extract extension header */
670                 this_header = next_header;
671                 ext = ( iobuf->data + hdrlen );
672                 extlen = sizeof ( ext->pad );
673                 if ( iob_len ( iobuf ) < ( hdrlen + extlen ) ) {
674                         DBGC ( ipv6col ( &iphdr->src ), "IPv6 too short for "
675                                "extension header type %d at %zd bytes (min "
676                                "%zd bytes)\n", this_header,
677                                ( iob_len ( iobuf ) - hdrlen ), extlen );
678                         rc = -EINVAL_LEN;
679                         goto err_header;
680                 }
681
682                 /* Determine size of extension header (if applicable) */
683                 if ( ( this_header == IPV6_HOPBYHOP ) ||
684                      ( this_header == IPV6_DESTINATION ) ||
685                      ( this_header == IPV6_ROUTING ) ) {
686                         /* Length field is present */
687                         extlen += ext->common.len;
688                 } else if ( this_header == IPV6_FRAGMENT ) {
689                         /* Length field is reserved and ignored (RFC2460) */
690                 } else {
691                         /* Not an extension header; assume rest is payload */
692                         break;
693                 }
694                 if ( iob_len ( iobuf ) < ( hdrlen + extlen ) ) {
695                         DBGC ( ipv6col ( &iphdr->src ), "IPv6 too short for "
696                                "extension header type %d at %zd bytes (min "
697                                "%zd bytes)\n", this_header,
698                                ( iob_len ( iobuf ) - hdrlen ), extlen );
699                         rc = -EINVAL_LEN;
700                         goto err_header;
701                 }
702                 hdrlen += extlen;
703                 next_header = ext->common.next_header;
704                 DBGC2 ( ipv6col ( &iphdr->src ), "IPv6 RX %s<-",
705                         inet6_ntoa ( &iphdr->dest ) );
706                 DBGC2 ( ipv6col ( &iphdr->src ), "%s ext type %d len %zd next "
707                         "%d\n", inet6_ntoa ( &iphdr->src ), this_header,
708                         extlen, next_header );
709
710                 /* Process this extension header */
711                 if ( ( this_header == IPV6_HOPBYHOP ) ||
712                      ( this_header == IPV6_DESTINATION ) ) {
713
714                         /* Check that all options can be ignored */
715                         if ( ( rc = ipv6_check_options ( iphdr, &ext->options,
716                                                          extlen ) ) != 0 )
717                                 goto err_header;
718
719                 } else if ( this_header == IPV6_FRAGMENT ) {
720
721                         /* Reassemble fragments */
722                         iobuf = fragment_reassemble ( &ipv6_reassembler, iobuf,
723                                                       &hdrlen );
724                         if ( ! iobuf )
725                                 return 0;
726                         iphdr = iobuf->data;
727                 }
728         }
729
730         /* Construct socket address, calculate pseudo-header checksum,
731          * and hand off to transport layer
732          */
733         memset ( &src, 0, sizeof ( src ) );
734         src.sin6.sin6_family = AF_INET6;
735         memcpy ( &src.sin6.sin6_addr, &iphdr->src,
736                  sizeof ( src.sin6.sin6_addr ) );
737         src.sin6.sin6_scope_id = netdev->index;
738         memset ( &dest, 0, sizeof ( dest ) );
739         dest.sin6.sin6_family = AF_INET6;
740         memcpy ( &dest.sin6.sin6_addr, &iphdr->dest,
741                  sizeof ( dest.sin6.sin6_addr ) );
742         dest.sin6.sin6_scope_id = netdev->index;
743         iob_pull ( iobuf, hdrlen );
744         pshdr_csum = ipv6_pshdr_chksum ( iphdr, iob_len ( iobuf ),
745                                          next_header, TCPIP_EMPTY_CSUM );
746         if ( ( rc = tcpip_rx ( iobuf, netdev, next_header, &src.st, &dest.st,
747                                pshdr_csum, &ipv6_stats ) ) != 0 ) {
748                 DBGC ( ipv6col ( &src.sin6.sin6_addr ), "IPv6 received packet "
749                                 "rejected by stack: %s\n", strerror ( rc ) );
750                 return rc;
751         }
752
753         return 0;
754
755  err_header:
756         ipv6_stats.in_hdr_errors++;
757  err_other:
758         free_iob ( iobuf );
759         return rc;
760 }
761
762 /**
763  * Parse IPv6 address
764  *
765  * @v string            IPv6 address string
766  * @ret in              IPv6 address to fill in
767  * @ret rc              Return status code
768  */
769 int inet6_aton ( const char *string, struct in6_addr *in ) {
770         uint16_t *word = in->s6_addr16;
771         uint16_t *end = ( word + ( sizeof ( in->s6_addr16 ) /
772                                    sizeof ( in->s6_addr16[0] ) ) );
773         uint16_t *pad = NULL;
774         const char *nptr = string;
775         char *endptr;
776         unsigned long value;
777         size_t pad_len;
778         size_t move_len;
779
780         /* Parse string */
781         while ( 1 ) {
782
783                 /* Parse current word */
784                 value = strtoul ( nptr, &endptr, 16 );
785                 if ( value > 0xffff ) {
786                         DBG ( "IPv6 invalid word value %#lx in \"%s\"\n",
787                               value, string );
788                         return -EINVAL;
789                 }
790                 *(word++) = htons ( value );
791
792                 /* Parse separator */
793                 if ( ! *endptr )
794                         break;
795                 if ( *endptr != ':' ) {
796                         DBG ( "IPv6 invalid separator '%c' in \"%s\"\n",
797                               *endptr, string );
798                         return -EINVAL;
799                 }
800                 if ( ( endptr == nptr ) && ( nptr != string ) ) {
801                         if ( pad ) {
802                                 DBG ( "IPv6 invalid multiple \"::\" in "
803                                       "\"%s\"\n", string );
804                                 return -EINVAL;
805                         }
806                         pad = word;
807                 }
808                 nptr = ( endptr + 1 );
809
810                 /* Check for overrun */
811                 if ( word == end ) {
812                         DBG ( "IPv6 too many words in \"%s\"\n", string );
813                         return -EINVAL;
814                 }
815         }
816
817         /* Insert padding if specified */
818         if ( pad ) {
819                 move_len = ( ( ( void * ) word ) - ( ( void * ) pad ) );
820                 pad_len = ( ( ( void * ) end ) - ( ( void * ) word ) );
821                 memmove ( ( ( ( void * ) pad ) + pad_len ), pad, move_len );
822                 memset ( pad, 0, pad_len );
823         } else if ( word != end ) {
824                 DBG ( "IPv6 underlength address \"%s\"\n", string );
825                 return -EINVAL;
826         }
827
828         return 0;
829 }
830
831 /**
832  * Convert IPv6 address to standard notation
833  *
834  * @v in                IPv6 address
835  * @ret string          IPv6 address string in canonical format
836  *
837  * RFC5952 defines the canonical format for IPv6 textual representation.
838  */
839 char * inet6_ntoa ( const struct in6_addr *in ) {
840         static char buf[41]; /* ":xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx" */
841         char *out = buf;
842         char *longest_start = NULL;
843         char *start = NULL;
844         int longest_len = 1;
845         int len = 0;
846         char *dest;
847         unsigned int i;
848         uint16_t value;
849
850         /* Format address, keeping track of longest run of zeros */
851         for ( i = 0 ; i < ( sizeof ( in->s6_addr16 ) /
852                             sizeof ( in->s6_addr16[0] ) ) ; i++ ) {
853                 value = ntohs ( in->s6_addr16[i] );
854                 if ( value == 0 ) {
855                         if ( len++ == 0 )
856                                 start = out;
857                         if ( len > longest_len ) {
858                                 longest_start = start;
859                                 longest_len = len;
860                         }
861                 } else {
862                         len = 0;
863                 }
864                 out += sprintf ( out, ":%x", value );
865         }
866
867         /* Abbreviate longest run of zeros, if applicable */
868         if ( longest_start ) {
869                 dest = strcpy ( ( longest_start + 1 ),
870                                 ( longest_start + ( 2 * longest_len ) ) );
871                 if ( dest[0] == '\0' )
872                         dest[1] = '\0';
873                 dest[0] = ':';
874         }
875         return ( ( longest_start == buf ) ? buf : ( buf + 1 ) );
876 }
877
878 /**
879  * Transcribe IPv6 address
880  *
881  * @v net_addr          IPv6 address
882  * @ret string          IPv6 address in standard notation
883  *
884  */
885 static const char * ipv6_ntoa ( const void *net_addr ) {
886         return inet6_ntoa ( net_addr );
887 }
888
889 /**
890  * Transcribe IPv6 socket address
891  *
892  * @v sa                Socket address
893  * @ret string          Socket address in standard notation
894  */
895 static const char * ipv6_sock_ntoa ( struct sockaddr *sa ) {
896         static char buf[ 39 /* "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx" */ +
897                          1 /* "%" */ + NETDEV_NAME_LEN + 1 /* NUL */ ];
898         struct sockaddr_in6 *sin6 = ( ( struct sockaddr_in6 * ) sa );
899         struct in6_addr *in = &sin6->sin6_addr;
900         struct net_device *netdev;
901         const char *netdev_name;
902
903         /* Identify network device, if applicable */
904         if ( IN6_IS_ADDR_LINKLOCAL ( in ) || IN6_IS_ADDR_MULTICAST ( in ) ) {
905                 netdev = find_netdev_by_index ( sin6->sin6_scope_id );
906                 netdev_name = ( netdev ? netdev->name : "UNKNOWN" );
907         } else {
908                 netdev_name = NULL;
909         }
910
911         /* Format socket address */
912         snprintf ( buf, sizeof ( buf ), "%s%s%s", inet6_ntoa ( in ),
913                    ( netdev_name ? "%" : "" ),
914                    ( netdev_name ? netdev_name : "" ) );
915         return buf;
916 }
917
918 /**
919  * Parse IPv6 socket address
920  *
921  * @v string            Socket address string
922  * @v sa                Socket address to fill in
923  * @ret rc              Return status code
924  */
925 static int ipv6_sock_aton ( const char *string, struct sockaddr *sa ) {
926         struct sockaddr_in6 *sin6 = ( ( struct sockaddr_in6 * ) sa );
927         struct in6_addr in;
928         struct net_device *netdev;
929         size_t len;
930         char *tmp;
931         char *in_string;
932         char *netdev_string;
933         int rc;
934
935         /* Create modifiable copy of string */
936         tmp = strdup ( string );
937         if ( ! tmp ) {
938                 rc = -ENOMEM;
939                 goto err_alloc;
940         }
941         in_string = tmp;
942
943         /* Strip surrounding "[...]", if present */
944         len = strlen ( in_string );
945         if ( ( in_string[0] == '[' ) && ( in_string[ len - 1 ] == ']' ) ) {
946                 in_string[ len - 1 ] = '\0';
947                 in_string++;
948         }
949
950         /* Split at network device name, if present */
951         netdev_string = strchr ( in_string, '%' );
952         if ( netdev_string )
953                 *(netdev_string++) = '\0';
954
955         /* Parse IPv6 address portion */
956         if ( ( rc = inet6_aton ( in_string, &in ) ) != 0 )
957                 goto err_inet6_aton;
958
959         /* Parse network device name, if present */
960         if ( netdev_string ) {
961                 netdev = find_netdev ( netdev_string );
962                 if ( ! netdev ) {
963                         rc = -ENODEV;
964                         goto err_find_netdev;
965                 }
966                 sin6->sin6_scope_id = netdev->index;
967         }
968
969         /* Copy IPv6 address portion to socket address */
970         memcpy ( &sin6->sin6_addr, &in, sizeof ( sin6->sin6_addr ) );
971
972  err_find_netdev:
973  err_inet6_aton:
974         free ( tmp );
975  err_alloc:
976         return rc;
977 }
978
979 /** IPv6 protocol */
980 struct net_protocol ipv6_protocol __net_protocol = {
981         .name = "IPv6",
982         .net_proto = htons ( ETH_P_IPV6 ),
983         .net_addr_len = sizeof ( struct in6_addr ),
984         .rx = ipv6_rx,
985         .ntoa = ipv6_ntoa,
986 };
987
988 /** IPv6 TCPIP net protocol */
989 struct tcpip_net_protocol ipv6_tcpip_protocol __tcpip_net_protocol = {
990         .name = "IPv6",
991         .sa_family = AF_INET6,
992         .header_len = sizeof ( struct ipv6_header ),
993         .tx = ipv6_tx,
994         .netdev = ipv6_netdev,
995 };
996
997 /** IPv6 socket address converter */
998 struct sockaddr_converter ipv6_sockaddr_converter __sockaddr_converter = {
999         .family = AF_INET6,
1000         .ntoa = ipv6_sock_ntoa,
1001         .aton = ipv6_sock_aton,
1002 };
1003
1004 /**
1005  * Parse IPv6 address setting value
1006  *
1007  * @v type              Setting type
1008  * @v value             Formatted setting value
1009  * @v buf               Buffer to contain raw value
1010  * @v len               Length of buffer
1011  * @ret len             Length of raw value, or negative error
1012  */
1013 int parse_ipv6_setting ( const struct setting_type *type __unused,
1014                          const char *value, void *buf, size_t len ) {
1015         struct in6_addr ipv6;
1016         int rc;
1017
1018         /* Parse IPv6 address */
1019         if ( ( rc = inet6_aton ( value, &ipv6 ) ) != 0 )
1020                 return rc;
1021
1022         /* Copy to buffer */
1023         if ( len > sizeof ( ipv6 ) )
1024                 len = sizeof ( ipv6 );
1025         memcpy ( buf, &ipv6, len );
1026
1027         return ( sizeof ( ipv6 ) );
1028 }
1029
1030 /**
1031  * Format IPv6 address setting value
1032  *
1033  * @v type              Setting type
1034  * @v raw               Raw setting value
1035  * @v raw_len           Length of raw setting value
1036  * @v buf               Buffer to contain formatted value
1037  * @v len               Length of buffer
1038  * @ret len             Length of formatted value, or negative error
1039  */
1040 int format_ipv6_setting ( const struct setting_type *type __unused,
1041                           const void *raw, size_t raw_len, char *buf,
1042                           size_t len ) {
1043         const struct in6_addr *ipv6 = raw;
1044
1045         if ( raw_len < sizeof ( *ipv6 ) )
1046                 return -EINVAL;
1047         return snprintf ( buf, len, "%s", inet6_ntoa ( ipv6 ) );
1048 }
1049
1050 /**
1051  * Create IPv6 network device
1052  *
1053  * @v netdev            Network device
1054  * @ret rc              Return status code
1055  */
1056 static int ipv6_probe ( struct net_device *netdev ) {
1057         struct ipv6_miniroute *miniroute;
1058         struct in6_addr address;
1059         int prefix_len;
1060         int rc;
1061
1062         /* Construct link-local address from EUI-64 as per RFC 2464 */
1063         memset ( &address, 0, sizeof ( address ) );
1064         prefix_len = ipv6_link_local ( &address, netdev );
1065         if ( prefix_len < 0 ) {
1066                 rc = prefix_len;
1067                 DBGC ( netdev, "IPv6 %s could not construct link-local "
1068                        "address: %s\n", netdev->name, strerror ( rc ) );
1069                 return rc;
1070         }
1071
1072         /* Create link-local address for this network device */
1073         miniroute = ipv6_add_miniroute ( netdev, &address, prefix_len,
1074                                          IPV6_HAS_ADDRESS );
1075         if ( ! miniroute )
1076                 return -ENOMEM;
1077
1078         return 0;
1079 }
1080
1081 /**
1082  * Destroy IPv6 network device
1083  *
1084  * @v netdev            Network device
1085  */
1086 static void ipv6_remove ( struct net_device *netdev ) {
1087         struct ipv6_miniroute *miniroute;
1088         struct ipv6_miniroute *tmp;
1089
1090         /* Delete all miniroutes for this network device */
1091         list_for_each_entry_safe ( miniroute, tmp, &ipv6_miniroutes, list ) {
1092                 if ( miniroute->netdev == netdev ) {
1093                         netdev_put ( miniroute->netdev );
1094                         list_del ( &miniroute->list );
1095                         free ( miniroute );
1096                 }
1097         }
1098 }
1099
1100 /** IPv6 network device driver */
1101 struct net_driver ipv6_driver __net_driver = {
1102         .name = "IPv6",
1103         .probe = ipv6_probe,
1104         .remove = ipv6_remove,
1105 };
1106
1107 /* Drag in ICMPv6 */
1108 REQUIRE_OBJECT ( icmpv6 );
1109
1110 /* Drag in NDP */
1111 REQUIRE_OBJECT ( ndp );