diff --git a/sbin/nandfs/Makefile b/sbin/nandfs/Makefile deleted file mode 100644 index 8a2c22336f..0000000000 --- a/sbin/nandfs/Makefile +++ /dev/null @@ -1,9 +0,0 @@ - -PACKAGE=nandfs -PROG= nandfs -SRCS= nandfs.c lssnap.c mksnap.c rmsnap.c -MAN= nandfs.8 - -LIBADD= nandfs - -.include diff --git a/sbin/nandfs/Makefile.depend b/sbin/nandfs/Makefile.depend deleted file mode 100644 index 0d67a9f576..0000000000 --- a/sbin/nandfs/Makefile.depend +++ /dev/null @@ -1,17 +0,0 @@ -# Autogenerated - do NOT edit! - -DIRDEPS = \ - gnu/lib/csu \ - include \ - include/xlocale \ - lib/${CSU_DIR} \ - lib/libc \ - lib/libcompiler_rt \ - lib/libnandfs \ - - -.include - -.if ${DEP_RELDIR} == ${_DEP_RELDIR} -# local dependencies - needed for -jN in clean tree -.endif diff --git a/sbin/nandfs/lssnap.c b/sbin/nandfs/lssnap.c deleted file mode 100644 index 68088e3b07..0000000000 --- a/sbin/nandfs/lssnap.c +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2012 The FreeBSD Foundation - * All rights reserved. - * - * This software was developed by Semihalf under sponsorship - * from the FreeBSD Foundation. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include "nandfs.h" - -#define NCPINFO 512 - -static void -lssnap_usage(void) -{ - - fprintf(stderr, "usage:\n"); - fprintf(stderr, "\tlssnap node\n"); -} - -static void -print_cpinfo(struct nandfs_cpinfo *cpinfo) -{ - struct tm tm; - time_t t; - char timebuf[128]; - - t = (time_t)cpinfo->nci_create; - localtime_r(&t, &tm); - strftime(timebuf, sizeof(timebuf), "%F %T", &tm); - - printf("%20llu %s\n", (unsigned long long)cpinfo->nci_cno, timebuf); -} - -int -nandfs_lssnap(int argc, char **argv) -{ - struct nandfs_cpinfo *cpinfos; - struct nandfs fs; - uint64_t next; - int error, nsnap, i; - - if (argc != 1) { - lssnap_usage(); - return (EX_USAGE); - } - - cpinfos = malloc(sizeof(*cpinfos) * NCPINFO); - if (cpinfos == NULL) { - fprintf(stderr, "cannot allocate memory\n"); - return (-1); - } - - nandfs_init(&fs, argv[0]); - error = nandfs_open(&fs); - if (error == -1) { - fprintf(stderr, "nandfs_open: %s\n", nandfs_errmsg(&fs)); - goto out; - } - - for (next = 1; next != 0; next = cpinfos[nsnap - 1].nci_next) { - nsnap = nandfs_get_snap(&fs, next, cpinfos, NCPINFO); - if (nsnap < 1) - break; - - for (i = 0; i < nsnap; i++) - print_cpinfo(&cpinfos[i]); - } - - if (nsnap == -1) - fprintf(stderr, "nandfs_get_snap: %s\n", nandfs_errmsg(&fs)); - -out: - nandfs_close(&fs); - nandfs_destroy(&fs); - free(cpinfos); - return (error); -} diff --git a/sbin/nandfs/mksnap.c b/sbin/nandfs/mksnap.c deleted file mode 100644 index 6c54be83e8..0000000000 --- a/sbin/nandfs/mksnap.c +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2012 The FreeBSD Foundation - * All rights reserved. - * - * This software was developed by Semihalf under sponsorship - * from the FreeBSD Foundation. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include -#include - -#include -#include - -#include -#include - -#include "nandfs.h" - -static void -mksnap_usage(void) -{ - - fprintf(stderr, "usage:\n"); - fprintf(stderr, "\tmksnap node\n"); -} - -int -nandfs_mksnap(int argc, char **argv) -{ - struct nandfs fs; - uint64_t cpno; - int error; - - if (argc != 1) { - mksnap_usage(); - return (EX_USAGE); - } - - nandfs_init(&fs, argv[0]); - error = nandfs_open(&fs); - if (error == -1) { - fprintf(stderr, "nandfs_open: %s\n", nandfs_errmsg(&fs)); - goto out; - } - - error = nandfs_make_snap(&fs, &cpno); - if (error == -1) - fprintf(stderr, "nandfs_make_snap: %s\n", nandfs_errmsg(&fs)); - else - printf("%jd\n", cpno); - -out: - nandfs_close(&fs); - nandfs_destroy(&fs); - return (error); -} diff --git a/sbin/nandfs/nandfs.8 b/sbin/nandfs/nandfs.8 deleted file mode 100644 index 8851df2e8a..0000000000 --- a/sbin/nandfs/nandfs.8 +++ /dev/null @@ -1,78 +0,0 @@ -.\" -.\" Copyright (c) 2012 The FreeBSD Foundation -.\" All rights reserved. -.\" -.\" This software was developed by Semihalf under sponsorship -.\" from the FreeBSD Foundation. -.\" -.\" Redistribution and use in source and binary forms, with or without -.\" modification, are permitted provided that the following conditions -.\" are met: -.\" -.\" 1. Redistributions of source code must retain the above copyright -.\" notice, this list of conditions and the following disclaimer. -.\" 2. Redistributions in binary form must reproduce the above copyright -.\" notice, this list of conditions and the following disclaimer in the -.\" documentation and/or other materials provided with the distribution. -.\" -.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -.\" SUCH DAMAGE. -.\" -.\" -.Dd September 10, 2016 -.Dt NANDFS 8 -.Os -.Sh NAME -.Nm nandfs -.Nd manage mounted NAND FS -.Sh SYNOPSIS -.Nm -.Cm lssnap -.Ar node -.Nm -.Cm mksnap -.Ar node -.Nm -.Cm rmsnap -.Ar snapshot node -.Sh DESCRIPTION -The -.Nm -utility allows the management of snapshots on a mounted NAND FS. -.Sh EXAMPLES -Create a snapshot of filesystem mounted on -.Em /nand . -.Bd -literal -offset 2n -.Li # Ic nandfs mksnap /nand -1 -.Ed -.Pp -List snapshots of filesystem mounted on -.Em /nand . -.Bd -literal -offset 2n -.Li # Ic nandfs lssnap /nand -1 2012-02-28 18:49:45 ss 138 2 -.Ed -.Pp -Remove snapshot 1 of filesystem mounted on -.Em /nand . -.Bd -literal -offset 2n -.Li # Ic nandfs rmsnap 1 /nand -.Ed -.Sh HISTORY -The -.Nm -utility appeared in -.Fx 10.0 . -.Sh AUTHORS -This utility and manual page were written by -.An Mateusz Guzik . diff --git a/sbin/nandfs/nandfs.c b/sbin/nandfs/nandfs.c deleted file mode 100644 index bd77dd50d5..0000000000 --- a/sbin/nandfs/nandfs.c +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2012 The FreeBSD Foundation - * All rights reserved. - * - * This software was developed by Semihalf under sponsorship - * from the FreeBSD Foundation. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include - -#include -#include -#include -#include -#include - -#include "nandfs.h" - -static void -usage(void) -{ - - fprintf(stderr, "usage: nandfs [lssnap | mksnap | rmsnap ] " - "node\n"); - exit(1); -} - -int -main(int argc, char **argv) -{ - int error = 0; - char *cmd; - - if (argc < 2) - usage(); - - cmd = argv[1]; - argc -= 2; - argv += 2; - - if (strcmp(cmd, "lssnap") == 0) - error = nandfs_lssnap(argc, argv); - else if (strcmp(cmd, "mksnap") == 0) - error = nandfs_mksnap(argc, argv); - else if (strcmp(cmd, "rmsnap") == 0) - error = nandfs_rmsnap(argc, argv); - else - usage(); - - return (error); -} diff --git a/sbin/nandfs/nandfs.h b/sbin/nandfs/nandfs.h deleted file mode 100644 index 89cc24ae29..0000000000 --- a/sbin/nandfs/nandfs.h +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2012 The FreeBSD Foundation - * All rights reserved. - * - * This software was developed by Semihalf under sponsorship - * from the FreeBSD Foundation. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * $FreeBSD: stable/11/sbin/nandfs/nandfs.h 330449 2018-03-05 07:26:05Z eadler $ - */ - -#ifndef NANDFS_H -#define NANDFS_H - -int nandfs_lssnap(int, char **); -int nandfs_mksnap(int, char **); -int nandfs_rmsnap(int, char **); - -#endif /* !NANDFS_H */ diff --git a/sbin/nandfs/rmsnap.c b/sbin/nandfs/rmsnap.c deleted file mode 100644 index cd97fdddc9..0000000000 --- a/sbin/nandfs/rmsnap.c +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2012 The FreeBSD Foundation - * All rights reserved. - * - * This software was developed by Semihalf under sponsorship - * from the FreeBSD Foundation. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include "nandfs.h" - -static void -rmsnap_usage(void) -{ - - fprintf(stderr, "usage:\n"); - fprintf(stderr, "\trmsnap snap node\n"); -} - -int -nandfs_rmsnap(int argc, char **argv) -{ - struct nandfs fs; - uint64_t cpno; - int error; - - if (argc != 2) { - rmsnap_usage(); - return (EX_USAGE); - } - - cpno = strtoll(argv[0], (char **)NULL, 10); - if (cpno == 0) { - fprintf(stderr, "%s must be a number greater than 0\n", - argv[0]); - return (EX_USAGE); - } - - nandfs_init(&fs, argv[1]); - error = nandfs_open(&fs); - if (error == -1) { - fprintf(stderr, "nandfs_open: %s\n", nandfs_errmsg(&fs)); - goto out; - } - - error = nandfs_delete_snap(&fs, cpno); - if (error == -1) - fprintf(stderr, "nandfs_delete_snap: %s\n", nandfs_errmsg(&fs)); - -out: - nandfs_close(&fs); - nandfs_destroy(&fs); - return (error); -} diff --git a/sbin/newfs_nandfs/Makefile b/sbin/newfs_nandfs/Makefile deleted file mode 100644 index 8cbe6ee5e4..0000000000 --- a/sbin/newfs_nandfs/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -# $FreeBSD: stable/11/sbin/newfs_nandfs/Makefile 298107 2016-04-16 07:45:30Z gjb $ - -PACKAGE=nandfs -PROG= newfs_nandfs -MAN= newfs_nandfs.8 - -LIBADD= geom - -.include diff --git a/sbin/newfs_nandfs/Makefile.depend b/sbin/newfs_nandfs/Makefile.depend deleted file mode 100644 index b90b813c26..0000000000 --- a/sbin/newfs_nandfs/Makefile.depend +++ /dev/null @@ -1,19 +0,0 @@ -# Autogenerated - do NOT edit! - -DIRDEPS = \ - gnu/lib/csu \ - include \ - include/xlocale \ - lib/${CSU_DIR} \ - lib/libc \ - lib/libcompiler_rt \ - lib/libexpat \ - lib/libgeom \ - lib/libsbuf \ - - -.include - -.if ${DEP_RELDIR} == ${_DEP_RELDIR} -# local dependencies - needed for -jN in clean tree -.endif diff --git a/sbin/newfs_nandfs/newfs_nandfs.8 b/sbin/newfs_nandfs/newfs_nandfs.8 deleted file mode 100644 index be200769f1..0000000000 --- a/sbin/newfs_nandfs/newfs_nandfs.8 +++ /dev/null @@ -1,74 +0,0 @@ -.\" -.\" Copyright (c) 2010 Semihalf -.\" All rights reserved. -.\" -.\" Redistribution and use in source and binary forms, with or without -.\" modification, are permitted provided that the following conditions -.\" are met: -.\" 1. Redistributions of source code must retain the above copyright -.\" notice, this list of conditions and the following disclaimer. -.\" 2. Redistributions in binary form must reproduce the above copyright -.\" notice, this list of conditions and the following disclaimer in the -.\" documentation and/or other materials provided with the distribution. -.\" -.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -.\" ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE -.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -.\" SUCH DAMAGE. -.\" -.\" $FreeBSD: stable/11/sbin/newfs_nandfs/newfs_nandfs.8 287396 2015-09-02 14:08:43Z trasz $ -.\" -.Dd October 1, 2013 -.Dt NEWFS_NANDFS 8 -.Os -.Sh NAME -.Nm newfs_nandfs -.Nd construct a new NAND FS file system -.Sh SYNOPSIS -.Nm -.Op Fl b Ar blocsize -.Op Fl B Ar blocks-per-segment -.Op Fl L Ar label -.Op Fl m Ar reserved-segment-percent -.Ar device -.Sh DESCRIPTION -The -.Nm -utility creates a NAND FS file system on device. -.Pp -The options are as follow: -.Bl -tag -width indent -.It Fl b Ar blocksize -Size of block (1024 if not specified). -.It Fl B Ar blocks_per_segment -Number of blocks per segment (2048 if not specified). -.It Fl L Ar label -Volume label (up to 16 characters). -.It Fl m Ar reserved_block_percent -Percentage of reserved blocks (5 if not specified). -.El -.Sh EXIT STATUS -Exit status is 0 on success and 1 on error. -.Sh EXAMPLES -Create a file system, using default parameters, on -.Pa /dev/ada0s1 : -.Bd -literal -offset indent -newfs_nandfs /dev/ada0s1 -.Ed -.Sh SEE ALSO -.Xr gpart 8 , -.Xr newfs 8 -.Sh HISTORY -The -.Nm -utility first appeared in -.Fx 10.0 . -.Sh AUTHORS -.An Grzegorz Bernacki diff --git a/sbin/newfs_nandfs/newfs_nandfs.c b/sbin/newfs_nandfs/newfs_nandfs.c deleted file mode 100644 index 29bde284a2..0000000000 --- a/sbin/newfs_nandfs/newfs_nandfs.c +++ /dev/null @@ -1,1182 +0,0 @@ -/*- - * SPDX-License-Identifier: BSD-2-Clause-FreeBSD - * - * Copyright (c) 2010-2012 Semihalf. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#define DEBUG -#undef DEBUG -#ifdef DEBUG -#define debug(fmt, args...) do { \ - printf("nandfs:" fmt "\n", ##args); } while (0) -#else -#define debug(fmt, args...) -#endif - -#define NANDFS_FIRST_BLOCK nandfs_first_block() -#define NANDFS_FIRST_CNO 1 -#define NANDFS_BLOCK_BAD 1 -#define NANDFS_BLOCK_GOOD 0 - -struct file_info { - uint64_t ino; - const char *name; - uint32_t mode; - uint64_t size; - uint8_t nblocks; - uint32_t *blocks; - struct nandfs_inode *inode; -}; - -static struct file_info user_files[] = { - { NANDFS_ROOT_INO, NULL, S_IFDIR | 0755, 0, 1, NULL, NULL }, -}; - -static struct file_info ifile = - { NANDFS_IFILE_INO, NULL, 0, 0, -1, NULL, NULL }; -static struct file_info sufile = - { NANDFS_SUFILE_INO, NULL, 0, 0, -1, NULL, NULL }; -static struct file_info cpfile = - { NANDFS_CPFILE_INO, NULL, 0, 0, -1, NULL, NULL }; -static struct file_info datfile = - { NANDFS_DAT_INO, NULL, 0, 0, -1, NULL, NULL }; - -struct nandfs_block { - LIST_ENTRY(nandfs_block) block_link; - uint32_t number; - uint64_t offset; - void *data; -}; - -static LIST_HEAD(, nandfs_block) block_head = - LIST_HEAD_INITIALIZER(&block_head); - -/* Storage geometry */ -static off_t mediasize; -static ssize_t sectorsize; -static uint64_t nsegments; -static uint64_t erasesize; -static uint64_t segsize; - -static struct nandfs_fsdata fsdata; -static struct nandfs_super_block super_block; - -static int is_nand; - -/* Nandfs parameters */ -static size_t blocksize = NANDFS_DEF_BLOCKSIZE; -static long blocks_per_segment; -static long rsv_segment_percent = 5; -static time_t nandfs_time; -static uint32_t bad_segments_count = 0; -static uint32_t *bad_segments = NULL; -static uint8_t fsdata_blocks_state[NANDFS_NFSAREAS]; - -static u_char *volumelabel = NULL; - -static struct nandfs_super_root *sr; - -static uint32_t nuserfiles; -static uint32_t seg_nblocks; -static uint32_t seg_endblock; - -#define SIZE_TO_BLOCK(size) howmany(size, blocksize) - -static uint32_t -nandfs_first_block(void) -{ - uint32_t i, first_free, start_bad_segments = 0; - - for (i = 0; i < bad_segments_count; i++) { - if (i == bad_segments[i]) - start_bad_segments++; - else - break; - } - - first_free = SIZE_TO_BLOCK(NANDFS_DATA_OFFSET_BYTES(erasesize) + - (start_bad_segments * segsize)); - - if (first_free < (uint32_t)blocks_per_segment) - return (blocks_per_segment); - else - return (first_free); -} - -static void -usage(void) -{ - - fprintf(stderr, - "usage: newfs_nandfs [ -options ] device\n" - "where the options are:\n" - "\t-b block-size\n" - "\t-B blocks-per-segment\n" - "\t-L volume label\n" - "\t-m reserved-segments-percentage\n"); - exit(1); -} - -static int -nandfs_log2(unsigned n) -{ - unsigned count; - - /* - * N.B. this function will return 0 if supplied 0. - */ - for (count = 0; n/2; count++) - n /= 2; - return count; -} - -/* from NetBSD's src/sys/net/if_ethersubr.c */ -static uint32_t -crc32_le(uint32_t crc, const uint8_t *buf, size_t len) -{ - static const uint32_t crctab[] = { - 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, - 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, - 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c - }; - size_t i; - - crc = crc ^ ~0U; - - for (i = 0; i < len; i++) { - crc ^= buf[i]; - crc = (crc >> 4) ^ crctab[crc & 0xf]; - crc = (crc >> 4) ^ crctab[crc & 0xf]; - } - - return (crc ^ ~0U); -} - -static void * -get_block(uint32_t block_nr, uint64_t offset) -{ - struct nandfs_block *block, *new_block; - - LIST_FOREACH(block, &block_head, block_link) { - if (block->number == block_nr) - return block->data; - } - - debug("allocating block %x\n", block_nr); - - new_block = malloc(sizeof(*block)); - if (!new_block) - err(1, "cannot allocate block"); - - new_block->number = block_nr; - new_block->offset = offset; - new_block->data = malloc(blocksize); - if (!new_block->data) - err(1, "cannot allocate block data"); - - memset(new_block->data, 0, blocksize); - - LIST_INSERT_HEAD(&block_head, new_block, block_link); - - return (new_block->data); -} - -static int -nandfs_seg_usage_blk_offset(uint64_t seg, uint64_t *blk, uint64_t *offset) -{ - uint64_t off; - uint16_t seg_size; - - seg_size = sizeof(struct nandfs_segment_usage); - - off = roundup(sizeof(struct nandfs_sufile_header), seg_size); - off += (seg * seg_size); - - *blk = off / blocksize; - *offset = (off % blocksize) / seg_size; - return (0); -} - -static uint32_t -segment_size(void) -{ - u_int size; - - size = sizeof(struct nandfs_segment_summary ); - size += seg_nblocks * sizeof(struct nandfs_binfo_v); - - if (size > blocksize) - err(1, "segsum info bigger that blocksize"); - - return (size); -} - - -static void -prepare_blockgrouped_file(uint32_t block) -{ - struct nandfs_block_group_desc *desc; - uint32_t i, entries; - - desc = (struct nandfs_block_group_desc *)get_block(block, 0); - entries = blocksize / sizeof(struct nandfs_block_group_desc); - for (i = 0; i < entries; i++) - desc[i].bg_nfrees = blocksize * 8; -} - -static void -alloc_blockgrouped_file(uint32_t block, uint32_t entry) -{ - struct nandfs_block_group_desc *desc; - uint32_t desc_nr; - uint32_t *bitmap; - - desc = (struct nandfs_block_group_desc *)get_block(block, 0); - bitmap = (uint32_t *)get_block(block + 1, 1); - - bitmap += (entry >> 5); - if (*bitmap & (1 << (entry % 32))) { - printf("nandfs: blockgrouped entry %d already allocated\n", - entry); - } - *bitmap |= (1 << (entry % 32)); - - desc_nr = entry / (blocksize * 8); - desc[desc_nr].bg_nfrees--; -} - - -static uint64_t -count_su_blocks(void) -{ - uint64_t maxblk, blk, offset, i; - - maxblk = blk = 0; - - for (i = 0; i < bad_segments_count; i++) { - nandfs_seg_usage_blk_offset(bad_segments[i], &blk, &offset); - debug("bad segment at block:%jx off: %jx", blk, offset); - if (blk > maxblk) - maxblk = blk; - } - - debug("bad segment needs %#jx", blk); - if (blk >= NANDFS_NDADDR) { - printf("nandfs: file too big (%jd > %d)\n", blk, NANDFS_NDADDR); - exit(2); - } - - sufile.size = (blk + 1) * blocksize; - return (blk + 1); -} - -static void -count_seg_blocks(void) -{ - uint32_t i; - - for (i = 0; i < nuserfiles; i++) - if (user_files[i].nblocks) { - seg_nblocks += user_files[i].nblocks; - user_files[i].blocks = malloc(user_files[i].nblocks * sizeof(uint32_t)); - } - - ifile.nblocks = 2 + - SIZE_TO_BLOCK(sizeof(struct nandfs_inode) * (NANDFS_USER_INO + 1)); - ifile.blocks = malloc(ifile.nblocks * sizeof(uint32_t)); - seg_nblocks += ifile.nblocks; - - cpfile.nblocks = - SIZE_TO_BLOCK((NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET + 1) * - sizeof(struct nandfs_checkpoint)); - cpfile.blocks = malloc(cpfile.nblocks * sizeof(uint32_t)); - seg_nblocks += cpfile.nblocks; - - if (!bad_segments) { - sufile.nblocks = - SIZE_TO_BLOCK((NANDFS_SUFILE_FIRST_SEGMENT_USAGE_OFFSET + 1) * - sizeof(struct nandfs_segment_usage)); - } else { - debug("bad blocks found: extra space for sufile"); - sufile.nblocks = count_su_blocks(); - } - - sufile.blocks = malloc(sufile.nblocks * sizeof(uint32_t)); - seg_nblocks += sufile.nblocks; - - datfile.nblocks = 2 + - SIZE_TO_BLOCK((seg_nblocks) * sizeof(struct nandfs_dat_entry)); - datfile.blocks = malloc(datfile.nblocks * sizeof(uint32_t)); - seg_nblocks += datfile.nblocks; -} - -static void -assign_file_blocks(uint64_t start_block) -{ - uint32_t i, j; - - for (i = 0; i < nuserfiles; i++) - for (j = 0; j < user_files[i].nblocks; j++) { - debug("user file %d at block %d at %#jx", - i, j, (uintmax_t)start_block); - user_files[i].blocks[j] = start_block++; - } - - for (j = 0; j < ifile.nblocks; j++) { - debug("ifile block %d at %#jx", j, (uintmax_t)start_block); - ifile.blocks[j] = start_block++; - } - - for (j = 0; j < cpfile.nblocks; j++) { - debug("cpfile block %d at %#jx", j, (uintmax_t)start_block); - cpfile.blocks[j] = start_block++; - } - - for (j = 0; j < sufile.nblocks; j++) { - debug("sufile block %d at %#jx", j, (uintmax_t)start_block); - sufile.blocks[j] = start_block++; - } - - for (j = 0; j < datfile.nblocks; j++) { - debug("datfile block %d at %#jx", j, (uintmax_t)start_block); - datfile.blocks[j] = start_block++; - } - - /* add one for superroot */ - debug("sr at block %#jx", (uintmax_t)start_block); - sr = (struct nandfs_super_root *)get_block(start_block++, 0); - seg_endblock = start_block; -} - -static void -save_datfile(void) -{ - - prepare_blockgrouped_file(datfile.blocks[0]); -} - -static uint64_t -update_datfile(uint64_t block) -{ - struct nandfs_dat_entry *dat; - static uint64_t vblock = 0; - uint64_t allocated, i, off; - - if (vblock == 0) { - alloc_blockgrouped_file(datfile.blocks[0], vblock); - vblock++; - } - allocated = vblock; - i = vblock / (blocksize / sizeof(*dat)); - off = vblock % (blocksize / sizeof(*dat)); - vblock++; - - dat = (struct nandfs_dat_entry *)get_block(datfile.blocks[2 + i], 2 + i); - - alloc_blockgrouped_file(datfile.blocks[0], allocated); - dat[off].de_blocknr = block; - dat[off].de_start = NANDFS_FIRST_CNO; - dat[off].de_end = UINTMAX_MAX; - - return (allocated); -} - -static union nandfs_binfo * -update_block_info(union nandfs_binfo *binfo, struct file_info *file) -{ - nandfs_daddr_t vblock; - uint32_t i; - - for (i = 0; i < file->nblocks; i++) { - debug("%s: blk %x", __func__, i); - if (file->ino != NANDFS_DAT_INO) { - vblock = update_datfile(file->blocks[i]); - binfo->bi_v.bi_vblocknr = vblock; - binfo->bi_v.bi_blkoff = i; - binfo->bi_v.bi_ino = file->ino; - file->inode->i_db[i] = vblock; - } else { - binfo->bi_dat.bi_blkoff = i; - binfo->bi_dat.bi_ino = file->ino; - file->inode->i_db[i] = datfile.blocks[i]; - } - binfo++; - } - - return (binfo); -} - -static void -save_segsum(struct nandfs_segment_summary *ss) -{ - union nandfs_binfo *binfo; - struct nandfs_block *block; - uint32_t sum_bytes, i; - uint8_t crc_data, crc_skip; - - sum_bytes = segment_size(); - ss->ss_magic = NANDFS_SEGSUM_MAGIC; - ss->ss_bytes = sizeof(struct nandfs_segment_summary); - ss->ss_flags = NANDFS_SS_LOGBGN | NANDFS_SS_LOGEND | NANDFS_SS_SR; - ss->ss_seq = 1; - ss->ss_create = nandfs_time; - - ss->ss_next = nandfs_first_block() + blocks_per_segment; - /* nblocks = segment blocks + segsum block + superroot */ - ss->ss_nblocks = seg_nblocks + 2; - ss->ss_nbinfos = seg_nblocks; - ss->ss_sumbytes = sum_bytes; - - crc_skip = sizeof(ss->ss_datasum) + sizeof(ss->ss_sumsum); - ss->ss_sumsum = crc32_le(0, (uint8_t *)ss + crc_skip, - sum_bytes - crc_skip); - crc_data = 0; - - binfo = (union nandfs_binfo *)(ss + 1); - for (i = 0; i < nuserfiles; i++) { - if (user_files[i].nblocks) - binfo = update_block_info(binfo, &user_files[i]); - } - - binfo = update_block_info(binfo, &ifile); - binfo = update_block_info(binfo, &cpfile); - binfo = update_block_info(binfo, &sufile); - update_block_info(binfo, &datfile); - - /* save superroot crc */ - crc_skip = sizeof(sr->sr_sum); - sr->sr_sum = crc32_le(0, (uint8_t *)sr + crc_skip, - NANDFS_SR_BYTES - crc_skip); - - /* segment checksup */ - crc_skip = sizeof(ss->ss_datasum); - LIST_FOREACH(block, &block_head, block_link) { - if (block->number < NANDFS_FIRST_BLOCK) - continue; - if (block->number == NANDFS_FIRST_BLOCK) - crc_data = crc32_le(0, - (uint8_t *)block->data + crc_skip, - blocksize - crc_skip); - else - crc_data = crc32_le(crc_data, (uint8_t *)block->data, - blocksize); - } - ss->ss_datasum = crc_data; -} - -static void -create_fsdata(void) -{ - struct uuid tmp; - - memset(&fsdata, 0, sizeof(struct nandfs_fsdata)); - - fsdata.f_magic = NANDFS_FSDATA_MAGIC; - fsdata.f_nsegments = nsegments; - fsdata.f_erasesize = erasesize; - fsdata.f_first_data_block = NANDFS_FIRST_BLOCK; - fsdata.f_blocks_per_segment = blocks_per_segment; - fsdata.f_r_segments_percentage = rsv_segment_percent; - fsdata.f_rev_level = NANDFS_CURRENT_REV; - fsdata.f_sbbytes = NANDFS_SB_BYTES; - fsdata.f_bytes = NANDFS_FSDATA_CRC_BYTES; - fsdata.f_ctime = nandfs_time; - fsdata.f_log_block_size = nandfs_log2(blocksize) - 10; - fsdata.f_errors = 1; - fsdata.f_inode_size = sizeof(struct nandfs_inode); - fsdata.f_dat_entry_size = sizeof(struct nandfs_dat_entry); - fsdata.f_checkpoint_size = sizeof(struct nandfs_checkpoint); - fsdata.f_segment_usage_size = sizeof(struct nandfs_segment_usage); - - uuidgen(&tmp, 1); - fsdata.f_uuid = tmp; - - if (volumelabel) - memcpy(fsdata.f_volume_name, volumelabel, 16); - - fsdata.f_sum = crc32_le(0, (const uint8_t *)&fsdata, - NANDFS_FSDATA_CRC_BYTES); -} - -static void -save_fsdata(void *data) -{ - - memcpy(data, &fsdata, sizeof(fsdata)); -} - -static void -create_super_block(void) -{ - - memset(&super_block, 0, sizeof(struct nandfs_super_block)); - - super_block.s_magic = NANDFS_SUPER_MAGIC; - super_block.s_last_cno = NANDFS_FIRST_CNO; - super_block.s_last_pseg = NANDFS_FIRST_BLOCK; - super_block.s_last_seq = 1; - super_block.s_free_blocks_count = - (nsegments - bad_segments_count) * blocks_per_segment; - super_block.s_mtime = 0; - super_block.s_wtime = nandfs_time; - super_block.s_state = NANDFS_VALID_FS; - - super_block.s_sum = crc32_le(0, (const uint8_t *)&super_block, - NANDFS_SB_BYTES); -} - -static void -save_super_block(void *data) -{ - - memcpy(data, &super_block, sizeof(super_block)); -} - -static void -save_super_root(void) -{ - - sr->sr_bytes = NANDFS_SR_BYTES; - sr->sr_flags = 0; - sr->sr_nongc_ctime = nandfs_time; - datfile.inode = &sr->sr_dat; - cpfile.inode = &sr->sr_cpfile; - sufile.inode = &sr->sr_sufile; -} - -static struct nandfs_dir_entry * -add_de(void *block, struct nandfs_dir_entry *de, uint64_t ino, - const char *name, uint8_t type) -{ - uint16_t reclen; - - /* modify last de */ - de->rec_len = NANDFS_DIR_REC_LEN(de->name_len); - de = (void *)((uint8_t *)de + de->rec_len); - - reclen = blocksize - ((uintptr_t)de - (uintptr_t)block); - if (reclen < NANDFS_DIR_REC_LEN(strlen(name))) { - printf("nandfs: too many dir entries for one block\n"); - return (NULL); - } - - de->inode = ino; - de->rec_len = reclen; - de->name_len = strlen(name); - de->file_type = type; - memset(de->name, 0, - (strlen(name) + NANDFS_DIR_PAD - 1) & ~NANDFS_DIR_ROUND); - memcpy(de->name, name, strlen(name)); - - return (de); -} - -static struct nandfs_dir_entry * -make_dir(void *block, uint64_t ino, uint64_t parent_ino) -{ - struct nandfs_dir_entry *de = (struct nandfs_dir_entry *)block; - - /* create '..' entry */ - de->inode = parent_ino; - de->rec_len = NANDFS_DIR_REC_LEN(2); - de->name_len = 2; - de->file_type = DT_DIR; - memset(de->name, 0, NANDFS_DIR_NAME_LEN(2)); - memcpy(de->name, "..", 2); - - /* create '.' entry */ - de = (void *)((uint8_t *)block + NANDFS_DIR_REC_LEN(2)); - de->inode = ino; - de->rec_len = blocksize - NANDFS_DIR_REC_LEN(2); - de->name_len = 1; - de->file_type = DT_DIR; - memset(de->name, 0, NANDFS_DIR_NAME_LEN(1)); - memcpy(de->name, ".", 1); - - return (de); -} - -static void -save_root_dir(void) -{ - struct file_info *root = &user_files[0]; - struct nandfs_dir_entry *de; - uint32_t i; - void *block; - - block = get_block(root->blocks[0], 0); - - de = make_dir(block, root->ino, root->ino); - for (i = 1; i < nuserfiles; i++) - de = add_de(block, de, user_files[i].ino, user_files[i].name, - IFTODT(user_files[i].mode)); - - root->size = ((uintptr_t)de - (uintptr_t)block) + - NANDFS_DIR_REC_LEN(de->name_len); -} - -static void -save_sufile(void) -{ - struct nandfs_sufile_header *header; - struct nandfs_segment_usage *su; - uint64_t blk, i, off; - void *block; - int start; - - /* - * At the beginning just zero-out everything - */ - for (i = 0; i < sufile.nblocks; i++) - get_block(sufile.blocks[i], 0); - - start = 0; - - block = get_block(sufile.blocks[start], 0); - header = (struct nandfs_sufile_header *)block; - header->sh_ncleansegs = nsegments - bad_segments_count - 1; - header->sh_ndirtysegs = 1; - header->sh_last_alloc = 1; - - su = (struct nandfs_segment_usage *)header; - off = NANDFS_SUFILE_FIRST_SEGMENT_USAGE_OFFSET; - /* Allocate data segment */ - su[off].su_lastmod = nandfs_time; - /* nblocks = segment blocks + segsum block + superroot */ - su[off].su_nblocks = seg_nblocks + 2; - su[off].su_flags = NANDFS_SEGMENT_USAGE_DIRTY; - off++; - /* Allocate next segment */ - su[off].su_lastmod = nandfs_time; - su[off].su_nblocks = 0; - su[off].su_flags = NANDFS_SEGMENT_USAGE_DIRTY; - for (i = 0; i < bad_segments_count; i++) { - nandfs_seg_usage_blk_offset(bad_segments[i], &blk, &off); - debug("storing bad_segments[%jd]=%x at %jx off %jx\n", i, - bad_segments[i], blk, off); - block = get_block(sufile.blocks[blk], - off * sizeof(struct nandfs_segment_usage *)); - su = (struct nandfs_segment_usage *)block; - su[off].su_lastmod = nandfs_time; - su[off].su_nblocks = 0; - su[off].su_flags = NANDFS_SEGMENT_USAGE_ERROR; - } -} - -static void -save_cpfile(void) -{ - struct nandfs_cpfile_header *header; - struct nandfs_checkpoint *cp, *initial_cp; - int i, entries = blocksize / sizeof(struct nandfs_checkpoint); - uint64_t cno; - - header = (struct nandfs_cpfile_header *)get_block(cpfile.blocks[0], 0); - header->ch_ncheckpoints = 1; - header->ch_nsnapshots = 0; - - cp = (struct nandfs_checkpoint *)header; - - /* fill first checkpoint data*/ - initial_cp = &cp[NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET]; - initial_cp->cp_flags = 0; - initial_cp->cp_checkpoints_count = 0; - initial_cp->cp_cno = NANDFS_FIRST_CNO; - initial_cp->cp_create = nandfs_time; - initial_cp->cp_nblk_inc = seg_endblock - 1; - initial_cp->cp_blocks_count = seg_nblocks; - memset(&initial_cp->cp_snapshot_list, 0, - sizeof(struct nandfs_snapshot_list)); - - ifile.inode = &initial_cp->cp_ifile_inode; - - /* mark rest of cp as invalid */ - cno = NANDFS_FIRST_CNO + 1; - i = NANDFS_CPFILE_FIRST_CHECKPOINT_OFFSET + 1; - for (; i < entries; i++) { - cp[i].cp_cno = cno++; - cp[i].cp_flags = NANDFS_CHECKPOINT_INVALID; - } -} - -static void -init_inode(struct nandfs_inode *inode, struct file_info *file) -{ - - inode->i_blocks = file->nblocks; - inode->i_ctime = nandfs_time; - inode->i_mtime = nandfs_time; - inode->i_mode = file->mode & 0xffff; - inode->i_links_count = 1; - - if (file->size > 0) - inode->i_size = file->size; - else - inode->i_size = 0; - - if (file->ino == NANDFS_USER_INO) - inode->i_flags = SF_NOUNLINK|UF_NOUNLINK; - else - inode->i_flags = 0; -} - -static void -save_ifile(void) -{ - struct nandfs_inode *inode; - struct file_info *file; - uint64_t ino, blk, off; - uint32_t i; - - prepare_blockgrouped_file(ifile.blocks[0]); - for (i = 0; i <= NANDFS_USER_INO; i++) - alloc_blockgrouped_file(ifile.blocks[0], i); - - for (i = 0; i < nuserfiles; i++) { - file = &user_files[i]; - ino = file->ino; - blk = ino / (blocksize / sizeof(*inode)); - off = ino % (blocksize / sizeof(*inode)); - inode = - (struct nandfs_inode *)get_block(ifile.blocks[2 + blk], 2 + blk); - file->inode = &inode[off]; - init_inode(file->inode, file); - } - - init_inode(ifile.inode, &ifile); - init_inode(cpfile.inode, &cpfile); - init_inode(sufile.inode, &sufile); - init_inode(datfile.inode, &datfile); -} - -static int -create_fs(void) -{ - uint64_t start_block; - uint32_t segsum_size; - char *data; - int i; - - nuserfiles = nitems(user_files); - - /* Count and assign blocks */ - count_seg_blocks(); - segsum_size = segment_size(); - start_block = NANDFS_FIRST_BLOCK + SIZE_TO_BLOCK(segsum_size); - assign_file_blocks(start_block); - - /* Create super root structure */ - save_super_root(); - - /* Create root directory */ - save_root_dir(); - - /* Fill in file contents */ - save_sufile(); - save_cpfile(); - save_ifile(); - save_datfile(); - - /* Save fsdata and superblocks */ - create_fsdata(); - create_super_block(); - - for (i = 0; i < NANDFS_NFSAREAS; i++) { - if (fsdata_blocks_state[i] != NANDFS_BLOCK_GOOD) - continue; - - data = get_block((i * erasesize)/blocksize, 0); - save_fsdata(data); - - data = get_block((i * erasesize + NANDFS_SBLOCK_OFFSET_BYTES) / - blocksize, 0); - if (blocksize > NANDFS_SBLOCK_OFFSET_BYTES) - data += NANDFS_SBLOCK_OFFSET_BYTES; - save_super_block(data); - memset(data + sizeof(struct nandfs_super_block), 0xff, - (blocksize - sizeof(struct nandfs_super_block) - - NANDFS_SBLOCK_OFFSET_BYTES)); - } - - /* Save segment summary and CRCs */ - save_segsum(get_block(NANDFS_FIRST_BLOCK, 0)); - - return (0); -} - -static void -write_fs(int fda) -{ - struct nandfs_block *block; - char *data; - u_int ret; - - /* Overwrite next block with ff if not nand device */ - if (!is_nand) { - data = get_block(seg_endblock, 0); - memset(data, 0xff, blocksize); - } - - LIST_FOREACH(block, &block_head, block_link) { - lseek(fda, block->number * blocksize, SEEK_SET); - ret = write(fda, block->data, blocksize); - if (ret != blocksize) - err(1, "cannot write filesystem data"); - } -} - -static void -check_parameters(void) -{ - int i; - - /* check blocksize */ - if ((blocksize < NANDFS_MIN_BLOCKSIZE) || (blocksize > MAXBSIZE) || - ((blocksize - 1) & blocksize)) { - errx(1, "Bad blocksize (%zu). Must be in range [%u-%u] " - "and a power of two.", blocksize, NANDFS_MIN_BLOCKSIZE, - MAXBSIZE); - } - - /* check blocks per segments */ - if ((blocks_per_segment < NANDFS_SEG_MIN_BLOCKS) || - ((blocksize - 1) & blocksize)) - errx(1, "Bad blocks per segment (%lu). Must be greater than " - "%u and a power of two.", blocks_per_segment, - NANDFS_SEG_MIN_BLOCKS); - - /* check reserved segment percentage */ - if ((rsv_segment_percent < 1) || (rsv_segment_percent > 99)) - errx(1, "Bad reserved segment percentage. " - "Must in range 1..99."); - - /* check volume label */ - i = 0; - if (volumelabel) { - while (isalnum(volumelabel[++i])) - ; - - if (volumelabel[i] != '\0') { - errx(1, "bad volume label. " - "Valid characters are alphanumerics."); - } - - if (strlen(volumelabel) >= 16) - errx(1, "Bad volume label. Length is longer than %d.", - 16); - } - - nandfs_time = time(NULL); -} - -static void -print_parameters(void) -{ - - printf("filesystem parameters:\n"); - printf("blocksize: %#zx sectorsize: %#zx\n", blocksize, sectorsize); - printf("erasesize: %#jx mediasize: %#jx\n", erasesize, mediasize); - printf("segment size: %#jx blocks per segment: %#x\n", segsize, - (uint32_t)blocks_per_segment); -} - -/* - * Exit with error if file system is mounted. - */ -static void -check_mounted(const char *fname, mode_t mode) -{ - struct statfs *mp; - const char *s1, *s2; - size_t len; - int n, r; - - if (!(n = getmntinfo(&mp, MNT_NOWAIT))) - err(1, "getmntinfo"); - - len = strlen(_PATH_DEV); - s1 = fname; - if (!strncmp(s1, _PATH_DEV, len)) - s1 += len; - - r = S_ISCHR(mode) && s1 != fname && *s1 == 'r'; - - for (; n--; mp++) { - s2 = mp->f_mntfromname; - - if (!strncmp(s2, _PATH_DEV, len)) - s2 += len; - if ((r && s2 != mp->f_mntfromname && !strcmp(s1 + 1, s2)) || - !strcmp(s1, s2)) - errx(1, "%s is mounted on %s", fname, mp->f_mntonname); - } -} - -static void -calculate_geometry(int fd) -{ - struct chip_param_io chip_params; - char ident[DISK_IDENT_SIZE]; - char medianame[MAXPATHLEN]; - - /* Check storage type */ - g_get_ident(fd, ident, DISK_IDENT_SIZE); - g_get_name(ident, medianame, MAXPATHLEN); - debug("device name: %s", medianame); - - is_nand = (strstr(medianame, "gnand") != NULL); - debug("is_nand = %d", is_nand); - - sectorsize = g_sectorsize(fd); - debug("sectorsize: %#zx", sectorsize); - - /* Get storage size */ - mediasize = g_mediasize(fd); - debug("mediasize: %#jx", mediasize); - - /* Get storage erase unit size */ - if (!is_nand) - erasesize = NANDFS_DEF_ERASESIZE; - else if (ioctl(fd, NAND_IO_GET_CHIP_PARAM, &chip_params) != -1) - erasesize = chip_params.page_size * chip_params.pages_per_block; - else - errx(1, "Cannot ioctl(NAND_IO_GET_CHIP_PARAM)"); - - debug("erasesize: %#jx", (uintmax_t)erasesize); - - if (blocks_per_segment == 0) { - if (erasesize >= NANDFS_MIN_SEGSIZE) - blocks_per_segment = erasesize / blocksize; - else - blocks_per_segment = NANDFS_MIN_SEGSIZE / blocksize; - } - - /* Calculate number of segments */ - segsize = blocksize * blocks_per_segment; - nsegments = ((mediasize - NANDFS_NFSAREAS * erasesize) / segsize) - 2; - debug("segsize: %#jx", segsize); - debug("nsegments: %#jx", nsegments); -} - -static void -erase_device(int fd) -{ - int rest, failed; - uint64_t i, nblocks; - off_t offset; - - failed = 0; - for (i = 0; i < NANDFS_NFSAREAS; i++) { - debug("Deleting %jx\n", i * erasesize); - if (g_delete(fd, i * erasesize, erasesize)) { - printf("cannot delete %jx\n", i * erasesize); - fsdata_blocks_state[i] = NANDFS_BLOCK_BAD; - failed++; - } else - fsdata_blocks_state[i] = NANDFS_BLOCK_GOOD; - } - - if (failed == NANDFS_NFSAREAS) { - printf("%d first blocks not usable. Unable to create " - "filesystem.\n", failed); - exit(1); - } - - for (i = 0; i < nsegments; i++) { - offset = NANDFS_NFSAREAS * erasesize + i * segsize; - if (g_delete(fd, offset, segsize)) { - printf("cannot delete segment %jx (offset %jd)\n", - i, offset); - bad_segments_count++; - bad_segments = realloc(bad_segments, - bad_segments_count * sizeof(uint32_t)); - bad_segments[bad_segments_count - 1] = i; - } - } - - if (bad_segments_count == nsegments) { - printf("no valid segments\n"); - exit(1); - } - - /* Delete remaining blocks at the end of device */ - rest = mediasize % segsize; - nblocks = rest / erasesize; - for (i = 0; i < nblocks; i++) { - offset = (segsize * nsegments) + (i * erasesize); - if (g_delete(fd, offset, erasesize)) { - printf("cannot delete space after last segment " - "- probably a bad block\n"); - } - } -} - -static void -erase_initial(int fd) -{ - char buf[512]; - u_int i; - - memset(buf, 0xff, sizeof(buf)); - - lseek(fd, 0, SEEK_SET); - for (i = 0; i < NANDFS_NFSAREAS * erasesize; i += sizeof(buf)) - write(fd, buf, sizeof(buf)); -} - -static void -create_nandfs(int fd) -{ - - create_fs(); - - write_fs(fd); -} - -static void -print_summary(void) -{ - - printf("filesystem was created successfully\n"); - printf("total segments: %#jx valid segments: %#jx\n", nsegments, - nsegments - bad_segments_count); - printf("total space: %ju MB free: %ju MB\n", - (nsegments * - blocks_per_segment * blocksize) / (1024 * 1024), - ((nsegments - bad_segments_count) * - blocks_per_segment * blocksize) / (1024 * 1024)); -} - -int -main(int argc, char *argv[]) -{ - struct stat sb; - char buf[MAXPATHLEN]; - const char opts[] = "b:B:L:m:"; - const char *fname; - int ch, fd; - - while ((ch = getopt(argc, argv, opts)) != -1) { - switch (ch) { - case 'b': - blocksize = strtol(optarg, (char **)NULL, 10); - if (blocksize == 0) - usage(); - break; - case 'B': - blocks_per_segment = strtol(optarg, (char **)NULL, 10); - if (blocks_per_segment == 0) - usage(); - break; - case 'L': - volumelabel = optarg; - break; - case 'm': - rsv_segment_percent = strtol(optarg, (char **)NULL, 10); - if (rsv_segment_percent == 0) - usage(); - break; - default: - usage(); - } - } - - argc -= optind; - argv += optind; - if (argc < 1 || argc > 2) - usage(); - - /* construct proper device path */ - fname = *argv++; - if (!strchr(fname, '/')) { - snprintf(buf, sizeof(buf), "%s%s", _PATH_DEV, fname); - if (!(fname = strdup(buf))) - err(1, NULL); - } - - fd = g_open(fname, 1); - if (fd == -1) - err(1, "Cannot open %s", fname); - - if (fstat(fd, &sb) == -1) - err(1, "Cannot stat %s", fname); - if (!S_ISCHR(sb.st_mode)) - warnx("%s is not a character device", fname); - - check_mounted(fname, sb.st_mode); - - calculate_geometry(fd); - - check_parameters(); - - print_parameters(); - - if (is_nand) - erase_device(fd); - else - erase_initial(fd); - - create_nandfs(fd); - - print_summary(); - - g_close(fd); - - return (0); -} - - diff --git a/sbin/ping6/Makefile b/sbin/ping6/Makefile deleted file mode 100644 index a1a189ce3c..0000000000 --- a/sbin/ping6/Makefile +++ /dev/null @@ -1,23 +0,0 @@ - -.include - -PACKAGE=runtime -PROG= ping6 -MAN= ping6.8 - -CFLAGS+=-DIPSEC -DKAME_SCOPEID - -BINOWN= root -BINMODE=4555 - -LIBADD= ipsec m md - -.if ${MK_DYNAMICROOT} == "no" -.warning ${PROG} built without libcasper support -.elif ${MK_CASPER} != "no" && !defined(RESCUE) -LIBADD+= casper -LIBADD+= cap_dns -CFLAGS+=-DWITH_CASPER -.endif - -.include diff --git a/sbin/ping6/Makefile.depend b/sbin/ping6/Makefile.depend deleted file mode 100644 index 1fb490782f..0000000000 --- a/sbin/ping6/Makefile.depend +++ /dev/null @@ -1,21 +0,0 @@ -# Autogenerated - do NOT edit! - -DIRDEPS = \ - include \ - include/arpa \ - include/xlocale \ - lib/${CSU_DIR} \ - lib/libc \ - lib/libcapsicum \ - lib/libcompiler_rt \ - lib/libipsec \ - lib/libmd \ - lib/libnv \ - lib/msun \ - - -.include - -.if ${DEP_RELDIR} == ${_DEP_RELDIR} -# local dependencies - needed for -jN in clean tree -.endif diff --git a/sbin/ping6/Makefile.depend.options b/sbin/ping6/Makefile.depend.options deleted file mode 100644 index 5d5af2276e..0000000000 --- a/sbin/ping6/Makefile.depend.options +++ /dev/null @@ -1,7 +0,0 @@ -# This file is not autogenerated - take care! - -DIRDEPS_OPTIONS= CASPER - -DIRDEPS.CASPER.yes= lib/libcasper/services/cap_dns - -.include diff --git a/sbin/ping6/ping6.8 b/sbin/ping6/ping6.8 deleted file mode 100644 index 5bb24c9e99..0000000000 --- a/sbin/ping6/ping6.8 +++ /dev/null @@ -1,560 +0,0 @@ -.\" $KAME: ping6.8,v 1.58 2003/06/20 12:00:22 itojun Exp $ -.\" -.\" Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. -.\" All rights reserved. -.\" -.\" Redistribution and use in source and binary forms, with or without -.\" modification, are permitted provided that the following conditions -.\" are met: -.\" 1. Redistributions of source code must retain the above copyright -.\" notice, this list of conditions and the following disclaimer. -.\" 2. Redistributions in binary form must reproduce the above copyright -.\" notice, this list of conditions and the following disclaimer in the -.\" documentation and/or other materials provided with the distribution. -.\" 3. Neither the name of the project nor the names of its contributors -.\" may be used to endorse or promote products derived from this software -.\" without specific prior written permission. -.\" -.\" THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND -.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -.\" ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE -.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -.\" SUCH DAMAGE. -.\" -.\" -.Dd September 10, 2020 -.Dt PING6 8 -.Os -.Sh NAME -.Nm ping6 -.Nd send -.Tn ICMPv6 ECHO_REQUEST -packets to network hosts -.Sh SYNOPSIS -.Nm -.\" without ipsec, or new ipsec -.Op Fl DdfHmnNoqrRtvwW -.\" old ipsec -.\" .Op Fl ADdEfmnNqRtvwW -.Bk -words -.Op Fl a Ar addrtype -.Ek -.Bk -words -.Op Fl b Ar bufsiz -.Ek -.Bk -words -.Op Fl c Ar count -.Ek -.Bk -words -.Op Fl g Ar gateway -.Ek -.Bk -words -.Op Fl h Ar hoplimit -.Ek -.Bk -words -.Op Fl I Ar interface -.Ek -.Bk -words -.Op Fl i Ar wait -.Ek -.Bk -words -.Op Fl x Ar waittime -.Ek -.Bk -words -.Op Fl X Ar timeout -.Ek -.Bk -words -.Op Fl l Ar preload -.Ek -.Bk -words -.\" new ipsec -.Op Fl P Ar policy -.Ek -.Bk -words -.Op Fl p Ar pattern -.Ek -.Bk -words -.Op Fl S Ar sourceaddr -.Ek -.Bk -words -.Op Fl s Ar packetsize -.Ek -.Bk -words -.Op Fl z Ar tclass -.Ek -.Bk -words -.Op Ar hops ... -.Ek -.Bk -words -.Ar host -.Ek -.Sh DESCRIPTION -The -.Nm -utility uses the -.Tn ICMPv6 -protocol's mandatory -.Tn ICMP6_ECHO_REQUEST -datagram to elicit an -.Tn ICMP6_ECHO_REPLY -from a host or gateway. -.Tn ICMP6_ECHO_REQUEST -datagrams (``pings'') have an IPv6 header, -and -.Tn ICMPv6 -header formatted as documented in RFC2463. -The options are as follows: -.Bl -tag -width Ds -.\" old ipsec -.\" .It Fl A -.\" Enables transport-mode IPsec authentication header -.\" (experimental). -.It Fl a Ar addrtype -Generate ICMPv6 Node Information Node Addresses query, rather than echo-request. -.Ar addrtype -must be a string constructed of the following characters. -.Bl -tag -width Ds -compact -.It Ic a -requests unicast addresses from all of the responder's interfaces. -If the character is omitted, -only those addresses which belong to the interface which has the -responder's address are requests. -.It Ic c -requests responder's IPv4-compatible and IPv4-mapped addresses. -.It Ic g -requests responder's global-scope addresses. -.It Ic s -requests responder's site-local addresses. -.It Ic l -requests responder's link-local addresses. -.It Ic A -requests responder's anycast addresses. -Without this character, the responder will return unicast addresses only. -With this character, the responder will return anycast addresses only. -Note that the specification does not specify how to get responder's -anycast addresses. -This is an experimental option. -.El -.It Fl b Ar bufsiz -Set socket buffer size. -.It Fl c Ar count -Stop after sending -(and receiving) -.Ar count -.Tn ECHO_RESPONSE -packets. -.It Fl D -Disable IPv6 fragmentation. -.It Fl d -Set the -.Dv SO_DEBUG -option on the socket being used. -.\" .It Fl E -.\" Enables transport-mode IPsec encapsulated security payload -.\" (experimental). -.It Fl f -Flood ping. -Outputs packets as fast as they come back or one hundred times per second, -whichever is more. -For every -.Tn ECHO_REQUEST -sent a period -.Dq \&. -is printed, while for every -.Tn ECHO_REPLY -received a backspace is printed. -This provides a rapid display of how many packets are being dropped. -Only the super-user may use this option. -.Bf -emphasis -This can be very hard on a network and should be used with caution. -.Ef -.It Fl g Ar gateway -Specifies to use -.Ar gateway -as the next hop to the destination. -The gateway must be a neighbor of the sending node. -.It Fl H -Specifies to try reverse-lookup of IPv6 addresses. -The -.Nm -utility does not try reverse-lookup unless the option is specified. -.It Fl h Ar hoplimit -Set the IPv6 hoplimit. -.It Fl I Ar interface -Source packets with the given interface address. -This flag applies if the ping destination is a multicast address, -or link-local/site-local unicast address. -.It Fl i Ar wait -Wait -.Ar wait -seconds -.Em between sending each packet . -The default is to wait for one second between each packet. -This option is incompatible with the -.Fl f -option. -.It Fl x Ar waittime -Time in milliseconds to wait for a reply for each packet sent. -If a reply arrives later, -the packet is not printed as replied, -but considered as replied when calculating statistics. -.It Fl X Ar timeout -Specify a timeout, -in seconds, -before ping exits regardless of how many packets have been received. -.It Fl l Ar preload -If -.Ar preload -is specified, -.Nm -sends that many packets as fast as possible before falling into its normal -mode of behavior. -Only the super-user may use this option. -.It Fl m -By default, -.Nm -asks the kernel to fragment packets to fit into the minimum IPv6 MTU. -The -.Fl m -option -will suppress the behavior in the following two levels: -when the option is specified once, the behavior will be disabled for -unicast packets. -When the option is more than once, it will be disabled for both -unicast and multicast packets. -.It Fl n -Numeric output only. -No attempt will be made to lookup symbolic names from addresses in the reply. -.It Fl N -Probe node information multicast group address -.Pq Li ff02::2:ffxx:xxxx . -.Ar host -must be string hostname of the target -(must not be a numeric IPv6 address). -Node information multicast group will be computed based on given -.Ar host , -and will be used as the final destination. -Since node information multicast group is a link-local multicast group, -outgoing interface needs to be specified by -.Fl I -option. -.Pp -When specified twice, the address -.Pq Li ff02::2:xxxx:xxxx -is used instead. -The former is in RFC 4620, the latter is in an old Internet Draft -draft-ietf-ipngwg-icmp-name-lookup. -Note that KAME-derived implementations including -.Fx -use the latter. -.It Fl o -Exit successfully after receiving one reply packet. -.It Fl p Ar pattern -You may specify up to 16 -.Dq pad -bytes to fill out the packet you send. -This is useful for diagnosing data-dependent problems in a network. -For example, -.Dq Li \-p ff -will cause the sent packet to be filled with all -ones. -.\" new ipsec -.It Fl P Ar policy -.Ar policy -specifies IPsec policy to be used for the probe. -.It Fl q -Quiet output. -Nothing is displayed except the summary lines at startup time and -when finished. -.It Fl r -Audible. -Include a bell -.Tn ( ASCII -0x07) -character in the output when any packet is received. -.It Fl R -Audible. -Output a bell -.Tn ( ASCII -0x07) -character when no packet is received before the next packet -is transmitted. -To cater for round-trip times that are longer than the interval -between transmissions, further missing packets cause a bell only -if the maximum number of unreceived packets has increased. -.It Fl S Ar sourceaddr -Specifies the source address of request packets. -The source address must be one of the unicast addresses of the sending node, -and must be numeric. -.It Fl s Ar packetsize -Specifies the number of data bytes to be sent. -The default is 56, which translates into 64 -.Tn ICMP -data bytes when combined -with the 8 bytes of -.Tn ICMP -header data. -You may need to specify -.Fl b -as well to extend socket buffer size. -.It Fl t -Generate ICMPv6 Node Information supported query types query, -rather than echo-request. -.Fl s -has no effect if -.Fl t -is specified. -.It Fl v -Verbose output. -.Tn ICMP -packets other than -.Tn ECHO_RESPONSE -that are received are listed. -.It Fl w -Generate ICMPv6 Node Information DNS Name query, rather than echo-request. -.Fl s -has no effect if -.Fl w -is specified. -.It Fl W -Same as -.Fl w , -but with old packet format based on 03 draft. -This option is present for backward compatibility. -.Fl s -has no effect if -.Fl w -is specified. -.It Fl z Ar tclass -Use the specified traffic class when sending. -.It Ar hops -IPv6 addresses for intermediate nodes, -which will be put into type 0 routing header. -.It Ar host -IPv6 address of the final destination node. -.El -.Pp -When using -.Nm -for fault isolation, it should first be run on the local host, to verify -that the local network interface is up and running. -Then, hosts and gateways further and further away should be -.Dq pinged . -Round-trip times and packet loss statistics are computed. -If duplicate packets are received, they are not included in the packet -loss calculation, although the round trip time of these packets is used -in calculating the round-trip time statistics. -When the specified number of packets have been sent -(and received) -or if the program is terminated with a -.Dv SIGINT , -a brief summary is displayed, showing the number of packets sent and -received, and the minimum, mean, maximum, and standard deviation of -the round-trip times. -.Pp -If -.Nm -receives a -.Dv SIGINFO -(see the -.Cm status -argument for -.Xr stty 1 ) -signal, the current number of packets sent and received, and the -minimum, mean, maximum, and standard deviation of the round-trip times -will be written to the standard output in the same format as the -standard completion message. -.Pp -This program is intended for use in network testing, measurement and -management. -Because of the load it can impose on the network, it is unwise to use -.Nm -during normal operations or from automated scripts. -.\" .Sh ICMP PACKET DETAILS -.\" An IP header without options is 20 bytes. -.\" An -.\" .Tn ICMP -.\" .Tn ECHO_REQUEST -.\" packet contains an additional 8 bytes worth of -.\" .Tn ICMP -.\" header followed by an arbitrary amount of data. -.\" When a -.\" .Ar packetsize -.\" is given, this indicated the size of this extra piece of data -.\" (the default is 56). -.\" Thus the amount of data received inside of an IP packet of type -.\" .Tn ICMP -.\" .Tn ECHO_REPLY -.\" will always be 8 bytes more than the requested data space -.\" (the -.\" .Tn ICMP -.\" header). -.\" .Pp -.\" If the data space is at least eight bytes large, -.\" .Nm -.\" uses the first eight bytes of this space to include a timestamp which -.\" it uses in the computation of round trip times. -.\" If less than eight bytes of pad are specified, no round trip times are -.\" given. -.Sh DUPLICATE AND DAMAGED PACKETS -The -.Nm -utility will report duplicate and damaged packets. -Duplicate packets should never occur when pinging a unicast address, -and seem to be caused by -inappropriate link-level retransmissions. -Duplicates may occur in many situations and are rarely -(if ever) -a good sign, although the presence of low levels of duplicates may not -always be cause for alarm. -Duplicates are expected when pinging a broadcast or multicast address, -since they are not really duplicates but replies from different hosts -to the same request. -.Pp -Damaged packets are obviously serious cause for alarm and often -indicate broken hardware somewhere in the -.Nm -packet's path -(in the network or in the hosts). -.Sh TRYING DIFFERENT DATA PATTERNS -The -(inter)network -layer should never treat packets differently depending on the data -contained in the data portion. -Unfortunately, data-dependent problems have been known to sneak into -networks and remain undetected for long periods of time. -In many cases the particular pattern that will have problems is something -that does not have sufficient -.Dq transitions , -such as all ones or all zeros, or a pattern right at the edge, such as -almost all zeros. -It is not -necessarily enough to specify a data pattern of all zeros (for example) -on the command line because the pattern that is of interest is -at the data link level, and the relationship between what you type and -what the controllers transmit can be complicated. -.Pp -This means that if you have a data-dependent problem you will probably -have to do a lot of testing to find it. -If you are lucky, you may manage to find a file that either -cannot -be sent across your network or that takes much longer to transfer than -other similar length files. -You can then examine this file for repeated patterns that you can test -using the -.Fl p -option of -.Nm . -.Sh EXIT STATUS -The -.Nm -utility returns 0 on success (the host is alive), -2 if the transmission was successful but no responses were received, -any other non-zero value if the arguments are incorrect or -another error has occurred. -.Sh EXAMPLES -Normally, -.Nm -works just like -.Xr ping 8 -would work; the following will send ICMPv6 echo request to -.Li dst.foo.com . -.Bd -literal -offset indent -ping6 -n dst.foo.com -.Ed -.Pp -The following will probe hostnames for all nodes on the network link attached to -.Li wi0 -interface. -The address -.Li ff02::1 -is named the link-local all-node multicast address, and the packet would -reach every node on the network link. -.Bd -literal -offset indent -ping6 -w ff02::1%wi0 -.Ed -.Pp -The following will probe addresses assigned to the destination node, -.Li dst.foo.com . -.Bd -literal -offset indent -ping6 -a agl dst.foo.com -.Ed -.Sh SEE ALSO -.Xr netstat 1 , -.Xr icmp6 4 , -.Xr inet6 4 , -.Xr ip6 4 , -.Xr ifconfig 8 , -.Xr ping 8 , -.Xr routed 8 , -.Xr traceroute 8 , -.Xr traceroute6 8 -.Rs -.%A A. Conta -.%A S. Deering -.%T "Internet Control Message Protocol (ICMPv6) for the Internet Protocol Version 6 (IPv6) Specification" -.%N RFC2463 -.%D December 1998 -.Re -.Rs -.%A Matt Crawford -.%T "IPv6 Node Information Queries" -.%N draft-ietf-ipngwg-icmp-name-lookups-09.txt -.%D May 2002 -.%O work in progress material -.Re -.Sh HISTORY -The -.Xr ping 8 -utility appeared in -.Bx 4.3 . -The -.Nm -utility with IPv6 support first appeared in the WIDE Hydrangea IPv6 -protocol stack kit. -.Pp -IPv6 and IPsec support based on the KAME Project -.Pq Pa http://www.kame.net/ -stack was initially integrated into -.Fx 4.0 . -.Sh BUGS -The -.Nm -utility -is intentionally separate from -.Xr ping 8 . -.Pp -There have been many discussions on why we separate -.Nm -and -.Xr ping 8 . -Some people argued that it would be more convenient to uniform the -ping command for both IPv4 and IPv6. -The followings are an answer to the request. -.Pp -From a developer's point of view: -since the underling raw sockets API is totally different between IPv4 -and IPv6, we would end up having two types of code base. -There would actually be less benefit to uniform the two commands -into a single command from the developer's standpoint. -.Pp -From an operator's point of view: unlike ordinary network applications -like remote login tools, we are usually aware of address family when using -network management tools. -We do not just want to know the reachability to the host, but want to know the -reachability to the host via a particular network protocol such as -IPv6. -Thus, even if we had a unified -.Xr ping 8 -command for both IPv4 and IPv6, we would usually type a -.Fl 6 -or -.Fl 4 -option (or something like those) to specify the particular address family. -This essentially means that we have two different commands. diff --git a/sbin/ping6/ping6.c b/sbin/ping6/ping6.c deleted file mode 100644 index 6964f4475e..0000000000 --- a/sbin/ping6/ping6.c +++ /dev/null @@ -1,2870 +0,0 @@ -/* $KAME: ping6.c,v 1.169 2003/07/25 06:01:47 itojun Exp $ */ - -/*- - * SPDX-License-Identifier: BSD-3-Clause - * - * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the project nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/* BSDI ping.c,v 2.3 1996/01/21 17:56:50 jch Exp */ - -/* - * Copyright (c) 1989, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Mike Muuss. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#if 0 -#ifndef lint -static const char copyright[] = -"@(#) Copyright (c) 1989, 1993\n\ - The Regents of the University of California. All rights reserved.\n"; -#endif /* not lint */ - -#ifndef lint -static char sccsid[] = "@(#)ping.c 8.1 (Berkeley) 6/5/93"; -#endif /* not lint */ -#endif - -#include - -/* - * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility, - * measure round-trip-delays and packet loss across network paths. - * - * Author - - * Mike Muuss - * U. S. Army Ballistic Research Laboratory - * December, 1983 - * - * Status - - * Public Domain. Distribution Unlimited. - * Bugs - - * More statistics could always be gathered. - * This program has to run SUID to ROOT to access the ICMP socket. - */ -/* - * NOTE: - * USE_SIN6_SCOPE_ID assumes that sin6_scope_id has the same semantics - * as IPV6_PKTINFO. Some people object it (sin6_scope_id specifies *link* - * while IPV6_PKTINFO specifies *interface*. Link is defined as collection of - * network attached to 1 or more interfaces) - */ - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef IPSEC -#include -#include -#endif - -#include - -struct tv32 { - u_int32_t tv32_sec; - u_int32_t tv32_nsec; -}; - -#define MAXPACKETLEN 131072 -#define IP6LEN 40 -#define ICMP6ECHOLEN 8 /* icmp echo header len excluding time */ -#define ICMP6ECHOTMLEN sizeof(struct tv32) -#define ICMP6_NIQLEN (ICMP6ECHOLEN + 8) -# define CONTROLLEN 10240 /* ancillary data buffer size RFC3542 20.1 */ -/* FQDN case, 64 bits of nonce + 32 bits ttl */ -#define ICMP6_NIRLEN (ICMP6ECHOLEN + 12) -#define EXTRA 256 /* for AH and various other headers. weird. */ -#define DEFDATALEN ICMP6ECHOTMLEN -#define MAXDATALEN MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN -#define NROUTES 9 /* number of record route slots */ -#define MAXWAIT 10000 /* max ms to wait for response */ -#define MAXALARM (60 * 60) /* max seconds for alarm timeout */ - -#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ -#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ -#define SET(bit) (A(bit) |= B(bit)) -#define CLR(bit) (A(bit) &= (~B(bit))) -#define TST(bit) (A(bit) & B(bit)) - -#define F_FLOOD 0x0001 -#define F_INTERVAL 0x0002 -#define F_PINGFILLED 0x0008 -#define F_QUIET 0x0010 -#define F_RROUTE 0x0020 -#define F_SO_DEBUG 0x0040 -#define F_VERBOSE 0x0100 -#ifdef IPSEC -#ifdef IPSEC_POLICY_IPSEC -#define F_POLICY 0x0400 -#else -#define F_AUTHHDR 0x0200 -#define F_ENCRYPT 0x0400 -#endif /*IPSEC_POLICY_IPSEC*/ -#endif /*IPSEC*/ -#define F_NODEADDR 0x0800 -#define F_FQDN 0x1000 -#define F_INTERFACE 0x2000 -#define F_SRCADDR 0x4000 -#define F_HOSTNAME 0x10000 -#define F_FQDNOLD 0x20000 -#define F_NIGROUP 0x40000 -#define F_SUPTYPES 0x80000 -#define F_NOMINMTU 0x100000 -#define F_ONCE 0x200000 -#define F_AUDIBLE 0x400000 -#define F_MISSED 0x800000 -#define F_DONTFRAG 0x1000000 -#define F_NOUSERDATA (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES) -#define F_WAITTIME 0x2000000 -static u_int options; - -#define IN6LEN sizeof(struct in6_addr) -#define SA6LEN sizeof(struct sockaddr_in6) -#define DUMMY_PORT 10101 - -#define SIN6(s) ((struct sockaddr_in6 *)(s)) - -/* - * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum - * number of received sequence numbers we can keep track of. Change 128 - * to 8192 for complete accuracy... - */ -#define MAX_DUP_CHK (8 * 8192) -static int mx_dup_ck = MAX_DUP_CHK; -static char rcvd_tbl[MAX_DUP_CHK / 8]; - -static struct sockaddr_in6 dst; /* who to ping6 */ -static struct sockaddr_in6 src; /* src addr of this packet */ -static socklen_t srclen; -static size_t datalen = DEFDATALEN; -static int ssend; /* send socket file descriptor */ -static int srecv; /* receive socket file descriptor */ -static u_char outpack[MAXPACKETLEN]; -static char BSPACE = '\b'; /* characters written for flood */ -static char BBELL = '\a'; /* characters written for AUDIBLE */ -static char DOT = '.'; -static char *hostname; -static int ident; /* process id to identify our packets */ -static u_int8_t nonce[8]; /* nonce field for node information */ -static int hoplimit = -1; /* hoplimit */ -static int tclass = -1; /* traffic class */ -static u_char *packet = NULL; -static cap_channel_t *capdns; - -/* counters */ -static long nmissedmax; /* max value of ntransmitted - nreceived - 1 */ -static long npackets; /* max packets to transmit */ -static long nreceived; /* # of packets we got back */ -static long nrepeats; /* number of duplicates */ -static long ntransmitted; /* sequence # for outbound packets = #sent */ -static int interval = 1000; /* interval between packets in ms */ -static int waittime = MAXWAIT; /* timeout for each packet */ -static long nrcvtimeout = 0; /* # of packets we got back after waittime */ - -/* timing */ -static int timing; /* flag to do timing */ -static double tmin = 999999999.0; /* minimum round trip time */ -static double tmax = 0.0; /* maximum round trip time */ -static double tsum = 0.0; /* sum of all times, for doing average */ -static double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ - -/* for node addresses */ -static u_short naflags; - -/* for ancillary data(advanced API) */ -static struct msghdr smsghdr; -static struct iovec smsgiov; -static char *scmsg = 0; - -static volatile sig_atomic_t seenint; -#ifdef SIGINFO -static volatile sig_atomic_t seeninfo; -#endif - -int main(int, char *[]); -static cap_channel_t *capdns_setup(void); -static void fill(char *, char *); -static int get_hoplim(struct msghdr *); -static int get_pathmtu(struct msghdr *); -static struct in6_pktinfo *get_rcvpktinfo(struct msghdr *); -static void onsignal(int); -static void onint(int); -static size_t pingerlen(void); -static int pinger(void); -static const char *pr_addr(struct sockaddr *, int); -static void pr_icmph(struct icmp6_hdr *, u_char *); -static void pr_iph(struct ip6_hdr *); -static void pr_suptypes(struct icmp6_nodeinfo *, size_t); -static void pr_nodeaddr(struct icmp6_nodeinfo *, int); -static int myechoreply(const struct icmp6_hdr *); -static int mynireply(const struct icmp6_nodeinfo *); -static const char *dnsdecode(const u_char *, const u_char *, const u_char *, - char *, size_t); -static void pr_pack(u_char *, int, struct msghdr *); -static void pr_exthdrs(struct msghdr *); -static void pr_ip6opt(void *, size_t); -static void pr_rthdr(void *, size_t); -static int pr_bitrange(u_int32_t, int, int); -static void pr_retip(struct ip6_hdr *, u_char *); -static void summary(void); -static int setpolicy(int, char *); -static char *nigroup(char *, int); -static void usage(void); - -int -main(int argc, char *argv[]) -{ - struct timespec last, intvl; - struct sockaddr_in6 from, *sin6; - struct addrinfo hints, *res; - struct sigaction si_sa; - int cc, i; - int almost_done, ch, hold, packlen, preload, optval, error; - int nig_oldmcprefix = -1; - u_char *datap; - char *e, *target, *ifname = NULL, *gateway = NULL; - int ip6optlen = 0; - struct cmsghdr *scmsgp = NULL; - /* For control (ancillary) data received from recvmsg() */ - u_char cm[CONTROLLEN]; -#if defined(SO_SNDBUF) && defined(SO_RCVBUF) - u_long lsockbufsize; - int sockbufsize = 0; -#endif - int usepktinfo = 0; - struct in6_pktinfo pktinfo; - char *cmsg_pktinfo = NULL; - struct ip6_rthdr *rthdr = NULL; -#ifdef IPSEC_POLICY_IPSEC - char *policy_in = NULL; - char *policy_out = NULL; -#endif - double t; - u_long alarmtimeout; - size_t rthlen; -#ifdef IPV6_USE_MIN_MTU - int mflag = 0; -#endif - cap_rights_t rights_srecv; - cap_rights_t rights_ssend; - cap_rights_t rights_stdin; - - /* just to be sure */ - memset(&smsghdr, 0, sizeof(smsghdr)); - memset(&smsgiov, 0, sizeof(smsgiov)); - memset(&pktinfo, 0, sizeof(pktinfo)); - - intvl.tv_sec = interval / 1000; - intvl.tv_nsec = interval % 1000 * 1000000; - - alarmtimeout = preload = 0; - datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN]; - capdns = capdns_setup(); -#ifndef IPSEC -#define ADDOPTS -#else -#ifdef IPSEC_POLICY_IPSEC -#define ADDOPTS "P:" -#else -#define ADDOPTS "AE" -#endif /*IPSEC_POLICY_IPSEC*/ -#endif - while ((ch = getopt(argc, argv, - "a:b:c:DdfHg:h:I:i:l:mnNop:qrRS:s:tvwWx:X:z:" ADDOPTS)) != -1) { -#undef ADDOPTS - switch (ch) { - case 'a': - { - char *cp; - - options &= ~F_NOUSERDATA; - options |= F_NODEADDR; - for (cp = optarg; *cp != '\0'; cp++) { - switch (*cp) { - case 'a': - naflags |= NI_NODEADDR_FLAG_ALL; - break; - case 'c': - case 'C': - naflags |= NI_NODEADDR_FLAG_COMPAT; - break; - case 'l': - case 'L': - naflags |= NI_NODEADDR_FLAG_LINKLOCAL; - break; - case 's': - case 'S': - naflags |= NI_NODEADDR_FLAG_SITELOCAL; - break; - case 'g': - case 'G': - naflags |= NI_NODEADDR_FLAG_GLOBAL; - break; - case 'A': /* experimental. not in the spec */ -#ifdef NI_NODEADDR_FLAG_ANYCAST - naflags |= NI_NODEADDR_FLAG_ANYCAST; - break; -#else - errx(1, -"-a A is not supported on the platform"); - /*NOTREACHED*/ -#endif - default: - usage(); - /*NOTREACHED*/ - } - } - break; - } - case 'b': -#if defined(SO_SNDBUF) && defined(SO_RCVBUF) - errno = 0; - e = NULL; - lsockbufsize = strtoul(optarg, &e, 10); - sockbufsize = (int)lsockbufsize; - if (errno || !*optarg || *e || - lsockbufsize > INT_MAX) - errx(1, "invalid socket buffer size"); -#else - errx(1, -"-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported"); -#endif - break; - case 'c': - npackets = strtol(optarg, &e, 10); - if (npackets <= 0 || *optarg == '\0' || *e != '\0') - errx(1, - "illegal number of packets -- %s", optarg); - break; - case 'D': - options |= F_DONTFRAG; - break; - case 'd': - options |= F_SO_DEBUG; - break; - case 'f': - if (getuid()) { - errno = EPERM; - errx(1, "Must be superuser to flood ping"); - } - options |= F_FLOOD; - setbuf(stdout, (char *)NULL); - break; - case 'g': - gateway = optarg; - break; - case 'H': - options |= F_HOSTNAME; - break; - case 'h': /* hoplimit */ - hoplimit = strtol(optarg, &e, 10); - if (*optarg == '\0' || *e != '\0') - errx(1, "illegal hoplimit %s", optarg); - if (255 < hoplimit || hoplimit < -1) - errx(1, - "illegal hoplimit -- %s", optarg); - break; - case 'I': - ifname = optarg; - options |= F_INTERFACE; -#ifndef USE_SIN6_SCOPE_ID - usepktinfo++; -#endif - break; - case 'i': /* wait between sending packets */ - t = strtod(optarg, &e); - if (*optarg == '\0' || *e != '\0') - errx(1, "illegal timing interval %s", optarg); - if (t < 1 && getuid()) { - errx(1, "%s: only root may use interval < 1s", - strerror(EPERM)); - } - intvl.tv_sec = (time_t)t; - intvl.tv_nsec = - (long)((t - intvl.tv_sec) * 1000000000); - if (intvl.tv_sec < 0) - errx(1, "illegal timing interval %s", optarg); - /* less than 1/hz does not make sense */ - if (intvl.tv_sec == 0 && intvl.tv_nsec < 1000) { - warnx("too small interval, raised to .000001"); - intvl.tv_nsec = 1000; - } - options |= F_INTERVAL; - break; - case 'l': - if (getuid()) { - errno = EPERM; - errx(1, "Must be superuser to preload"); - } - preload = strtol(optarg, &e, 10); - if (preload < 0 || *optarg == '\0' || *e != '\0') - errx(1, "illegal preload value -- %s", optarg); - break; - case 'm': -#ifdef IPV6_USE_MIN_MTU - mflag++; - break; -#else - errx(1, "-%c is not supported on this platform", ch); - /*NOTREACHED*/ -#endif - case 'n': - options &= ~F_HOSTNAME; - break; - case 'N': - options |= F_NIGROUP; - nig_oldmcprefix++; - break; - case 'o': - options |= F_ONCE; - break; - case 'p': /* fill buffer with user pattern */ - options |= F_PINGFILLED; - fill((char *)datap, optarg); - break; - case 'q': - options |= F_QUIET; - break; - case 'r': - options |= F_AUDIBLE; - break; - case 'R': - options |= F_MISSED; - break; - case 'S': - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */ - hints.ai_family = AF_INET6; - hints.ai_socktype = SOCK_RAW; - hints.ai_protocol = IPPROTO_ICMPV6; - - error = cap_getaddrinfo(capdns, optarg, NULL, &hints, &res); - if (error) { - errx(1, "invalid source address: %s", - gai_strerror(error)); - } - /* - * res->ai_family must be AF_INET6 and res->ai_addrlen - * must be sizeof(src). - */ - memcpy(&src, res->ai_addr, res->ai_addrlen); - srclen = res->ai_addrlen; - freeaddrinfo(res); - options |= F_SRCADDR; - break; - case 's': /* size of packet to send */ - datalen = strtol(optarg, &e, 10); - if (datalen <= 0 || *optarg == '\0' || *e != '\0') - errx(1, "illegal datalen value -- %s", optarg); - if (datalen > MAXDATALEN) { - errx(1, - "datalen value too large, maximum is %d", - MAXDATALEN); - } - break; - case 't': - options &= ~F_NOUSERDATA; - options |= F_SUPTYPES; - break; - case 'v': - options |= F_VERBOSE; - break; - case 'w': - options &= ~F_NOUSERDATA; - options |= F_FQDN; - break; - case 'W': - options &= ~F_NOUSERDATA; - options |= F_FQDNOLD; - break; - case 'x': - t = strtod(optarg, &e); - if (*e || e == optarg || t > (double)INT_MAX) - err(EX_USAGE, "invalid timing interval: `%s'", - optarg); - options |= F_WAITTIME; - waittime = (int)t; - break; - case 'X': - alarmtimeout = strtoul(optarg, &e, 0); - if ((alarmtimeout < 1) || (alarmtimeout == ULONG_MAX)) - errx(EX_USAGE, "invalid timeout: `%s'", - optarg); - if (alarmtimeout > MAXALARM) - errx(EX_USAGE, "invalid timeout: `%s' > %d", - optarg, MAXALARM); - alarm((int)alarmtimeout); - break; - case 'z': /* traffic class */ - tclass = strtol(optarg, &e, 10); - if (*optarg == '\0' || *e != '\0') - errx(1, "illegal traffic class %s", optarg); - if (255 < tclass || tclass < -1) - errx(1, - "illegal traffic class -- %s", optarg); - break; -#ifdef IPSEC -#ifdef IPSEC_POLICY_IPSEC - case 'P': - options |= F_POLICY; - if (!strncmp("in", optarg, 2)) { - if ((policy_in = strdup(optarg)) == NULL) - errx(1, "strdup"); - } else if (!strncmp("out", optarg, 3)) { - if ((policy_out = strdup(optarg)) == NULL) - errx(1, "strdup"); - } else - errx(1, "invalid security policy"); - break; -#else - case 'A': - options |= F_AUTHHDR; - break; - case 'E': - options |= F_ENCRYPT; - break; -#endif /*IPSEC_POLICY_IPSEC*/ -#endif /*IPSEC*/ - default: - usage(); - /*NOTREACHED*/ - } - } - - argc -= optind; - argv += optind; - - if (argc < 1) { - usage(); - /*NOTREACHED*/ - } - - if (argc > 1) { -#ifdef IPV6_RECVRTHDR /* 2292bis */ - rthlen = CMSG_SPACE(inet6_rth_space(IPV6_RTHDR_TYPE_0, - argc - 1)); -#else /* RFC2292 */ - rthlen = inet6_rthdr_space(IPV6_RTHDR_TYPE_0, argc - 1); -#endif - if (rthlen == 0) { - errx(1, "too many intermediate hops"); - /*NOTREACHED*/ - } - ip6optlen += rthlen; - } - - if (options & F_NIGROUP) { - target = nigroup(argv[argc - 1], nig_oldmcprefix); - if (target == NULL) { - usage(); - /*NOTREACHED*/ - } - } else - target = argv[argc - 1]; - - /* cap_getaddrinfo */ - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_flags = AI_CANONNAME; - hints.ai_family = AF_INET6; - hints.ai_socktype = SOCK_RAW; - hints.ai_protocol = IPPROTO_ICMPV6; - - error = cap_getaddrinfo(capdns, target, NULL, &hints, &res); - if (error) - errx(1, "%s", gai_strerror(error)); - if (res->ai_canonname) - hostname = strdup(res->ai_canonname); - else - hostname = target; - - if (!res->ai_addr) - errx(1, "cap_getaddrinfo failed"); - - (void)memcpy(&dst, res->ai_addr, res->ai_addrlen); - - if ((ssend = socket(res->ai_family, res->ai_socktype, - res->ai_protocol)) < 0) - err(1, "socket ssend"); - if ((srecv = socket(res->ai_family, res->ai_socktype, - res->ai_protocol)) < 0) - err(1, "socket srecv"); - freeaddrinfo(res); - - /* set the source address if specified. */ - if ((options & F_SRCADDR) != 0) { - /* properly fill sin6_scope_id */ - if (IN6_IS_ADDR_LINKLOCAL(&src.sin6_addr) && ( - IN6_IS_ADDR_LINKLOCAL(&dst.sin6_addr) || - IN6_IS_ADDR_MC_LINKLOCAL(&dst.sin6_addr) || - IN6_IS_ADDR_MC_NODELOCAL(&dst.sin6_addr))) { - if (src.sin6_scope_id == 0) - src.sin6_scope_id = dst.sin6_scope_id; - if (dst.sin6_scope_id == 0) - dst.sin6_scope_id = src.sin6_scope_id; - } - if (bind(ssend, (struct sockaddr *)&src, srclen) != 0) - err(1, "bind"); - } - /* set the gateway (next hop) if specified */ - if (gateway) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET6; - hints.ai_socktype = SOCK_RAW; - hints.ai_protocol = IPPROTO_ICMPV6; - - error = cap_getaddrinfo(capdns, gateway, NULL, &hints, &res); - if (error) { - errx(1, "cap_getaddrinfo for the gateway %s: %s", - gateway, gai_strerror(error)); - } - if (res->ai_next && (options & F_VERBOSE)) - warnx("gateway resolves to multiple addresses"); - - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_NEXTHOP, - res->ai_addr, res->ai_addrlen)) { - err(1, "setsockopt(IPV6_NEXTHOP)"); - } - - freeaddrinfo(res); - } - - /* - * let the kerel pass extension headers of incoming packets, - * for privileged socket options - */ - if ((options & F_VERBOSE) != 0) { - int opton = 1; - -#ifdef IPV6_RECVHOPOPTS - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_RECVHOPOPTS)"); -#else /* old adv. API */ - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPOPTS, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_HOPOPTS)"); -#endif -#ifdef IPV6_RECVDSTOPTS - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_RECVDSTOPTS)"); -#else /* old adv. API */ - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_DSTOPTS, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_DSTOPTS)"); -#endif -#ifdef IPV6_RECVRTHDRDSTOPTS - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDRDSTOPTS, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_RECVRTHDRDSTOPTS)"); -#endif - } - - /* revoke root privilege */ - if (seteuid(getuid()) != 0) - err(1, "seteuid() failed"); - if (setuid(getuid()) != 0) - err(1, "setuid() failed"); - - if ((options & F_FLOOD) && (options & F_INTERVAL)) - errx(1, "-f and -i incompatible options"); - - if ((options & F_NOUSERDATA) == 0) { - if (datalen >= sizeof(struct tv32)) { - /* we can time transfer */ - timing = 1; - } else - timing = 0; - /* in F_VERBOSE case, we may get non-echoreply packets*/ - if (options & F_VERBOSE) - packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA; - else - packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA; - } else { - /* suppress timing for node information query */ - timing = 0; - datalen = 2048; - packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA; - } - - if (!(packet = (u_char *)malloc((u_int)packlen))) - err(1, "Unable to allocate packet"); - if (!(options & F_PINGFILLED)) - for (i = ICMP6ECHOLEN; i < packlen; ++i) - *datap++ = i; - - ident = getpid() & 0xFFFF; - arc4random_buf(nonce, sizeof(nonce)); - optval = 1; - if (options & F_DONTFRAG) - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_DONTFRAG, - &optval, sizeof(optval)) == -1) - err(1, "IPV6_DONTFRAG"); - hold = 1; - - if (options & F_SO_DEBUG) { - (void)setsockopt(ssend, SOL_SOCKET, SO_DEBUG, (char *)&hold, - sizeof(hold)); - (void)setsockopt(srecv, SOL_SOCKET, SO_DEBUG, (char *)&hold, - sizeof(hold)); - } - optval = IPV6_DEFHLIM; - if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr)) - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - &optval, sizeof(optval)) == -1) - err(1, "IPV6_MULTICAST_HOPS"); -#ifdef IPV6_USE_MIN_MTU - if (mflag != 1) { - optval = mflag > 1 ? 0 : 1; - - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_USE_MIN_MTU, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_USE_MIN_MTU)"); - } -#ifdef IPV6_RECVPATHMTU - else { - optval = 1; - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPATHMTU, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_RECVPATHMTU)"); - } -#endif /* IPV6_RECVPATHMTU */ -#endif /* IPV6_USE_MIN_MTU */ - -#ifdef IPSEC -#ifdef IPSEC_POLICY_IPSEC - if (options & F_POLICY) { - if (setpolicy(srecv, policy_in) < 0) - errx(1, "%s", ipsec_strerror()); - if (setpolicy(ssend, policy_out) < 0) - errx(1, "%s", ipsec_strerror()); - } -#else - if (options & F_AUTHHDR) { - optval = IPSEC_LEVEL_REQUIRE; -#ifdef IPV6_AUTH_TRANS_LEVEL - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)"); - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_TRANS_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_AUTH_TRANS_LEVEL)"); -#else /* old def */ - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_AUTH_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_AUTH_LEVEL)"); - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_AUTH_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_AUTH_LEVEL)"); -#endif - } - if (options & F_ENCRYPT) { - optval = IPSEC_LEVEL_REQUIRE; - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)"); - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_ESP_TRANS_LEVEL, - &optval, sizeof(optval)) == -1) - err(1, "setsockopt(IPV6_ESP_TRANS_LEVEL)"); - } -#endif /*IPSEC_POLICY_IPSEC*/ -#endif - -#ifdef ICMP6_FILTER - { - struct icmp6_filter filt; - if (!(options & F_VERBOSE)) { - ICMP6_FILTER_SETBLOCKALL(&filt); - if ((options & F_FQDN) || (options & F_FQDNOLD) || - (options & F_NODEADDR) || (options & F_SUPTYPES)) - ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt); - else - ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt); - } else { - ICMP6_FILTER_SETPASSALL(&filt); - } - if (setsockopt(srecv, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, - sizeof(filt)) < 0) - err(1, "setsockopt(ICMP6_FILTER)"); - } -#endif /*ICMP6_FILTER*/ - - /* let the kerel pass extension headers of incoming packets */ - if ((options & F_VERBOSE) != 0) { - int opton = 1; - -#ifdef IPV6_RECVRTHDR - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_RECVRTHDR)"); -#else /* old adv. API */ - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RTHDR, &opton, - sizeof(opton))) - err(1, "setsockopt(IPV6_RTHDR)"); -#endif - } - -/* - optval = 1; - if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr)) - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, - &optval, sizeof(optval)) == -1) - err(1, "IPV6_MULTICAST_LOOP"); -*/ - - /* Specify the outgoing interface and/or the source address */ - if (usepktinfo) - ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo)); - - if (hoplimit != -1) - ip6optlen += CMSG_SPACE(sizeof(int)); - - /* set IP6 packet options */ - if (ip6optlen) { - if ((scmsg = (char *)malloc(ip6optlen)) == NULL) - errx(1, "can't allocate enough memory"); - smsghdr.msg_control = (caddr_t)scmsg; - smsghdr.msg_controllen = ip6optlen; - scmsgp = CMSG_FIRSTHDR(&smsghdr); - } - if (usepktinfo) { - cmsg_pktinfo = CMSG_DATA(scmsgp); - scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); - scmsgp->cmsg_level = IPPROTO_IPV6; - scmsgp->cmsg_type = IPV6_PKTINFO; - scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); - } - - /* set the outgoing interface */ - if (ifname) { -#ifndef USE_SIN6_SCOPE_ID - /* pktinfo must have already been allocated */ - if ((pktinfo.ipi6_ifindex = if_nametoindex(ifname)) == 0) - errx(1, "%s: invalid interface name", ifname); -#else - if ((dst.sin6_scope_id = if_nametoindex(ifname)) == 0) - errx(1, "%s: invalid interface name", ifname); -#endif - } - if (hoplimit != -1) { - scmsgp->cmsg_len = CMSG_LEN(sizeof(int)); - scmsgp->cmsg_level = IPPROTO_IPV6; - scmsgp->cmsg_type = IPV6_HOPLIMIT; - memcpy(CMSG_DATA(scmsgp), &hoplimit, sizeof(hoplimit)); - - scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); - } - - if (tclass != -1) { - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_TCLASS, - &tclass, sizeof(tclass)) == -1) - err(1, "setsockopt(IPV6_TCLASS)"); - } - - if (argc > 1) { /* some intermediate addrs are specified */ - int hops; - int rthdrlen; - - rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1); - scmsgp->cmsg_len = CMSG_LEN(rthdrlen); - scmsgp->cmsg_level = IPPROTO_IPV6; - scmsgp->cmsg_type = IPV6_RTHDR; - rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp); - rthdr = inet6_rth_init((void *)rthdr, rthdrlen, - IPV6_RTHDR_TYPE_0, argc - 1); - if (rthdr == NULL) - errx(1, "can't initialize rthdr"); - - for (hops = 0; hops < argc - 1; hops++) { - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET6; - - if ((error = cap_getaddrinfo(capdns, argv[hops], NULL, &hints, - &res))) - errx(1, "%s", gai_strerror(error)); - if (res->ai_addr->sa_family != AF_INET6) - errx(1, - "bad addr family of an intermediate addr"); - sin6 = (struct sockaddr_in6 *)(void *)res->ai_addr; - if (inet6_rth_add(rthdr, &sin6->sin6_addr)) - errx(1, "can't add an intermediate node"); - freeaddrinfo(res); - } - - scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); - } - - /* From now on we will use only reverse DNS lookups. */ -#ifdef WITH_CASPER - if (capdns != NULL) { - const char *types[1]; - - types[0] = "ADDR2NAME"; - if (cap_dns_type_limit(capdns, types, nitems(types)) < 0) - err(1, "unable to limit access to system.dns service"); - } -#endif - if (!(options & F_SRCADDR)) { - /* - * get the source address. XXX since we revoked the root - * privilege, we cannot use a raw socket for this. - */ - int dummy; - socklen_t len = sizeof(src); - - if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) - err(1, "UDP socket"); - - src.sin6_family = AF_INET6; - src.sin6_addr = dst.sin6_addr; - src.sin6_port = ntohs(DUMMY_PORT); - src.sin6_scope_id = dst.sin6_scope_id; - - if (usepktinfo && - setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO, - (void *)&pktinfo, sizeof(pktinfo))) - err(1, "UDP setsockopt(IPV6_PKTINFO)"); - - if (hoplimit != -1 && - setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS, - (void *)&hoplimit, sizeof(hoplimit))) - err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)"); - - if (hoplimit != -1 && - setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, - (void *)&hoplimit, sizeof(hoplimit))) - err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)"); - - if (rthdr && - setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR, - (void *)rthdr, (rthdr->ip6r_len + 1) << 3)) - err(1, "UDP setsockopt(IPV6_RTHDR)"); - - if (connect(dummy, (struct sockaddr *)&src, len) < 0) - err(1, "UDP connect"); - - if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0) - err(1, "getsockname"); - - close(dummy); - } - - /* Save pktinfo in the ancillary data. */ - if (usepktinfo) - memcpy(cmsg_pktinfo, &pktinfo, sizeof(pktinfo)); - - if (connect(ssend, (struct sockaddr *)&dst, sizeof(dst)) != 0) - err(1, "connect() ssend"); - - caph_cache_catpages(); - if (caph_enter_casper() < 0) - err(1, "caph_enter_casper"); - - cap_rights_init(&rights_stdin); - if (caph_rights_limit(STDIN_FILENO, &rights_stdin) < 0) - err(1, "caph_rights_limit stdin"); - if (caph_limit_stdout() < 0) - err(1, "caph_limit_stdout"); - if (caph_limit_stderr() < 0) - err(1, "caph_limit_stderr"); - - cap_rights_init(&rights_srecv, CAP_RECV, CAP_EVENT, CAP_SETSOCKOPT); - if (caph_rights_limit(srecv, &rights_srecv) < 0) - err(1, "caph_rights_limit srecv"); - cap_rights_init(&rights_ssend, CAP_SEND, CAP_SETSOCKOPT); - if (caph_rights_limit(ssend, &rights_ssend) < 0) - err(1, "caph_rights_limit ssend"); - -#if defined(SO_SNDBUF) && defined(SO_RCVBUF) - if (sockbufsize) { - if (datalen > (size_t)sockbufsize) - warnx("you need -b to increase socket buffer size"); - if (setsockopt(ssend, SOL_SOCKET, SO_SNDBUF, &sockbufsize, - sizeof(sockbufsize)) < 0) - err(1, "setsockopt(SO_SNDBUF)"); - if (setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, &sockbufsize, - sizeof(sockbufsize)) < 0) - err(1, "setsockopt(SO_RCVBUF)"); - } - else { - if (datalen > 8 * 1024) /*XXX*/ - warnx("you need -b to increase socket buffer size"); - /* - * When pinging the broadcast address, you can get a lot of - * answers. Doing something so evil is useful if you are trying - * to stress the ethernet, or just want to fill the arp cache - * to get some stuff for /etc/ethers. - */ - hold = 48 * 1024; - setsockopt(srecv, SOL_SOCKET, SO_RCVBUF, (char *)&hold, - sizeof(hold)); - } -#endif - - optval = 1; -#ifndef USE_SIN6_SCOPE_ID -#ifdef IPV6_RECVPKTINFO - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval, - sizeof(optval)) < 0) - warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */ -#else /* old adv. API */ - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_PKTINFO, &optval, - sizeof(optval)) < 0) - warn("setsockopt(IPV6_PKTINFO)"); /* XXX err? */ -#endif -#endif /* USE_SIN6_SCOPE_ID */ -#ifdef IPV6_RECVHOPLIMIT - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval, - sizeof(optval)) < 0) - warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */ -#else /* old adv. API */ - if (setsockopt(srecv, IPPROTO_IPV6, IPV6_HOPLIMIT, &optval, - sizeof(optval)) < 0) - warn("setsockopt(IPV6_HOPLIMIT)"); /* XXX err? */ -#endif - - cap_rights_clear(&rights_srecv, CAP_SETSOCKOPT); - if (caph_rights_limit(srecv, &rights_srecv) < 0) - err(1, "caph_rights_limit srecv setsockopt"); - cap_rights_clear(&rights_ssend, CAP_SETSOCKOPT); - if (caph_rights_limit(ssend, &rights_ssend) < 0) - err(1, "caph_rights_limit ssend setsockopt"); - - printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()), - (unsigned long)(pingerlen() - 8)); - printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src))); - printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst))); - - if (preload == 0) - pinger(); - else { - if (npackets != 0 && preload > npackets) - preload = npackets; - while (preload--) - pinger(); - } - clock_gettime(CLOCK_MONOTONIC, &last); - - sigemptyset(&si_sa.sa_mask); - si_sa.sa_flags = 0; - si_sa.sa_handler = onsignal; - if (sigaction(SIGINT, &si_sa, 0) == -1) - err(EX_OSERR, "sigaction SIGINT"); - seenint = 0; -#ifdef SIGINFO - if (sigaction(SIGINFO, &si_sa, 0) == -1) - err(EX_OSERR, "sigaction SIGINFO"); - seeninfo = 0; -#endif - if (alarmtimeout > 0) { - if (sigaction(SIGALRM, &si_sa, 0) == -1) - err(EX_OSERR, "sigaction SIGALRM"); - } - if (options & F_FLOOD) { - intvl.tv_sec = 0; - intvl.tv_nsec = 10000000; - } - - almost_done = 0; - while (seenint == 0) { - struct timespec now, timeout; - struct msghdr m; - struct iovec iov[2]; - fd_set rfds; - int n; - - /* signal handling */ - if (seenint) - onint(SIGINT); -#ifdef SIGINFO - if (seeninfo) { - summary(); - seeninfo = 0; - continue; - } -#endif - FD_ZERO(&rfds); - FD_SET(srecv, &rfds); - clock_gettime(CLOCK_MONOTONIC, &now); - timespecadd(&last, &intvl, &timeout); - timespecsub(&timeout, &now, &timeout); - if (timeout.tv_sec < 0) - timespecclear(&timeout); - - n = pselect(srecv + 1, &rfds, NULL, NULL, &timeout, NULL); - if (n < 0) - continue; /* EINTR */ - if (n == 1) { - m.msg_name = (caddr_t)&from; - m.msg_namelen = sizeof(from); - memset(&iov, 0, sizeof(iov)); - iov[0].iov_base = (caddr_t)packet; - iov[0].iov_len = packlen; - m.msg_iov = iov; - m.msg_iovlen = 1; - memset(cm, 0, CONTROLLEN); - m.msg_control = (void *)cm; - m.msg_controllen = CONTROLLEN; - - cc = recvmsg(srecv, &m, 0); - if (cc < 0) { - if (errno != EINTR) { - warn("recvmsg"); - sleep(1); - } - continue; - } else if (cc == 0) { - int mtu; - - /* - * receive control messages only. Process the - * exceptions (currently the only possibility is - * a path MTU notification.) - */ - if ((mtu = get_pathmtu(&m)) > 0) { - if ((options & F_VERBOSE) != 0) { - printf("new path MTU (%d) is " - "notified\n", mtu); - } - } - continue; - } else { - /* - * an ICMPv6 message (probably an echoreply) - * arrived. - */ - pr_pack(packet, cc, &m); - } - if (((options & F_ONCE) != 0 && nreceived > 0) || - (npackets > 0 && nreceived >= npackets)) - break; - } - if (n == 0 || (options & F_FLOOD)) { - if (npackets == 0 || ntransmitted < npackets) - pinger(); - else { - if (almost_done) - break; - almost_done = 1; - /* - * If we're not transmitting any more packets, - * change the timer to wait two round-trip times - * if we've received any packets or (waittime) - * milliseconds if we haven't. - */ - intvl.tv_nsec = 0; - if (nreceived) { - intvl.tv_sec = 2 * tmax / 1000; - if (intvl.tv_sec == 0) - intvl.tv_sec = 1; - } else { - intvl.tv_sec = waittime / 1000; - intvl.tv_nsec = - waittime % 1000 * 1000000; - } - } - clock_gettime(CLOCK_MONOTONIC, &last); - if (ntransmitted - nreceived - 1 > nmissedmax) { - nmissedmax = ntransmitted - nreceived - 1; - if (options & F_MISSED) - (void)write(STDOUT_FILENO, &BBELL, 1); - } - } - } - sigemptyset(&si_sa.sa_mask); - si_sa.sa_flags = 0; - si_sa.sa_handler = SIG_IGN; - sigaction(SIGINT, &si_sa, 0); - sigaction(SIGALRM, &si_sa, 0); - summary(); - - if(packet != NULL) - free(packet); - - exit(nreceived == 0 ? 2 : 0); -} - -static void -onsignal(int sig) -{ - - switch (sig) { - case SIGINT: - case SIGALRM: - seenint++; - break; -#ifdef SIGINFO - case SIGINFO: - seeninfo++; - break; -#endif - } -} - -/* - * pinger -- - * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet - * will be added on by the kernel. The ID field is our UNIX process ID, - * and the sequence number is an ascending integer. The first 8 bytes - * of the data portion are used to hold a UNIX "timespec" struct in VAX - * byte-order, to compute the round-trip time. - */ -static size_t -pingerlen(void) -{ - size_t l; - - if (options & F_FQDN) - l = ICMP6_NIQLEN + sizeof(dst.sin6_addr); - else if (options & F_FQDNOLD) - l = ICMP6_NIQLEN; - else if (options & F_NODEADDR) - l = ICMP6_NIQLEN + sizeof(dst.sin6_addr); - else if (options & F_SUPTYPES) - l = ICMP6_NIQLEN; - else - l = ICMP6ECHOLEN + datalen; - - return l; -} - -static int -pinger(void) -{ - struct icmp6_hdr *icp; - struct iovec iov[2]; - int i, cc; - struct icmp6_nodeinfo *nip; - uint16_t seq; - - if (npackets && ntransmitted >= npackets) - return(-1); /* no more transmission */ - - icp = (struct icmp6_hdr *)outpack; - nip = (struct icmp6_nodeinfo *)outpack; - memset(icp, 0, sizeof(*icp)); - icp->icmp6_cksum = 0; - seq = ntransmitted++; - CLR(seq % mx_dup_ck); - - if (options & F_FQDN) { - uint16_t s; - - icp->icmp6_type = ICMP6_NI_QUERY; - icp->icmp6_code = ICMP6_NI_SUBJ_IPV6; - nip->ni_qtype = htons(NI_QTYPE_FQDN); - nip->ni_flags = htons(0); - - memcpy(nip->icmp6_ni_nonce, nonce, - sizeof(nip->icmp6_ni_nonce)); - s = htons(seq); - memcpy(nip->icmp6_ni_nonce, &s, sizeof(s)); - - memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr, - sizeof(dst.sin6_addr)); - cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr); - datalen = 0; - } else if (options & F_FQDNOLD) { - uint16_t s; - /* packet format in 03 draft - no Subject data on queries */ - icp->icmp6_type = ICMP6_NI_QUERY; - icp->icmp6_code = 0; /* code field is always 0 */ - nip->ni_qtype = htons(NI_QTYPE_FQDN); - nip->ni_flags = htons(0); - - memcpy(nip->icmp6_ni_nonce, nonce, - sizeof(nip->icmp6_ni_nonce)); - s = htons(seq); - memcpy(nip->icmp6_ni_nonce, &s, sizeof(s)); - - cc = ICMP6_NIQLEN; - datalen = 0; - } else if (options & F_NODEADDR) { - uint16_t s; - - icp->icmp6_type = ICMP6_NI_QUERY; - icp->icmp6_code = ICMP6_NI_SUBJ_IPV6; - nip->ni_qtype = htons(NI_QTYPE_NODEADDR); - nip->ni_flags = naflags; - - memcpy(nip->icmp6_ni_nonce, nonce, - sizeof(nip->icmp6_ni_nonce)); - s = htons(seq); - memcpy(nip->icmp6_ni_nonce, &s, sizeof(s)); - - memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr, - sizeof(dst.sin6_addr)); - cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr); - datalen = 0; - } else if (options & F_SUPTYPES) { - uint16_t s; - - icp->icmp6_type = ICMP6_NI_QUERY; - icp->icmp6_code = ICMP6_NI_SUBJ_FQDN; /*empty*/ - nip->ni_qtype = htons(NI_QTYPE_SUPTYPES); - /* we support compressed bitmap */ - nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS; - - memcpy(nip->icmp6_ni_nonce, nonce, - sizeof(nip->icmp6_ni_nonce)); - s = htons(seq); - memcpy(nip->icmp6_ni_nonce, &s, sizeof(s)); - - cc = ICMP6_NIQLEN; - datalen = 0; - } else { - icp->icmp6_type = ICMP6_ECHO_REQUEST; - icp->icmp6_code = 0; - icp->icmp6_id = htons(ident); - icp->icmp6_seq = htons(seq); - if (timing) { - struct timespec tv; - struct tv32 tv32; - (void)clock_gettime(CLOCK_MONOTONIC, &tv); - /* - * Truncate seconds down to 32 bits in order - * to fit the timestamp within 8 bytes of the - * packet. We're only concerned with - * durations, not absolute times. - */ - tv32.tv32_sec = (uint32_t)htonl(tv.tv_sec); - tv32.tv32_nsec = (uint32_t)htonl(tv.tv_nsec); - memcpy(&outpack[ICMP6ECHOLEN], &tv32, sizeof(tv32)); - } - cc = ICMP6ECHOLEN + datalen; - } - -#ifdef DIAGNOSTIC - if (pingerlen() != cc) - errx(1, "internal error; length mismatch"); -#endif - - memset(&iov, 0, sizeof(iov)); - iov[0].iov_base = (caddr_t)outpack; - iov[0].iov_len = cc; - smsghdr.msg_iov = iov; - smsghdr.msg_iovlen = 1; - - i = sendmsg(ssend, &smsghdr, 0); - - if (i < 0 || i != cc) { - if (i < 0) - warn("sendmsg"); - (void)printf("ping6: wrote %s %d chars, ret=%d\n", - hostname, cc, i); - } - if (!(options & F_QUIET) && options & F_FLOOD) - (void)write(STDOUT_FILENO, &DOT, 1); - - return(0); -} - -static int -myechoreply(const struct icmp6_hdr *icp) -{ - if (ntohs(icp->icmp6_id) == ident) - return 1; - else - return 0; -} - -static int -mynireply(const struct icmp6_nodeinfo *nip) -{ - if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t), - nonce + sizeof(u_int16_t), - sizeof(nonce) - sizeof(u_int16_t)) == 0) - return 1; - else - return 0; -} - -/* - * Decode a name from a DNS message. - * - * Format of the message is described in RFC 1035 subsection 4.1.4. - * - * Arguments: - * sp - Pointer to a DNS pointer octet or to the first octet of a label - * in the message. - * ep - Pointer to the end of the message (one step past the last octet). - * base - Pointer to the beginning of the message. - * buf - Buffer into which the decoded name will be saved. - * bufsiz - Size of the buffer 'buf'. - * - * Return value: - * Pointer to an octet immediately following the ending zero octet - * of the decoded label, or NULL if an error occurred. - */ -static const char * -dnsdecode(const u_char *sp, const u_char *ep, const u_char *base, char *buf, - size_t bufsiz) -{ - int i; - const u_char *cp; - char cresult[MAXDNAME + 1]; - const u_char *comp; - int l; - - cp = sp; - *buf = '\0'; - - if (cp >= ep) - return NULL; - while (cp < ep) { - i = *cp; - if (i == 0 || cp != sp) { - if (strlcat((char *)buf, ".", bufsiz) >= bufsiz) - return NULL; /*result overrun*/ - } - if (i == 0) - break; - cp++; - - if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) { - /* DNS compression */ - if (!base) - return NULL; - - comp = base + (i & 0x3f); - if (dnsdecode(comp, cp, base, cresult, - sizeof(cresult)) == NULL) - return NULL; - if (strlcat(buf, cresult, bufsiz) >= bufsiz) - return NULL; /*result overrun*/ - break; - } else if ((i & 0x3f) == i) { - if (i > ep - cp) - return NULL; /*source overrun*/ - while (i-- > 0 && cp < ep) { - l = snprintf(cresult, sizeof(cresult), - isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff); - if ((size_t)l >= sizeof(cresult) || l < 0) - return NULL; - if (strlcat(buf, cresult, bufsiz) >= bufsiz) - return NULL; /*result overrun*/ - cp++; - } - } else - return NULL; /*invalid label*/ - } - if (i != 0) - return NULL; /*not terminated*/ - cp++; - return cp; -} - -/* - * pr_pack -- - * Print out the packet, if it came from us. This logic is necessary - * because ALL readers of the ICMP socket get a copy of ALL ICMP packets - * which arrive ('tis only fair). This permits multiple copies of this - * program to be run without having intermingled output (or statistics!). - */ -static void -pr_pack(u_char *buf, int cc, struct msghdr *mhdr) -{ -#define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c) - struct icmp6_hdr *icp; - struct icmp6_nodeinfo *ni; - int i; - int hoplim; - struct sockaddr *from; - int fromlen; - const u_char *cp = NULL; - u_char *dp, *end = buf + cc; - struct in6_pktinfo *pktinfo = NULL; - struct timespec tv, tp; - struct tv32 tpp; - double triptime = 0; - int dupflag; - size_t off; - int oldfqdn; - u_int16_t seq; - char dnsname[MAXDNAME + 1]; - - (void)clock_gettime(CLOCK_MONOTONIC, &tv); - - if (!mhdr || !mhdr->msg_name || - mhdr->msg_namelen != sizeof(struct sockaddr_in6) || - ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) { - if (options & F_VERBOSE) - warnx("invalid peername"); - return; - } - from = (struct sockaddr *)mhdr->msg_name; - fromlen = mhdr->msg_namelen; - if (cc < (int)sizeof(struct icmp6_hdr)) { - if (options & F_VERBOSE) - warnx("packet too short (%d bytes) from %s", cc, - pr_addr(from, fromlen)); - return; - } - if (((mhdr->msg_flags & MSG_CTRUNC) != 0) && - (options & F_VERBOSE) != 0) - warnx("some control data discarded, insufficient buffer size"); - icp = (struct icmp6_hdr *)buf; - ni = (struct icmp6_nodeinfo *)buf; - off = 0; - - if ((hoplim = get_hoplim(mhdr)) == -1) { - warnx("failed to get receiving hop limit"); - return; - } - if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) { - warnx("failed to get receiving packet information"); - return; - } - - if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) { - seq = ntohs(icp->icmp6_seq); - ++nreceived; - if (timing) { - memcpy(&tpp, icp + 1, sizeof(tpp)); - tp.tv_sec = ntohl(tpp.tv32_sec); - tp.tv_nsec = ntohl(tpp.tv32_nsec); - timespecsub(&tv, &tp, &tv); - triptime = ((double)tv.tv_sec) * 1000.0 + - ((double)tv.tv_nsec) / 1000000.0; - tsum += triptime; - tsumsq += triptime * triptime; - if (triptime < tmin) - tmin = triptime; - if (triptime > tmax) - tmax = triptime; - } - - if (TST(seq % mx_dup_ck)) { - ++nrepeats; - --nreceived; - dupflag = 1; - } else { - SET(seq % mx_dup_ck); - dupflag = 0; - } - - if (options & F_QUIET) - return; - - if (options & F_WAITTIME && triptime > waittime) { - ++nrcvtimeout; - return; - } - - if (options & F_FLOOD) - (void)write(STDOUT_FILENO, &BSPACE, 1); - else { - if (options & F_AUDIBLE) - (void)write(STDOUT_FILENO, &BBELL, 1); - (void)printf("%d bytes from %s, icmp_seq=%u", cc, - pr_addr(from, fromlen), seq); - (void)printf(" hlim=%d", hoplim); - if ((options & F_VERBOSE) != 0) { - struct sockaddr_in6 dstsa; - - memset(&dstsa, 0, sizeof(dstsa)); - dstsa.sin6_family = AF_INET6; - dstsa.sin6_len = sizeof(dstsa); - dstsa.sin6_scope_id = pktinfo->ipi6_ifindex; - dstsa.sin6_addr = pktinfo->ipi6_addr; - (void)printf(" dst=%s", - pr_addr((struct sockaddr *)&dstsa, - sizeof(dstsa))); - } - if (timing) - (void)printf(" time=%.3f ms", triptime); - if (dupflag) - (void)printf("(DUP!)"); - /* check the data */ - cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN; - dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN; - for (i = 8; cp < end; ++i, ++cp, ++dp) { - if (*cp != *dp) { - (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp); - break; - } - } - } - } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) { - memcpy(&seq, ni->icmp6_ni_nonce, sizeof(seq)); - seq = ntohs(seq); - ++nreceived; - if (TST(seq % mx_dup_ck)) { - ++nrepeats; - --nreceived; - dupflag = 1; - } else { - SET(seq % mx_dup_ck); - dupflag = 0; - } - - if (options & F_QUIET) - return; - - (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen)); - - switch (ntohs(ni->ni_code)) { - case ICMP6_NI_SUCCESS: - break; - case ICMP6_NI_REFUSED: - printf("refused, type 0x%x", ntohs(ni->ni_type)); - goto fqdnend; - case ICMP6_NI_UNKNOWN: - printf("unknown, type 0x%x", ntohs(ni->ni_type)); - goto fqdnend; - default: - printf("unknown code 0x%x, type 0x%x", - ntohs(ni->ni_code), ntohs(ni->ni_type)); - goto fqdnend; - } - - switch (ntohs(ni->ni_qtype)) { - case NI_QTYPE_NOOP: - printf("NodeInfo NOOP"); - break; - case NI_QTYPE_SUPTYPES: - pr_suptypes(ni, end - (u_char *)ni); - break; - case NI_QTYPE_NODEADDR: - pr_nodeaddr(ni, end - (u_char *)ni); - break; - case NI_QTYPE_FQDN: - default: /* XXX: for backward compatibility */ - cp = (u_char *)ni + ICMP6_NIRLEN; - if (buf[off + ICMP6_NIRLEN] == - cc - off - ICMP6_NIRLEN - 1) - oldfqdn = 1; - else - oldfqdn = 0; - if (oldfqdn) { - cp++; /* skip length */ - while (cp < end) { - safeputc(*cp & 0xff); - cp++; - } - } else { - i = 0; - while (cp < end) { - cp = dnsdecode((const u_char *)cp, end, - (const u_char *)(ni + 1), dnsname, - sizeof(dnsname)); - if (cp == NULL) { - printf("???"); - break; - } - /* - * name-lookup special handling for - * truncated name - */ - if (cp + 1 <= end && !*cp && - strlen(dnsname) > 0) { - dnsname[strlen(dnsname) - 1] = '\0'; - cp++; - } - printf("%s%s", i > 0 ? "," : "", - dnsname); - } - } - if (options & F_VERBOSE) { - u_long t; - int32_t ttl; - int comma = 0; - - (void)printf(" ("); /*)*/ - - switch (ni->ni_code) { - case ICMP6_NI_REFUSED: - (void)printf("refused"); - comma++; - break; - case ICMP6_NI_UNKNOWN: - (void)printf("unknown qtype"); - comma++; - break; - } - - if ((end - (u_char *)ni) < ICMP6_NIRLEN) { - /* case of refusion, unknown */ - /*(*/ - putchar(')'); - goto fqdnend; - } - memcpy(&t, &buf[off+ICMP6ECHOLEN+8], sizeof(t)); - ttl = (int32_t)ntohl(t); - if (comma) - printf(","); - if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) { - (void)printf("TTL=%d:meaningless", - (int)ttl); - } else { - if (ttl < 0) { - (void)printf("TTL=%d:invalid", - ttl); - } else - (void)printf("TTL=%d", ttl); - } - comma++; - - if (oldfqdn) { - if (comma) - printf(","); - printf("03 draft"); - comma++; - } else { - cp = (u_char *)ni + ICMP6_NIRLEN; - if (cp == end) { - if (comma) - printf(","); - printf("no name"); - comma++; - } - } - - if (buf[off + ICMP6_NIRLEN] != - cc - off - ICMP6_NIRLEN - 1 && oldfqdn) { - if (comma) - printf(","); - (void)printf("invalid namelen:%d/%lu", - buf[off + ICMP6_NIRLEN], - (u_long)cc - off - ICMP6_NIRLEN - 1); - comma++; - } - /*(*/ - putchar(')'); - } - fqdnend: - ; - } - } else { - /* We've got something other than an ECHOREPLY */ - if (!(options & F_VERBOSE)) - return; - (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen)); - pr_icmph(icp, end); - } - - if (!(options & F_FLOOD)) { - (void)putchar('\n'); - if (options & F_VERBOSE) - pr_exthdrs(mhdr); - (void)fflush(stdout); - } -#undef safeputc -} - -static void -pr_exthdrs(struct msghdr *mhdr) -{ - ssize_t bufsize; - void *bufp; - struct cmsghdr *cm; - - bufsize = 0; - bufp = mhdr->msg_control; - for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; - cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { - if (cm->cmsg_level != IPPROTO_IPV6) - continue; - - bufsize = CONTROLLEN - ((caddr_t)CMSG_DATA(cm) - (caddr_t)bufp); - if (bufsize <= 0) - continue; - switch (cm->cmsg_type) { - case IPV6_HOPOPTS: - printf(" HbH Options: "); - pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize); - break; - case IPV6_DSTOPTS: -#ifdef IPV6_RTHDRDSTOPTS - case IPV6_RTHDRDSTOPTS: -#endif - printf(" Dst Options: "); - pr_ip6opt(CMSG_DATA(cm), (size_t)bufsize); - break; - case IPV6_RTHDR: - printf(" Routing: "); - pr_rthdr(CMSG_DATA(cm), (size_t)bufsize); - break; - } - } -} - -static void -pr_ip6opt(void *extbuf, size_t bufsize) -{ - struct ip6_hbh *ext; - int currentlen; - u_int8_t type; - socklen_t extlen, len; - void *databuf; - size_t offset; - u_int16_t value2; - u_int32_t value4; - - ext = (struct ip6_hbh *)extbuf; - extlen = (ext->ip6h_len + 1) * 8; - printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt, - (unsigned int)ext->ip6h_len, (unsigned long)extlen); - - /* - * Bounds checking on the ancillary data buffer: - * subtract the size of a cmsg structure from the buffer size. - */ - if (bufsize < (extlen + CMSG_SPACE(0))) { - extlen = bufsize - CMSG_SPACE(0); - warnx("options truncated, showing only %u (total=%u)", - (unsigned int)(extlen / 8 - 1), - (unsigned int)(ext->ip6h_len)); - } - - currentlen = 0; - while (1) { - currentlen = inet6_opt_next(extbuf, extlen, currentlen, - &type, &len, &databuf); - if (currentlen == -1) - break; - switch (type) { - /* - * Note that inet6_opt_next automatically skips any padding - * optins. - */ - case IP6OPT_JUMBO: - offset = 0; - offset = inet6_opt_get_val(databuf, offset, - &value4, sizeof(value4)); - printf(" Jumbo Payload Opt: Length %u\n", - (u_int32_t)ntohl(value4)); - break; - case IP6OPT_ROUTER_ALERT: - offset = 0; - offset = inet6_opt_get_val(databuf, offset, - &value2, sizeof(value2)); - printf(" Router Alert Opt: Type %u\n", - ntohs(value2)); - break; - default: - printf(" Received Opt %u len %lu\n", - type, (unsigned long)len); - break; - } - } - return; -} - -static void -pr_rthdr(void *extbuf, size_t bufsize) -{ - struct in6_addr *in6; - char ntopbuf[INET6_ADDRSTRLEN]; - struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf; - int i, segments, origsegs, rthsize, size0, size1; - - /* print fixed part of the header */ - printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt, - rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type); - if ((segments = inet6_rth_segments(extbuf)) >= 0) { - printf("%d segments, ", segments); - printf("%d left\n", rh->ip6r_segleft); - } else { - printf("segments unknown, "); - printf("%d left\n", rh->ip6r_segleft); - return; - } - - /* - * Bounds checking on the ancillary data buffer. When calculating - * the number of items to show keep in mind: - * - The size of the cmsg structure - * - The size of one segment (the size of a Type 0 routing header) - * - When dividing add a fudge factor of one in case the - * dividend is not evenly divisible by the divisor - */ - rthsize = (rh->ip6r_len + 1) * 8; - if (bufsize < (rthsize + CMSG_SPACE(0))) { - origsegs = segments; - size0 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 0); - size1 = inet6_rth_space(IPV6_RTHDR_TYPE_0, 1); - segments -= (rthsize - (bufsize - CMSG_SPACE(0))) / - (size1 - size0) + 1; - warnx("segments truncated, showing only %d (total=%d)", - segments, origsegs); - } - - for (i = 0; i < segments; i++) { - in6 = inet6_rth_getaddr(extbuf, i); - if (in6 == NULL) - printf(" [%d]\n", i); - else { - if (!inet_ntop(AF_INET6, in6, ntopbuf, - sizeof(ntopbuf))) - strlcpy(ntopbuf, "?", sizeof(ntopbuf)); - printf(" [%d]%s\n", i, ntopbuf); - } - } - - return; - -} - -static int -pr_bitrange(u_int32_t v, int soff, int ii) -{ - int off; - int i; - - off = 0; - while (off < 32) { - /* shift till we have 0x01 */ - if ((v & 0x01) == 0) { - if (ii > 1) - printf("-%u", soff + off - 1); - ii = 0; - switch (v & 0x0f) { - case 0x00: - v >>= 4; - off += 4; - continue; - case 0x08: - v >>= 3; - off += 3; - continue; - case 0x04: case 0x0c: - v >>= 2; - off += 2; - continue; - default: - v >>= 1; - off += 1; - continue; - } - } - - /* we have 0x01 with us */ - for (i = 0; i < 32 - off; i++) { - if ((v & (0x01 << i)) == 0) - break; - } - if (!ii) - printf(" %u", soff + off); - ii += i; - v >>= i; off += i; - } - return ii; -} - -static void -pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen) - /* ni->qtype must be SUPTYPES */ -{ - size_t clen; - u_int32_t v; - const u_char *cp, *end; - u_int16_t cur; - struct cbit { - u_int16_t words; /*32bit count*/ - u_int16_t skip; - } cbit; -#define MAXQTYPES (1 << 16) - size_t off; - int b; - - cp = (u_char *)(ni + 1); - end = ((u_char *)ni) + nilen; - cur = 0; - b = 0; - - printf("NodeInfo Supported Qtypes"); - if (options & F_VERBOSE) { - if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) - printf(", compressed bitmap"); - else - printf(", raw bitmap"); - } - - while (cp < end) { - clen = (size_t)(end - cp); - if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) { - if (clen == 0 || clen > MAXQTYPES / 8 || - clen % sizeof(v)) { - printf("???"); - return; - } - } else { - if (clen < sizeof(cbit) || clen % sizeof(v)) - return; - memcpy(&cbit, cp, sizeof(cbit)); - if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) > - clen) - return; - cp += sizeof(cbit); - clen = ntohs(cbit.words) * sizeof(v); - if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 > - MAXQTYPES) - return; - } - - for (off = 0; off < clen; off += sizeof(v)) { - memcpy(&v, cp + off, sizeof(v)); - v = (u_int32_t)ntohl(v); - b = pr_bitrange(v, (int)(cur + off * 8), b); - } - /* flush the remaining bits */ - b = pr_bitrange(0, (int)(cur + off * 8), b); - - cp += clen; - cur += clen * 8; - if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0) - cur += ntohs(cbit.skip) * 32; - } -} - -static void -pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen) - /* ni->qtype must be NODEADDR */ -{ - u_char *cp = (u_char *)(ni + 1); - char ntop_buf[INET6_ADDRSTRLEN]; - int withttl = 0; - - nilen -= sizeof(struct icmp6_nodeinfo); - - if (options & F_VERBOSE) { - switch (ni->ni_code) { - case ICMP6_NI_REFUSED: - (void)printf("refused"); - break; - case ICMP6_NI_UNKNOWN: - (void)printf("unknown qtype"); - break; - } - if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE) - (void)printf(" truncated"); - } - putchar('\n'); - if (nilen <= 0) - printf(" no address\n"); - - /* - * In icmp-name-lookups 05 and later, TTL of each returned address - * is contained in the resposne. We try to detect the version - * by the length of the data, but note that the detection algorithm - * is incomplete. We assume the latest draft by default. - */ - if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0) - withttl = 1; - while (nilen > 0) { - u_int32_t ttl = 0; - - if (withttl) { - uint32_t t; - - memcpy(&t, cp, sizeof(t)); - ttl = (u_int32_t)ntohl(t); - cp += sizeof(u_int32_t); - nilen -= sizeof(u_int32_t); - } - - if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) == - NULL) - strlcpy(ntop_buf, "?", sizeof(ntop_buf)); - printf(" %s", ntop_buf); - if (withttl) { - if (ttl == 0xffffffff) { - /* - * XXX: can this convention be applied to all - * type of TTL (i.e. non-ND TTL)? - */ - printf("(TTL=infty)"); - } - else - printf("(TTL=%u)", ttl); - } - putchar('\n'); - - nilen -= sizeof(struct in6_addr); - cp += sizeof(struct in6_addr); - } -} - -static int -get_hoplim(struct msghdr *mhdr) -{ - struct cmsghdr *cm; - - for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; - cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { - if (cm->cmsg_len == 0) - return(-1); - - if (cm->cmsg_level == IPPROTO_IPV6 && - cm->cmsg_type == IPV6_HOPLIMIT && - cm->cmsg_len == CMSG_LEN(sizeof(int))) { - int r; - - memcpy(&r, CMSG_DATA(cm), sizeof(r)); - return(r); - } - } - - return(-1); -} - -static struct in6_pktinfo * -get_rcvpktinfo(struct msghdr *mhdr) -{ - static struct in6_pktinfo pi; - struct cmsghdr *cm; - - for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; - cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { - if (cm->cmsg_len == 0) - return(NULL); - - if (cm->cmsg_level == IPPROTO_IPV6 && - cm->cmsg_type == IPV6_PKTINFO && - cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) { - memcpy(&pi, CMSG_DATA(cm), sizeof(pi)); - return(&pi); - } - } - - return(NULL); -} - -static int -get_pathmtu(struct msghdr *mhdr) -{ -#ifdef IPV6_RECVPATHMTU - struct cmsghdr *cm; - struct ip6_mtuinfo mtuctl; - - for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; - cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { - if (cm->cmsg_len == 0) - return(0); - - if (cm->cmsg_level == IPPROTO_IPV6 && - cm->cmsg_type == IPV6_PATHMTU && - cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) { - memcpy(&mtuctl, CMSG_DATA(cm), sizeof(mtuctl)); - - /* - * If the notified destination is different from - * the one we are pinging, just ignore the info. - * We check the scope ID only when both notified value - * and our own value have non-0 values, because we may - * have used the default scope zone ID for sending, - * in which case the scope ID value is 0. - */ - if (!IN6_ARE_ADDR_EQUAL(&mtuctl.ip6m_addr.sin6_addr, - &dst.sin6_addr) || - (mtuctl.ip6m_addr.sin6_scope_id && - dst.sin6_scope_id && - mtuctl.ip6m_addr.sin6_scope_id != - dst.sin6_scope_id)) { - if ((options & F_VERBOSE) != 0) { - printf("path MTU for %s is notified. " - "(ignored)\n", - pr_addr((struct sockaddr *)&mtuctl.ip6m_addr, - sizeof(mtuctl.ip6m_addr))); - } - return(0); - } - - /* - * Ignore an invalid MTU. XXX: can we just believe - * the kernel check? - */ - if (mtuctl.ip6m_mtu < IPV6_MMTU) - return(0); - - /* notification for our destination. return the MTU. */ - return((int)mtuctl.ip6m_mtu); - } - } -#endif - return(0); -} - -/* - * onint -- - * SIGINT handler. - */ -/* ARGSUSED */ -static void -onint(int notused __unused) -{ - /* - * When doing reverse DNS lookups, the seenint flag might not - * be noticed for a while. Just exit if we get a second SIGINT. - */ - if ((options & F_HOSTNAME) && seenint != 0) - _exit(nreceived ? 0 : 2); -} - -/* - * summary -- - * Print out statistics. - */ -static void -summary(void) -{ - - (void)printf("\n--- %s ping6 statistics ---\n", hostname); - (void)printf("%ld packets transmitted, ", ntransmitted); - (void)printf("%ld packets received, ", nreceived); - if (nrepeats) - (void)printf("+%ld duplicates, ", nrepeats); - if (ntransmitted) { - if (nreceived > ntransmitted) - (void)printf("-- somebody's duplicating packets!"); - else - (void)printf("%.1f%% packet loss", - ((((double)ntransmitted - nreceived) * 100.0) / - ntransmitted)); - } - if (nrcvtimeout) - printf(", %ld packets out of wait time", nrcvtimeout); - (void)putchar('\n'); - if (nreceived && timing) { - /* Only display average to microseconds */ - double num = nreceived + nrepeats; - double avg = tsum / num; - double dev = sqrt(tsumsq / num - avg * avg); - (void)printf( - "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n", - tmin, avg, tmax, dev); - (void)fflush(stdout); - } - (void)fflush(stdout); -} - -/*subject type*/ -static const char *niqcode[] = { - "IPv6 address", - "DNS label", /*or empty*/ - "IPv4 address", -}; - -/*result code*/ -static const char *nircode[] = { - "Success", "Refused", "Unknown", -}; - - -/* - * pr_icmph -- - * Print a descriptive string about an ICMP header. - */ -static void -pr_icmph(struct icmp6_hdr *icp, u_char *end) -{ - char ntop_buf[INET6_ADDRSTRLEN]; - struct nd_redirect *red; - struct icmp6_nodeinfo *ni; - char dnsname[MAXDNAME + 1]; - const u_char *cp; - size_t l; - - switch (icp->icmp6_type) { - case ICMP6_DST_UNREACH: - switch (icp->icmp6_code) { - case ICMP6_DST_UNREACH_NOROUTE: - (void)printf("No Route to Destination\n"); - break; - case ICMP6_DST_UNREACH_ADMIN: - (void)printf("Destination Administratively " - "Unreachable\n"); - break; - case ICMP6_DST_UNREACH_BEYONDSCOPE: - (void)printf("Destination Unreachable Beyond Scope\n"); - break; - case ICMP6_DST_UNREACH_ADDR: - (void)printf("Destination Host Unreachable\n"); - break; - case ICMP6_DST_UNREACH_NOPORT: - (void)printf("Destination Port Unreachable\n"); - break; - default: - (void)printf("Destination Unreachable, Bad Code: %d\n", - icp->icmp6_code); - break; - } - /* Print returned IP header information */ - pr_retip((struct ip6_hdr *)(icp + 1), end); - break; - case ICMP6_PACKET_TOO_BIG: - (void)printf("Packet too big mtu = %d\n", - (int)ntohl(icp->icmp6_mtu)); - pr_retip((struct ip6_hdr *)(icp + 1), end); - break; - case ICMP6_TIME_EXCEEDED: - switch (icp->icmp6_code) { - case ICMP6_TIME_EXCEED_TRANSIT: - (void)printf("Time to live exceeded\n"); - break; - case ICMP6_TIME_EXCEED_REASSEMBLY: - (void)printf("Frag reassembly time exceeded\n"); - break; - default: - (void)printf("Time exceeded, Bad Code: %d\n", - icp->icmp6_code); - break; - } - pr_retip((struct ip6_hdr *)(icp + 1), end); - break; - case ICMP6_PARAM_PROB: - (void)printf("Parameter problem: "); - switch (icp->icmp6_code) { - case ICMP6_PARAMPROB_HEADER: - (void)printf("Erroneous Header "); - break; - case ICMP6_PARAMPROB_NEXTHEADER: - (void)printf("Unknown Nextheader "); - break; - case ICMP6_PARAMPROB_OPTION: - (void)printf("Unrecognized Option "); - break; - default: - (void)printf("Bad code(%d) ", icp->icmp6_code); - break; - } - (void)printf("pointer = 0x%02x\n", - (u_int32_t)ntohl(icp->icmp6_pptr)); - pr_retip((struct ip6_hdr *)(icp + 1), end); - break; - case ICMP6_ECHO_REQUEST: - (void)printf("Echo Request"); - /* XXX ID + Seq + Data */ - break; - case ICMP6_ECHO_REPLY: - (void)printf("Echo Reply"); - /* XXX ID + Seq + Data */ - break; - case ICMP6_MEMBERSHIP_QUERY: - (void)printf("Listener Query"); - break; - case ICMP6_MEMBERSHIP_REPORT: - (void)printf("Listener Report"); - break; - case ICMP6_MEMBERSHIP_REDUCTION: - (void)printf("Listener Done"); - break; - case ND_ROUTER_SOLICIT: - (void)printf("Router Solicitation"); - break; - case ND_ROUTER_ADVERT: - (void)printf("Router Advertisement"); - break; - case ND_NEIGHBOR_SOLICIT: - (void)printf("Neighbor Solicitation"); - break; - case ND_NEIGHBOR_ADVERT: - (void)printf("Neighbor Advertisement"); - break; - case ND_REDIRECT: - red = (struct nd_redirect *)icp; - (void)printf("Redirect\n"); - if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf, - sizeof(ntop_buf))) - strlcpy(ntop_buf, "?", sizeof(ntop_buf)); - (void)printf("Destination: %s", ntop_buf); - if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf, - sizeof(ntop_buf))) - strlcpy(ntop_buf, "?", sizeof(ntop_buf)); - (void)printf(" New Target: %s", ntop_buf); - break; - case ICMP6_NI_QUERY: - (void)printf("Node Information Query"); - /* XXX ID + Seq + Data */ - ni = (struct icmp6_nodeinfo *)icp; - l = end - (u_char *)(ni + 1); - printf(", "); - switch (ntohs(ni->ni_qtype)) { - case NI_QTYPE_NOOP: - (void)printf("NOOP"); - break; - case NI_QTYPE_SUPTYPES: - (void)printf("Supported qtypes"); - break; - case NI_QTYPE_FQDN: - (void)printf("DNS name"); - break; - case NI_QTYPE_NODEADDR: - (void)printf("nodeaddr"); - break; - case NI_QTYPE_IPV4ADDR: - (void)printf("IPv4 nodeaddr"); - break; - default: - (void)printf("unknown qtype"); - break; - } - if (options & F_VERBOSE) { - switch (ni->ni_code) { - case ICMP6_NI_SUBJ_IPV6: - if (l == sizeof(struct in6_addr) && - inet_ntop(AF_INET6, ni + 1, ntop_buf, - sizeof(ntop_buf)) != NULL) { - (void)printf(", subject=%s(%s)", - niqcode[ni->ni_code], ntop_buf); - } else { -#if 1 - /* backward compat to -W */ - (void)printf(", oldfqdn"); -#else - (void)printf(", invalid"); -#endif - } - break; - case ICMP6_NI_SUBJ_FQDN: - if (end == (u_char *)(ni + 1)) { - (void)printf(", no subject"); - break; - } - printf(", subject=%s", niqcode[ni->ni_code]); - cp = (const u_char *)(ni + 1); - cp = dnsdecode(cp, end, NULL, dnsname, - sizeof(dnsname)); - if (cp != NULL) - printf("(%s)", dnsname); - else - printf("(invalid)"); - break; - case ICMP6_NI_SUBJ_IPV4: - if (l == sizeof(struct in_addr) && - inet_ntop(AF_INET, ni + 1, ntop_buf, - sizeof(ntop_buf)) != NULL) { - (void)printf(", subject=%s(%s)", - niqcode[ni->ni_code], ntop_buf); - } else - (void)printf(", invalid"); - break; - default: - (void)printf(", invalid"); - break; - } - } - break; - case ICMP6_NI_REPLY: - (void)printf("Node Information Reply"); - /* XXX ID + Seq + Data */ - ni = (struct icmp6_nodeinfo *)icp; - printf(", "); - switch (ntohs(ni->ni_qtype)) { - case NI_QTYPE_NOOP: - (void)printf("NOOP"); - break; - case NI_QTYPE_SUPTYPES: - (void)printf("Supported qtypes"); - break; - case NI_QTYPE_FQDN: - (void)printf("DNS name"); - break; - case NI_QTYPE_NODEADDR: - (void)printf("nodeaddr"); - break; - case NI_QTYPE_IPV4ADDR: - (void)printf("IPv4 nodeaddr"); - break; - default: - (void)printf("unknown qtype"); - break; - } - if (options & F_VERBOSE) { - if (ni->ni_code > nitems(nircode)) - printf(", invalid"); - else - printf(", %s", nircode[ni->ni_code]); - } - break; - default: - (void)printf("Bad ICMP type: %d", icp->icmp6_type); - } -} - -/* - * pr_iph -- - * Print an IP6 header. - */ -static void -pr_iph(struct ip6_hdr *ip6) -{ - u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK; - u_int8_t tc; - char ntop_buf[INET6_ADDRSTRLEN]; - - tc = *(&ip6->ip6_vfc + 1); /* XXX */ - tc = (tc >> 4) & 0x0f; - tc |= (ip6->ip6_vfc << 4); - - printf("Vr TC Flow Plen Nxt Hlim\n"); - printf(" %1x %02x %05x %04x %02x %02x\n", - (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow), - ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim); - if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf))) - strlcpy(ntop_buf, "?", sizeof(ntop_buf)); - printf("%s->", ntop_buf); - if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf))) - strlcpy(ntop_buf, "?", sizeof(ntop_buf)); - printf("%s\n", ntop_buf); -} - -/* - * pr_addr -- - * Return an ascii host address as a dotted quad and optionally with - * a hostname. - */ -static const char * -pr_addr(struct sockaddr *addr, int addrlen) -{ - static char buf[NI_MAXHOST]; - int flag = 0; - - if ((options & F_HOSTNAME) == 0) - flag |= NI_NUMERICHOST; - - if (cap_getnameinfo(capdns, addr, addrlen, buf, sizeof(buf), NULL, 0, - flag) == 0) - return (buf); - else - return "?"; -} - -/* - * pr_retip -- - * Dump some info on a returned (via ICMPv6) IPv6 packet. - */ -static void -pr_retip(struct ip6_hdr *ip6, u_char *end) -{ - u_char *cp = (u_char *)ip6, nh; - int hlen; - - if ((size_t)(end - (u_char *)ip6) < sizeof(*ip6)) { - printf("IP6"); - goto trunc; - } - pr_iph(ip6); - hlen = sizeof(*ip6); - - nh = ip6->ip6_nxt; - cp += hlen; - while (end - cp >= 8) { - struct ah ah; - - switch (nh) { - case IPPROTO_HOPOPTS: - printf("HBH "); - hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3; - nh = ((struct ip6_hbh *)cp)->ip6h_nxt; - break; - case IPPROTO_DSTOPTS: - printf("DSTOPT "); - hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3; - nh = ((struct ip6_dest *)cp)->ip6d_nxt; - break; - case IPPROTO_FRAGMENT: - printf("FRAG "); - hlen = sizeof(struct ip6_frag); - nh = ((struct ip6_frag *)cp)->ip6f_nxt; - break; - case IPPROTO_ROUTING: - printf("RTHDR "); - hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3; - nh = ((struct ip6_rthdr *)cp)->ip6r_nxt; - break; -#ifdef IPSEC - case IPPROTO_AH: - printf("AH "); - memcpy(&ah, cp, sizeof(ah)); - hlen = (ah.ah_len+2) << 2; - nh = ah.ah_nxt; - break; -#endif - case IPPROTO_ICMPV6: - printf("ICMP6: type = %d, code = %d\n", - *cp, *(cp + 1)); - return; - case IPPROTO_ESP: - printf("ESP\n"); - return; - case IPPROTO_TCP: - printf("TCP: from port %u, to port %u (decimal)\n", - (*cp * 256 + *(cp + 1)), - (*(cp + 2) * 256 + *(cp + 3))); - return; - case IPPROTO_UDP: - printf("UDP: from port %u, to port %u (decimal)\n", - (*cp * 256 + *(cp + 1)), - (*(cp + 2) * 256 + *(cp + 3))); - return; - default: - printf("Unknown Header(%d)\n", nh); - return; - } - - if ((cp += hlen) >= end) - goto trunc; - } - if (end - cp < 8) - goto trunc; - - putchar('\n'); - return; - - trunc: - printf("...\n"); - return; -} - -static void -fill(char *bp, char *patp) -{ - int ii, jj, kk; - int pat[16]; - char *cp; - - for (cp = patp; *cp; cp++) - if (!isxdigit(*cp)) - errx(1, "patterns must be specified as hex digits"); - ii = sscanf(patp, - "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", - &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], - &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], - &pat[13], &pat[14], &pat[15]); - -/* xxx */ - if (ii > 0) - for (kk = 0; - (size_t)kk <= MAXDATALEN - 8 + sizeof(struct tv32) + ii; - kk += ii) - for (jj = 0; jj < ii; ++jj) - bp[jj + kk] = pat[jj]; - if (!(options & F_QUIET)) { - (void)printf("PATTERN: 0x"); - for (jj = 0; jj < ii; ++jj) - (void)printf("%02x", bp[jj] & 0xFF); - (void)printf("\n"); - } -} - -#ifdef IPSEC -#ifdef IPSEC_POLICY_IPSEC -static int -setpolicy(int so __unused, char *policy) -{ - char *buf; - - if (policy == NULL) - return 0; /* ignore */ - - buf = ipsec_set_policy(policy, strlen(policy)); - if (buf == NULL) - errx(1, "%s", ipsec_strerror()); - if (setsockopt(ssend, IPPROTO_IPV6, IPV6_IPSEC_POLICY, buf, - ipsec_get_policylen(buf)) < 0) - warnx("Unable to set IPsec policy"); - free(buf); - - return 0; -} -#endif -#endif - -static char * -nigroup(char *name, int nig_oldmcprefix) -{ - char *p; - char *q; - MD5_CTX ctxt; - u_int8_t digest[16]; - u_int8_t c; - size_t l; - char hbuf[NI_MAXHOST]; - struct in6_addr in6; - int valid; - - p = strchr(name, '.'); - if (!p) - p = name + strlen(name); - l = p - name; - if (l > 63 || l > sizeof(hbuf) - 1) - return NULL; /*label too long*/ - strncpy(hbuf, name, l); - hbuf[(int)l] = '\0'; - - for (q = name; *q; q++) { - if (isupper(*(unsigned char *)q)) - *q = tolower(*(unsigned char *)q); - } - - /* generate 16 bytes of pseudo-random value. */ - memset(&ctxt, 0, sizeof(ctxt)); - MD5Init(&ctxt); - c = l & 0xff; - MD5Update(&ctxt, &c, sizeof(c)); - MD5Update(&ctxt, (unsigned char *)name, l); - MD5Final(digest, &ctxt); - - if (nig_oldmcprefix) { - /* draft-ietf-ipngwg-icmp-name-lookup */ - valid = inet_pton(AF_INET6, "ff02::2:0000:0000", &in6); - } else { - /* RFC 4620 */ - valid = inet_pton(AF_INET6, "ff02::2:ff00:0000", &in6); - } - if (valid != 1) - return NULL; /*XXX*/ - - if (nig_oldmcprefix) { - /* draft-ietf-ipngwg-icmp-name-lookup */ - bcopy(digest, &in6.s6_addr[12], 4); - } else { - /* RFC 4620 */ - bcopy(digest, &in6.s6_addr[13], 3); - } - - if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL) - return NULL; - - return strdup(hbuf); -} - -static void -usage(void) -{ - (void)fprintf(stderr, -#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC) - "A" -#endif - "usage: ping6 [-" - "Dd" -#if defined(IPSEC) && !defined(IPSEC_POLICY_IPSEC) - "E" -#endif - "fH" -#ifdef IPV6_USE_MIN_MTU - "m" -#endif - "nNoqrRtvwW] " - "[-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n" - " [-h hoplimit] [-I interface] [-i wait] [-l preload]" -#if defined(IPSEC) && defined(IPSEC_POLICY_IPSEC) - " [-P policy]" -#endif - "\n" - " [-p pattern] [-S sourceaddr] [-s packetsize] " - "[-x waittime]\n" - " [-X timeout] [-z tclass] [hops ...] host\n"); - exit(1); -} - -static cap_channel_t * -capdns_setup(void) -{ - cap_channel_t *capcas, *capdnsloc; -#ifdef WITH_CASPER - const char *types[2]; - int families[1]; -#endif - capcas = cap_init(); - if (capcas == NULL) - err(1, "unable to create casper process"); - capdnsloc = cap_service_open(capcas, "system.dns"); - /* Casper capability no longer needed. */ - cap_close(capcas); - if (capdnsloc == NULL) - err(1, "unable to open system.dns service"); -#ifdef WITH_CASPER - types[0] = "NAME2ADDR"; - types[1] = "ADDR2NAME"; - if (cap_dns_type_limit(capdnsloc, types, nitems(types)) < 0) - err(1, "unable to limit access to system.dns service"); - families[0] = AF_INET6; - if (cap_dns_family_limit(capdnsloc, families, nitems(families)) < 0) - err(1, "unable to limit access to system.dns service"); -#endif - return (capdnsloc); -} diff --git a/sbin/sunlabel/Makefile b/sbin/sunlabel/Makefile deleted file mode 100644 index 95e8cc9e46..0000000000 --- a/sbin/sunlabel/Makefile +++ /dev/null @@ -1,21 +0,0 @@ - -.PATH: ${SRCTOP}/sys/geom - -PROG= sunlabel -SRCS= sunlabel.c geom_sunlabel_enc.c -MAN= sunlabel.8 - -.if ${MACHINE_CPUARCH} == "sparc64" -LINKS= ${BINDIR}/sunlabel ${BINDIR}/disklabel -MLINKS= sunlabel.8 disklabel.8 -.endif - -LIBADD= geom - -.include - -test: ${PROG} - sh ${.CURDIR}/runtest.sh - -testx: ${PROG} - sh -x ${.CURDIR}/runtest.sh diff --git a/sbin/sunlabel/Makefile.depend b/sbin/sunlabel/Makefile.depend deleted file mode 100644 index 22afc5e5d3..0000000000 --- a/sbin/sunlabel/Makefile.depend +++ /dev/null @@ -1,15 +0,0 @@ -# Autogenerated - do NOT edit! - -DIRDEPS = \ - include \ - include/xlocale \ - lib/${CSU_DIR} \ - lib/libc \ - lib/libgeom \ - - -.include - -.if ${DEP_RELDIR} == ${_DEP_RELDIR} -# local dependencies - needed for -jN in clean tree -.endif diff --git a/sbin/sunlabel/runtest.sh b/sbin/sunlabel/runtest.sh deleted file mode 100644 index 1a18d30317..0000000000 --- a/sbin/sunlabel/runtest.sh +++ /dev/null @@ -1,156 +0,0 @@ -#!/bin/sh - -TMP=/tmp/$$. -set -e -MD=`mdconfig -a -t malloc -s 2m` -trap "exec 7 /dev/null 2>&1 -./sunlabel $MD > ${TMP}l0 - -sed ' -/ c:/{ -p -s/c:/a:/ -s/3969/1024/ -} -' ${TMP}l0 > ${TMP}l1 - -./sunlabel -R $MD ${TMP}l1 -if [ -c /dev/${MD}a ] ; then - echo "PASS: Created a: partition" 1>&2 -else - echo "FAIL: Did not create a: partition" 1>&2 - exit 2 -fi - -# Spoil and rediscover - -true > /dev/${MD} -if [ -c /dev/${MD}a ] ; then - echo "PASS: Recreated a: partition after spoilage" 1>&2 -else - echo "FAIL: Did not recreate a: partition after spoilage" 1>&2 - exit 2 -fi - -dd if=/dev/$MD of=${TMP}i1 count=16 > /dev/null 2>&1 -sed ' -/ c:/{ -p -s/c:/a:/ -s/3969/2048/ -} -' ${TMP}l0 > ${TMP}l2 - -./sunlabel -R $MD ${TMP}l2 -dd if=/dev/$MD of=${TMP}i2 count=16 > /dev/null 2>&1 - -exec 7< /dev/${MD}a - -for t in a c -do - if dd if=${TMP}i2 of=/dev/${MD}$t 2>/dev/null ; then - echo "PASS: Could rewrite same label to ...$t while ...a open" 1>&2 - else - echo "FAIL: Could not rewrite same label to ...$t while ...a open" 1>&2 - exit 2 - fi - - if dd if=${TMP}i1 of=/dev/${MD}$t 2>/dev/null ; then - echo "FAIL: Could label with smaller ...a to ...$t while ...a open" 1>&2 - exit 2 - else - echo "PASS: Could not label with smaller ...a to ...$t while ...a open" 1>&2 - fi - - if dd if=${TMP}i0 of=/dev/${MD}$t 2>/dev/null ; then - echo "FAIL: Could write label missing ...a to ...$t while ...a open" 1>&2 - exit 2 - else - echo "PASS: Could not write label missing ...a to ...$t while ...a open" 1>&2 - fi -done - -exec 7< /dev/null - -if dd if=${TMP}i0 of=/dev/${MD}c 2>/dev/null ; then - echo "PASS: Could write missing ...a label to ...c" 1>&2 -else - echo "FAIL: Could not write missing ...a label to ...c" 1>&2 - exit 2 -fi - -if dd if=${TMP}i2 of=/dev/${MD}c 2>/dev/null ; then - echo "PASS: Could write large ...a label to ...c" 1>&2 -else - echo "FAIL: Could not write large ...a label to ...c" 1>&2 - exit 2 -fi - -if dd if=${TMP}i1 of=/dev/${MD}c 2>/dev/null ; then - echo "PASS: Could write small ...a label to ...c" 1>&2 -else - echo "FAIL: Could not write small ...a label to ...c" 1>&2 - exit 2 -fi - -if dd if=${TMP}i2 of=/dev/${MD}a 2>/dev/null ; then - echo "PASS: Could increase size of ...a by writing to ...a" 1>&2 -else - echo "FAIL: Could not increase size of ...a by writing to ...a" 1>&2 - exit 2 -fi - -if dd if=${TMP}i1 of=/dev/${MD}a 2>/dev/null ; then - echo "FAIL: Could decrease size of ...a by writing to ...a" 1>&2 - exit 2 -else - echo "PASS: Could not decrease size of ...a by writing to ...a" 1>&2 -fi - -if dd if=${TMP}i0 of=/dev/${MD}a 2>/dev/null ; then - echo "FAIL: Could delete ...a by writing to ...a" 1>&2 - exit 2 -else - echo "PASS: Could not delete ...a by writing to ...a" 1>&2 -fi - -if ./sunlabel -B -b ${TMP}i0 ${MD} ; then - if [ ! -c /dev/${MD}a ] ; then - echo "FAILED: Writing bootcode killed ...a" 1>&2 - exit 2 - else - echo "PASS: Could write bootcode while closed" 1>&2 - fi -else - echo "FAILED: Could not write bootcode while closed" 1>&2 - exit 2 -fi - -exec 7> /dev/${MD}c -if ktrace ./sunlabel -B -b ${TMP}i0 ${MD} ; then - if [ ! -c /dev/${MD}a ] ; then - echo "FAILED: Writing bootcode killed ...a" 1>&2 - exit 2 - else - echo "PASS: Could write bootcode while open" 1>&2 - fi -else - echo "FAILED: Could not write bootcode while open" 1>&2 - exit 2 -fi -exec 7> /dev/null - -if dd if=${TMP}i0 of=/dev/${MD}c 2>/dev/null ; then - echo "PASS: Could delete ...a by writing to ...c" 1>&2 -else - echo "FAIL: Could not delete ...a by writing to ...c" 1>&2 - exit 2 -fi - -# XXX: need to add a 'b' partition and check for overlaps. - -exit 0 diff --git a/sbin/sunlabel/sunlabel.8 b/sbin/sunlabel/sunlabel.8 deleted file mode 100644 index 523af3b310..0000000000 --- a/sbin/sunlabel/sunlabel.8 +++ /dev/null @@ -1,431 +0,0 @@ -.\" Copyright (c) 2004 -.\" David E. O'Brien. All rights reserved. -.\" Copyright (c) 2004, 2005 -.\" Joerg Wunsch. All rights reserved. -.\" -.\" Redistribution and use in source and binary forms, with or without -.\" modification, are permitted provided that the following conditions -.\" are met: -.\" 1. Redistributions of source code must retain the above copyright -.\" notice, this list of conditions and the following disclaimer. -.\" 2. Redistributions in binary form must reproduce the above copyright -.\" notice, this list of conditions and the following disclaimer in the -.\" documentation and/or other materials provided with the distribution. -.\" -.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -.\" SUCH DAMAGE. -.\" -.\" -.Dd March 30, 2005 -.Dt SUNLABEL 8 -.Os -.Sh NAME -.Nm sunlabel -.Nd read and write disk pack label suitable for Sun's OpenBoot PROM -.Sh SYNOPSIS -.Nm -.Op Fl r -.Op Fl c No \&| Fl h -.Ar disk -.Nm -.Fl B -.Op Fl b Ar boot1 -.Op Fl n -.Ar disk -.Nm -.Fl R -.Op Fl B Op Fl b Ar boot1 -.Op Fl r -.Op Fl n -.Op Fl c -.Ar disk protofile -.Nm -.Fl e -.Op Fl B Op Fl b Ar boot1 -.Op Fl r -.Op Fl n -.Op Fl c -.Ar disk -.Nm -.Fl w -.Op Fl B Op Fl b Ar boot1 -.Op Fl r -.Op Fl n -.Op Fl c -.Ar disk type -.Sh DESCRIPTION -The -.Nm -utility -installs, examines or modifies the -.Em Sun OpenBoot PROM -label on a disk. -In addition, -.Nm -can install bootstrap code. -.Ss Introduction -The label occupies the first sector (i.e., 512 bytes) of each disk. -It starts with a textual description which by convention also mentions -the disk geometry in textual form (number of cylinders, alternate -cylinders, heads, and sectors per track), optionally followed by a -table of SVR4-compatible VTOC tags and flags per partition, followed -by the partition table itself. -Finally, a checksum is recorded to ensure the label has not been -tampered with. -.Pp -The -.Em Sun OpenBoot PROM -label allows for 8 disk partitions. -The partition table lists the starting cylinder of the partition, -plus the size of the partition in 512-byte sectors. -Thus, partitions in the -.Em Sun OpenBoot PROM -must always start at a cylinder boundary (for whatever geometry -emulation has been chosen). -.Pp -The optional SVR4-compatible VTOC tag and flags table is not used -by the -.Fx -kernel. -It is maintained solely for compatibility with the -.Tn Solaris -operating system that might share disks with -.Fx -on the same hardware platform. -.Pp -The -.Em Sun OpenBoot PROM -label is natively understood by the underlying hardware, which can -bootstrap from a single partition entry, as opposed to the very first -block(s) of the entire disk as on many other hardware platforms. -.Pp -Note that the hardware platform mandates that two cylinders are set -aside as -.Em alternate cylinders -which are not available to user programs (and not even through the -.Dq Li backup -partition). -.Ss Options -Options are listed in alphabetical order here. -Note that only those option combinations listed under -.Sx SYNOPSIS -are allowable. -.Bl -tag -width ".Fl b Ar bootpath" -.It Fl b Ar bootpath -Specify that -.Ar bootpath -is to be used as the boot image, rather than the default of -.Pa /boot/boot1 . -.It Fl B -Install bootstrap code onto the disk. -Note that since the underlying hardware platform bootstraps from -partitions, not disks, this operation is only useful if there is -a partition starting at offset 0. -.It Fl c -Use cylinders for partition size display rather than -(512-byte) sectors. -This also changes the default interpretation of the partition -size entries when editing the label, or reading from a prototype -file. -Thus, prototype files are only compatible when both, obtaining -the file and re-installing it is done using the same -.Fl c -option setting. -.It Fl e -Enter edit mode. -See -.Sx Edit mode -below for a more detailed explanation. -.It Fl h -When displaying the label, make the partition size and offset -values -.Dq human readable . -The displayed numbers will get a suffix of -.Ql B -for bytes, -.Ql K -for 1024 bytes each, -.Ql M -for 1048576 bytes each, or -.Ql G -for 1073741824 bytes each appended. -Note that due to possible rounding errors, prototype files -obtained using the -.Fl h -option are not suited for re-installing using the -.Fl R -option. -.It Fl n -No changes. -All operations, checks etc., are performed normally, but nothing -is written to disk. -.It Fl r -Obsolete option that used to indicate that the operation should -be done directly on disk, as opposed through the respective kernel -services. -Ignored. -.It Fl R -Restore label from the prototype in -.Ar protofile . -A prototype file is simply the textual representation of the -label as printed using the first form of the -.Nm -utility shown in the -.Sx SYNOPSIS . -Note that the -.Fl c -option used to obtain the prototype must match the option used -when restoring the label (both present, or both absent). -.It Fl w -Write mode. -Suitable to write an initial label to disk. -The -.Ar type -argument used to be an entry into a table of predefined labels, -but this functionality is not supported by -.Nm . -Instead, the only allowable -.Ar type -argument is the string -.Dq Li auto , -indicating that an automatically created label should be written -to disk. -This automatism will try to create an initial label that fits as -best as possible into the available disk capacity. -.El -.Pp -If neither of the -.Fl e , R , -or -.Fl w -options are present, the existing label for -.Ar disk -will be printed to standard output. -.Pp -The -.Ar disk -argument -must be given as a plain disk name, without any leading -.Pa /dev/ . -.Ss Edit mode -In edit mode, the existing label from -.Ar disk -will be read, and put into a template file. -The command referenced by the -.Ev EDITOR -environmental variable will be started to allow the user -to edit the label. -The label is then checked and examined for any errors. -If no errors have been found, the new label is written to disk. -If there were any errors, a message is printed to standard -error output, and the user is given the opportunity to edit -the template file again. -If accepted, editing starts over. -If declined, no changes will -be written to disk. -.Pp -The label presented for editing is the same as the standard -printout, with some added hints about the possible options to -specify the sector size and starting cylinder. -The following areas in the template can be edited: -.Bl -tag -width indent -.It Sy Textual label, geometry emulation -The line -.D1 Li text: Ar XXXX Li cyl Ar CC Li alt 2 hd Ar HH Li sec Ar SS -represents the label text. -It must be retained exactly in the form shown. -The editable text -.Ar XXXX -is a simple (non-whitespace) text describing the disk. -By convention, this text mentions the approximate size of the -disk, as in -.Dq Li SUN9.0G -for a 9 GB disk shipped by Sun. -.Pp -The values -.Ar CC , -.Ar HH , -and -.Ar SS -describe the number of cylinders, heads (tracks per -cylinder), and sectors per track respectively. -They might be modified to change the geometry emulation. -Each number must be between 1 and 65535. -The product -.D1 Em (CC + 2) * HH * SS -must be less than or equal to the total number of sectors of the -disk (which is given as a hint in a comment field). -.It Sy Volume name -The volume name (if present) is introduced by the string -.Dq "volume name:" . -It can be up to 8 characters long, and might be useful to distinguish -different disks in a system. -Note that volume names require the VTOC elements to be present, so -any of the VTOC constraints described below need to be obeyed as well -if a volume name is to be set. -Setting an empty volume name will delete it from the label. -.It Sy Partition entries -Partition entries start with a letter from -.Ql a -through -.Ql h , -immediately followed by a colon, followed by the size of this -partition, and the starting cylinder of the partition. -The unit of the size field defaults to sectors, or to cylinders -if the -.Fl c -option is in effect. -Alternatively, a different unit may be specified by appending -.Ql s -for (512-byte) sectors, -.Ql c -for cylinders, -.Ql k -for kilobytes, -.Ql m -for megabytes, or -.Ql g -for gigabytes. -The last partition entry may specify the size as -.Ql * -to indicate that this entry should consume the rest of disk not -consumed by any other partition so far. -.Pp -The start of partition is always taken as a cylinder number (starting -at 0) since this is what the underlying hardware uses. -Alternatively, specifying it as -.Ql * -will make the computation automatically chose the nearest possible -cylinder boundary. -.Pp -Partition -.Ql c -must always be present, must start at 0, and must cover the entire -disk (without considering the alternate cylinders though). -.Pp -Optionally, each partition entry may be followed by an SVR4-compatible -VTOC tag name, and a flag description. -The following VTOC tag names are known: -.Bl -column -offset indent ".Li unassigned" ".Sy value" ".Sy comment" -.It Sy name Ta Sy value Ta Sy comment -.It Li unassigned Ta No 0x00 Ta \& -.It Li boot Ta No 0x01 Ta \& -.It Li root Ta No 0x02 Ta \& -.It Li swap Ta No 0x03 Ta \& -.It Li usr Ta No 0x04 Ta \& -.It Li backup Ta No 0x05 Ta c partition, entire disk -.It Li stand Ta No 0x06 Ta \& -.It Li var Ta No 0x07 Ta \& -.It Li home Ta No 0x08 Ta \& -.It Li altsctr Ta No 0x09 Ta alternate sector partition -.It Li cache Ta No 0x0a Ta Solaris cachefs partition -.It Li VxVM_pub Ta No 0x0e Ta VxVM public region -.It Li VxVM_priv Ta No 0x0f Ta VxVM private region -.El -.Pp -The following VTOC flags are known: -.Bl -column -offset indent ".Sy name" ".Sy value" ".Sy comment" -.It Sy name Ta Sy value Ta Sy comment -.It Li wm Ta No 0x00 Ta read/write, mountable -.It Li wu Ta No 0x01 Ta read/write, unmountable -.It Li rm Ta No 0x10 Ta read/only, mountable -.It Li ru Ta No 0x11 Ta read/only, unmountable -.El -.Pp -Optionally, both the tag and/or the flag name may be specified -numerically, using standard -.Ql C -numerical notation (prefix -.Ql 0x -for hexadecimal numbers, -.Ql 0 -for octal numbers). -If the flag field is omitted, it defaults to -.Ql wm . -If the tag field is also omitted, it defaults to -.Dq Li unassigned . -If none of the partitions lists any VTOC tag/flags, no -SVR4-compatible VTOC elements will be written to disk. -If VTOC-style elements are present, partition -.Ql c -must be marked as -.Dq Li backup -(and should be marked -.Ql wu ) . -.El -.Pp -When checking the label, partition -.Ql c -is checked for presence, and for the mentioned restrictions. -All other partitions are checked for possible overlaps, as -well as for not extending past the end of unit. -If VTOC-style elements are present, overlaps of unmountable -partitions against other partitions will be warned still but -do not cause a rejection of the label. -That way, -.Em encapsulated disks -of volume management software are acceptable as long as the -volume management partitions are clearly marked as unmountable. -.Pp -Any other fields in the label template are informational only, -and will not be parsed when reading the label. -.Pp -Note that when changing the geometry emulation by editing the -textual description line, all partition entries will be -considered based on the new geometry emulation. -.Sh ENVIRONMENT -.Bl -tag -width ".Ev EDITOR" -compact -.It Ev EDITOR -Name of the command to edit the template file in edit-mode. -Defaults to -.Xr vi 1 . -.El -.Sh FILES -.Bl -tag -width ".Pa /boot/boot1" -compact -.It Pa /boot/boot1 -Default boot image. -.El -.Sh SEE ALSO -.Xr vi 1 , -.Xr geom 4 , -.Xr bsdlabel 8 -.Sh HISTORY -The -.Nm -utility appeared in -.Fx 5.1 . -.Sh AUTHORS -The -.Nm -utility was written by -.An Jake Burkholder , -modeling it after the -.Xr bsdlabel 8 -command available on other architectures. -.Pp -.An -nosplit -This man page was initially written by -.An David O'Brien , -and later substantially updated by -.An J\(:org Wunsch . -.Sh BUGS -Installing bootstrap code onto an entire disk is merely pointless. -.Nm -should rather support installing bootstrap code into a partition -instead. -.Pp -The -.Dq auto -layout algorithm could be smarter. -By now, it tends to emulate fairly large cylinders which due to -the two reserved alternate cylinders causes a fair amount of -wasted disk space. diff --git a/sbin/sunlabel/sunlabel.c b/sbin/sunlabel/sunlabel.c deleted file mode 100644 index 9a1e3bd828..0000000000 --- a/sbin/sunlabel/sunlabel.c +++ /dev/null @@ -1,1000 +0,0 @@ -/*- - * Copyright (c) 2003 Jake Burkholder. - * Copyright (c) 2004,2005 Joerg Wunsch. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ -/*- - * SPDX-License-Identifier: BSD-4-Clause - * - * Copyright (c) 1994, 1995 Gordon W. Ross - * Copyright (c) 1994 Theo de Raadt - * All rights reserved. - * Copyright (c) 1987, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Symmetric Computer Systems. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * This product includes software developed by Theo de Raadt. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * from: $NetBSD: disksubr.c,v 1.13 2000/12/17 22:39:18 pk $ - */ - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define _PATH_TMPFILE "/tmp/EdDk.XXXXXXXXXX" -#define _PATH_BOOT "/boot/boot1" - -static int bflag; -static int Bflag; -static int cflag; -static int eflag; -static int hflag; -static int nflag; -static int Rflag; -static int wflag; - -static off_t mediasize; -static uint32_t sectorsize; - -struct tags { - const char *name; - unsigned int id; -}; - -static int check_label(struct sun_disklabel *sl); -static void read_label(struct sun_disklabel *sl, const char *disk); -static void write_label(struct sun_disklabel *sl, const char *disk, - const char *bootpath); -static void edit_label(struct sun_disklabel *sl, const char *disk, - const char *bootpath); -static int parse_label(struct sun_disklabel *sl, const char *file); -static void print_label(struct sun_disklabel *sl, const char *disk, FILE *out); - -static int parse_size(struct sun_disklabel *sl, int part, char *size); -static int parse_offset(struct sun_disklabel *sl, int part, char *offset); - -static const char *flagname(unsigned int tag); -static const char *tagname(unsigned int tag); -static unsigned int parse_flag(struct sun_disklabel *sl, int part, - const char *flag); -static unsigned int parse_tag(struct sun_disklabel *sl, int part, - const char *tag); -static const char *make_h_number(uintmax_t u); - -static void usage(void); - -extern char *__progname; - -static struct tags knowntags[] = { - { "unassigned", VTOC_UNASSIGNED }, - { "boot", VTOC_BOOT }, - { "root", VTOC_ROOT }, - { "swap", VTOC_SWAP }, - { "usr", VTOC_USR }, - { "backup", VTOC_BACKUP }, - { "stand", VTOC_STAND }, - { "var", VTOC_VAR }, - { "home", VTOC_HOME }, - { "altsctr", VTOC_ALTSCTR }, - { "cache", VTOC_CACHE }, - { "VxVM_pub", VTOC_VXVM_PUB }, - { "VxVM_priv", VTOC_VXVM_PRIV }, -}; - -static struct tags knownflags[] = { - { "wm", 0 }, - { "wu", VTOC_UNMNT }, - { "rm", VTOC_RONLY }, - { "ru", VTOC_UNMNT | VTOC_RONLY }, -}; - -/* - * Disk label editor for sun disklabels. - */ -int -main(int ac, char **av) -{ - struct sun_disklabel sl; - const char *bootpath; - const char *proto; - const char *disk; - int ch; - - bootpath = _PATH_BOOT; - while ((ch = getopt(ac, av, "b:BcehnrRw")) != -1) - switch (ch) { - case 'b': - bflag = 1; - bootpath = optarg; - break; - case 'B': - Bflag = 1; - break; - case 'c': - cflag = 1; - break; - case 'e': - eflag = 1; - break; - case 'h': - hflag = 1; - break; - case 'n': - nflag = 1; - break; - case 'r': - fprintf(stderr, "Obsolete -r flag ignored\n"); - break; - case 'R': - Rflag = 1; - break; - case 'w': - wflag = 1; - break; - default: - usage(); - break; - } - if (bflag && !Bflag) - usage(); - if (nflag && !(Bflag || eflag || Rflag || wflag)) - usage(); - if (eflag && (Rflag || wflag)) - usage(); - if (eflag) - hflag = 0; - ac -= optind; - av += optind; - if (ac == 0) - usage(); - bzero(&sl, sizeof(sl)); - disk = av[0]; - if (wflag) { - if (ac != 2 || strcmp(av[1], "auto") != 0) - usage(); - read_label(&sl, disk); - bzero(sl.sl_part, sizeof(sl.sl_part)); - sl.sl_part[SUN_RAWPART].sdkp_cyloffset = 0; - sl.sl_part[SUN_RAWPART].sdkp_nsectors = sl.sl_ncylinders * - sl.sl_ntracks * sl.sl_nsectors; - write_label(&sl, disk, bootpath); - } else if (eflag) { - if (ac != 1) - usage(); - read_label(&sl, disk); - if (sl.sl_magic != SUN_DKMAGIC) - errx(1, "%s%s has no sun disklabel", _PATH_DEV, disk); - edit_label(&sl, disk, bootpath); - } else if (Rflag) { - if (ac != 2) - usage(); - proto = av[1]; - read_label(&sl, disk); - if (parse_label(&sl, proto) != 0) - errx(1, "%s: invalid label", proto); - write_label(&sl, disk, bootpath); - } else if (Bflag) { - read_label(&sl, disk); - if (sl.sl_magic != SUN_DKMAGIC) - errx(1, "%s%s has no sun disklabel", _PATH_DEV, disk); - write_label(&sl, disk, bootpath); - } else { - read_label(&sl, disk); - if (sl.sl_magic != SUN_DKMAGIC) - errx(1, "%s%s has no sun disklabel", _PATH_DEV, disk); - print_label(&sl, disk, stdout); - } - return (0); -} - -static int -check_label(struct sun_disklabel *sl) -{ - uint64_t nsectors; - uint64_t ostart; - uint64_t start; - uint64_t oend; - uint64_t end; - int havevtoc; - int warnonly; - int i; - int j; - - havevtoc = sl->sl_vtoc_sane == SUN_VTOC_SANE; - - nsectors = sl->sl_ncylinders * sl->sl_ntracks * sl->sl_nsectors; - if (sl->sl_part[SUN_RAWPART].sdkp_cyloffset != 0 || - sl->sl_part[SUN_RAWPART].sdkp_nsectors != nsectors) { - warnx("partition c is incorrect, must start at 0 and cover " - "whole disk"); - return (1); - } - if (havevtoc && sl->sl_vtoc_map[2].svtoc_tag != VTOC_BACKUP) { - warnx("partition c must have tag \"backup\""); - return (1); - } - for (i = 0; i < SUN_NPART; i++) { - if (i == 2 || sl->sl_part[i].sdkp_nsectors == 0) - continue; - start = (uint64_t)sl->sl_part[i].sdkp_cyloffset * - sl->sl_ntracks * sl->sl_nsectors; - end = start + sl->sl_part[i].sdkp_nsectors; - if (end > nsectors) { - warnx("partition %c extends past end of disk", - 'a' + i); - return (1); - } - if (havevtoc) { - if (sl->sl_vtoc_map[i].svtoc_tag == VTOC_BACKUP) { - warnx("only partition c is allowed to have " - "tag \"backup\""); - return (1); - } - } - for (j = 0; j < SUN_NPART; j++) { - /* - * Overlaps for unmountable partitions are - * non-fatal but will be warned anyway. - */ - warnonly = havevtoc && - ((sl->sl_vtoc_map[i].svtoc_flag & VTOC_UNMNT) != 0 || - (sl->sl_vtoc_map[j].svtoc_flag & VTOC_UNMNT) != 0); - - if (j == 2 || j == i || - sl->sl_part[j].sdkp_nsectors == 0) - continue; - ostart = (uint64_t)sl->sl_part[j].sdkp_cyloffset * - sl->sl_ntracks * sl->sl_nsectors; - oend = ostart + sl->sl_part[j].sdkp_nsectors; - if ((start <= ostart && end >= oend) || - (start > ostart && start < oend) || - (end > ostart && end < oend)) { - warnx("partition %c overlaps partition %c", - 'a' + i, 'a' + j); - if (!warnonly) - return (1); - } - } - } - return (0); -} - -static void -read_label(struct sun_disklabel *sl, const char *disk) -{ - char path[MAXPATHLEN]; - uint32_t fwsectors; - uint32_t fwheads; - char buf[SUN_SIZE]; - int fd, error; - - snprintf(path, sizeof(path), "%s%s", _PATH_DEV, disk); - if ((fd = open(path, O_RDONLY)) < 0) - err(1, "open %s", path); - if (read(fd, buf, sizeof(buf)) != sizeof(buf)) - err(1, "read"); - error = sunlabel_dec(buf, sl); - if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) != 0) - if (error) - err(1, "%s: ioctl(DIOCGMEDIASIZE) failed", disk); - if (ioctl(fd, DIOCGSECTORSIZE, §orsize) != 0) { - if (error) - err(1, "%s: DIOCGSECTORSIZE failed", disk); - else - sectorsize = 512; - } - if (error) { - bzero(sl, sizeof(*sl)); - if (ioctl(fd, DIOCGFWSECTORS, &fwsectors) != 0) - fwsectors = 63; - if (ioctl(fd, DIOCGFWHEADS, &fwheads) != 0) { - if (mediasize <= 63 * 1024 * sectorsize) - fwheads = 1; - else if (mediasize <= 63 * 16 * 1024 * sectorsize) - fwheads = 16; - else - fwheads = 255; - } - sl->sl_rpm = 3600; - sl->sl_pcylinders = mediasize / (fwsectors * fwheads * - sectorsize); - sl->sl_sparespercyl = 0; - sl->sl_interleave = 1; - sl->sl_ncylinders = sl->sl_pcylinders - 2; - sl->sl_acylinders = 2; - sl->sl_nsectors = fwsectors; - sl->sl_ntracks = fwheads; - sl->sl_part[SUN_RAWPART].sdkp_cyloffset = 0; - sl->sl_part[SUN_RAWPART].sdkp_nsectors = sl->sl_ncylinders * - sl->sl_ntracks * sl->sl_nsectors; - if (mediasize > (off_t)4999L * 1024L * 1024L) { - sprintf(sl->sl_text, - "FreeBSD%jdG cyl %u alt %u hd %u sec %u", - (intmax_t)(mediasize + 512 * 1024 * 1024) / - (1024 * 1024 * 1024), - sl->sl_ncylinders, sl->sl_acylinders, - sl->sl_ntracks, sl->sl_nsectors); - } else { - sprintf(sl->sl_text, - "FreeBSD%jdM cyl %u alt %u hd %u sec %u", - (intmax_t)(mediasize + 512 * 1024) / (1024 * 1024), - sl->sl_ncylinders, sl->sl_acylinders, - sl->sl_ntracks, sl->sl_nsectors); - } - } - close(fd); -} - -static void -write_label(struct sun_disklabel *sl, const char *disk, const char *bootpath) -{ - char path[MAXPATHLEN]; - char boot[SUN_BOOTSIZE]; - char buf[SUN_SIZE]; - const char *errstr; - off_t off; - int bfd; - int fd; - int i; - struct gctl_req *grq; - - sl->sl_magic = SUN_DKMAGIC; - - if (check_label(sl) != 0) - errx(1, "invalid label"); - - bzero(buf, sizeof(buf)); - sunlabel_enc(buf, sl); - - if (nflag) { - print_label(sl, disk, stdout); - return; - } - if (Bflag) { - if ((bfd = open(bootpath, O_RDONLY)) < 0) - err(1, "open %s", bootpath); - i = read(bfd, boot, sizeof(boot)); - if (i < 0) - err(1, "read"); - else if (i != sizeof (boot)) - errx(1, "read wrong size boot code (%d)", i); - close(bfd); - } - snprintf(path, sizeof(path), "%s%s", _PATH_DEV, disk); - fd = open(path, O_RDWR); - if (fd < 0) { - grq = gctl_get_handle(); - gctl_ro_param(grq, "verb", -1, "write label"); - gctl_ro_param(grq, "class", -1, "SUN"); - gctl_ro_param(grq, "geom", -1, disk); - gctl_ro_param(grq, "label", sizeof buf, buf); - errstr = gctl_issue(grq); - if (errstr != NULL) - errx(1, "%s", errstr); - gctl_free(grq); - if (Bflag) { - grq = gctl_get_handle(); - gctl_ro_param(grq, "verb", -1, "write bootcode"); - gctl_ro_param(grq, "class", -1, "SUN"); - gctl_ro_param(grq, "geom", -1, disk); - gctl_ro_param(grq, "bootcode", sizeof boot, boot); - errstr = gctl_issue(grq); - if (errstr != NULL) - errx(1, "%s", errstr); - gctl_free(grq); - } - } else { - if (lseek(fd, 0, SEEK_SET) < 0) - err(1, "lseek"); - if (write(fd, buf, sizeof(buf)) != sizeof(buf)) - err (1, "write"); - if (Bflag) { - for (i = 0; i < SUN_NPART; i++) { - if (sl->sl_part[i].sdkp_nsectors == 0) - continue; - off = sl->sl_part[i].sdkp_cyloffset * - sl->sl_ntracks * sl->sl_nsectors * 512; - /* - * Ignore first SUN_SIZE bytes of boot code to - * avoid overwriting the label. - */ - if (lseek(fd, off + SUN_SIZE, SEEK_SET) < 0) - err(1, "lseek"); - if (write(fd, boot + SUN_SIZE, - sizeof(boot) - SUN_SIZE) != - sizeof(boot) - SUN_SIZE) - err(1, "write"); - } - } - close(fd); - } - exit(0); -} - -static void -edit_label(struct sun_disklabel *sl, const char *disk, const char *bootpath) -{ - char tmpfil[] = _PATH_TMPFILE; - const char *editor; - int status; - FILE *fp; - pid_t pid; - pid_t r; - int fd; - int c; - - if ((fd = mkstemp(tmpfil)) < 0) - err(1, "mkstemp"); - if ((fp = fdopen(fd, "w")) == NULL) - err(1, "fdopen"); - print_label(sl, disk, fp); - fflush(fp); - for (;;) { - if ((pid = fork()) < 0) - err(1, "fork"); - if (pid == 0) { - if ((editor = getenv("EDITOR")) == NULL) - editor = _PATH_VI; - execlp(editor, editor, tmpfil, (char *)NULL); - err(1, "execlp %s", editor); - } - status = 0; - while ((r = wait(&status)) > 0 && r != pid) - ; - if (WIFEXITED(status)) { - if (parse_label(sl, tmpfil) == 0) { - fclose(fp); - unlink(tmpfil); - write_label(sl, disk, bootpath); - return; - } - printf("re-edit the label? [y]: "); - fflush(stdout); - c = getchar(); - if (c != EOF && c != '\n') - while (getchar() != '\n') - ; - if (c == 'n') { - fclose(fp); - unlink(tmpfil); - return; - } - } - } - fclose(fp); - unlink(tmpfil); - return; -} - -static int -parse_label(struct sun_disklabel *sl, const char *file) -{ - char offset[32]; - char size[32]; - char flag[32]; - char tag[32]; - char buf[128]; - char text[128]; - char volname[SUN_VOLNAME_LEN + 1]; - struct sun_disklabel sl1; - char *bp; - const char *what; - uint8_t part; - FILE *fp; - int line; - int rv; - int wantvtoc; - unsigned alt, cyl, hd, nr, sec; - - line = wantvtoc = 0; - if ((fp = fopen(file, "r")) == NULL) - err(1, "fopen"); - sl1 = *sl; - bzero(&sl1.sl_part, sizeof(sl1.sl_part)); - while (fgets(buf, sizeof(buf), fp) != NULL) { - /* - * In order to recognize a partition entry, we search - * for lines starting with a single letter followed by - * a colon as their first non-white characters. We - * silently ignore any other lines, so any comment etc. - * lines in the label template will be ignored. - * - * XXX We should probably also recognize the geometry - * fields on top, and allow changing the geometry - * emulated by this disk. - */ - for (bp = buf; isspace(*bp); bp++) - ; - if (strncmp(bp, "text:", strlen("text:")) == 0) { - bp += strlen("text:"); - rv = sscanf(bp, - " %s cyl %u alt %u hd %u sec %u", - text, &cyl, &alt, &hd, &sec); - if (rv != 5) { - warnx("%s, line %d: text label does not " - "contain required fields", - file, line + 1); - fclose(fp); - return (1); - } - if (alt != 2) { - warnx("%s, line %d: # alt must be equal 2", - file, line + 1); - fclose(fp); - return (1); - } - if (cyl == 0 || cyl > USHRT_MAX) { - what = "cyl"; - nr = cyl; - unreasonable: - warnx("%s, line %d: # %s %d unreasonable", - file, line + 1, what, nr); - fclose(fp); - return (1); - } - if (hd == 0 || hd > USHRT_MAX) { - what = "hd"; - nr = hd; - goto unreasonable; - } - if (sec == 0 || sec > USHRT_MAX) { - what = "sec"; - nr = sec; - goto unreasonable; - } - if (mediasize == 0) - warnx("unit size unknown, no sector count " - "check could be done"); - else if ((uintmax_t)(cyl + alt) * sec * hd > - (uintmax_t)mediasize / sectorsize) { - warnx("%s, line %d: sector count %ju exceeds " - "unit size %ju", - file, line + 1, - (uintmax_t)(cyl + alt) * sec * hd, - (uintmax_t)mediasize / sectorsize); - fclose(fp); - return (1); - } - sl1.sl_pcylinders = cyl + alt; - sl1.sl_ncylinders = cyl; - sl1.sl_acylinders = alt; - sl1.sl_nsectors = sec; - sl1.sl_ntracks = hd; - memset(sl1.sl_text, 0, sizeof(sl1.sl_text)); - snprintf(sl1.sl_text, sizeof(sl1.sl_text), - "%s cyl %u alt %u hd %u sec %u", - text, cyl, alt, hd, sec); - continue; - } - if (strncmp(bp, "volume name:", strlen("volume name:")) == 0) { - wantvtoc = 1; /* Volume name requires VTOC. */ - bp += strlen("volume name:"); -#if SUN_VOLNAME_LEN != 8 -# error "scanf field width does not match SUN_VOLNAME_LEN" -#endif - /* - * We set the field length to one more than - * SUN_VOLNAME_LEN to allow detecting an - * overflow. - */ - memset(volname, 0, sizeof volname); - rv = sscanf(bp, " %9[^\n]", volname); - if (rv != 1) { - /* Clear the volume name. */ - memset(sl1.sl_vtoc_volname, 0, - SUN_VOLNAME_LEN); - } else { - memcpy(sl1.sl_vtoc_volname, volname, - SUN_VOLNAME_LEN); - if (volname[SUN_VOLNAME_LEN] != '\0') - warnx( -"%s, line %d: volume name longer than %d characters, truncating", - file, line + 1, SUN_VOLNAME_LEN); - } - continue; - } - if (strlen(bp) < 2 || bp[1] != ':') { - line++; - continue; - } - rv = sscanf(bp, "%c: %30s %30s %30s %30s", - &part, size, offset, tag, flag); - if (rv < 3) { - syntaxerr: - warnx("%s: syntax error on line %d", - file, line + 1); - fclose(fp); - return (1); - } - if (parse_size(&sl1, part - 'a', size) || - parse_offset(&sl1, part - 'a', offset)) - goto syntaxerr; - if (rv > 3) { - wantvtoc = 1; - if (rv == 5 && parse_flag(&sl1, part - 'a', flag)) - goto syntaxerr; - if (parse_tag(&sl1, part - 'a', tag)) - goto syntaxerr; - } - line++; - } - fclose(fp); - if (wantvtoc) { - sl1.sl_vtoc_sane = SUN_VTOC_SANE; - sl1.sl_vtoc_vers = SUN_VTOC_VERSION; - sl1.sl_vtoc_nparts = SUN_NPART; - } else { - sl1.sl_vtoc_sane = 0; - sl1.sl_vtoc_vers = 0; - sl1.sl_vtoc_nparts = 0; - bzero(&sl1.sl_vtoc_map, sizeof(sl1.sl_vtoc_map)); - } - *sl = sl1; - return (check_label(sl)); -} - -static int -parse_size(struct sun_disklabel *sl, int part, char *size) -{ - uintmax_t nsectors; - uintmax_t total; - uintmax_t n; - char *p; - int i; - - nsectors = 0; - n = strtoumax(size, &p, 10); - if (*p != '\0') { - if (strcmp(size, "*") == 0) { - total = sl->sl_ncylinders * sl->sl_ntracks * - sl->sl_nsectors; - for (i = 0; i < part; i++) { - if (i == 2) - continue; - nsectors += sl->sl_part[i].sdkp_nsectors; - } - n = total - nsectors; - } else if (p[1] == '\0' && (p[0] == 'C' || p[0] == 'c')) { - n = n * sl->sl_ntracks * sl->sl_nsectors; - } else if (p[1] == '\0' && (p[0] == 'K' || p[0] == 'k')) { - n = roundup((n * 1024) / 512, - sl->sl_ntracks * sl->sl_nsectors); - } else if (p[1] == '\0' && (p[0] == 'M' || p[0] == 'm')) { - n = roundup((n * 1024 * 1024) / 512, - sl->sl_ntracks * sl->sl_nsectors); - } else if (p[1] == '\0' && (p[0] == 'S' || p[0] == 's')) { - /* size in sectors, no action neded */ - } else if (p[1] == '\0' && (p[0] == 'G' || p[0] == 'g')) { - n = roundup((n * 1024 * 1024 * 1024) / 512, - sl->sl_ntracks * sl->sl_nsectors); - } else - return (-1); - } else if (cflag) { - n = n * sl->sl_ntracks * sl->sl_nsectors; - } - sl->sl_part[part].sdkp_nsectors = n; - return (0); -} - -static int -parse_offset(struct sun_disklabel *sl, int part, char *offset) -{ - uintmax_t nsectors; - uintmax_t n; - char *p; - int i; - - nsectors = 0; - n = strtoumax(offset, &p, 10); - if (*p != '\0') { - if (strcmp(offset, "*") == 0) { - for (i = 0; i < part; i++) { - if (i == 2) - continue; - nsectors += sl->sl_part[i].sdkp_nsectors; - } - n = nsectors / (sl->sl_nsectors * sl->sl_ntracks); - } else - return (-1); - } - sl->sl_part[part].sdkp_cyloffset = n; - return (0); -} - -static void -print_label(struct sun_disklabel *sl, const char *disk, FILE *out) -{ - int i, j; - int havevtoc; - uintmax_t secpercyl; - /* Long enough to hex-encode each character. */ - char volname[4 * SUN_VOLNAME_LEN + 1]; - - havevtoc = sl->sl_vtoc_sane == SUN_VTOC_SANE; - secpercyl = sl->sl_nsectors * sl->sl_ntracks; - - fprintf(out, -"# /dev/%s:\n" -"text: %s\n" -"bytes/sector: %d\n" -"sectors/cylinder: %ju\n", - disk, - sl->sl_text, - sectorsize, - secpercyl); - if (eflag) - fprintf(out, - "# max sectors/unit (including alt cylinders): %ju\n", - (uintmax_t)mediasize / sectorsize); - fprintf(out, -"sectors/unit: %ju\n", - secpercyl * sl->sl_ncylinders); - if (havevtoc && sl->sl_vtoc_volname[0] != '\0') { - for (i = j = 0; i < SUN_VOLNAME_LEN; i++) { - if (sl->sl_vtoc_volname[i] == '\0') - break; - if (isprint(sl->sl_vtoc_volname[i])) - volname[j++] = sl->sl_vtoc_volname[i]; - else - j += sprintf(volname + j, "\\x%02X", - sl->sl_vtoc_volname[i]); - } - volname[j] = '\0'; - fprintf(out, "volume name: %s\n", volname); - } - fprintf(out, -"\n" -"%d partitions:\n" -"#\n", - SUN_NPART); - if (!hflag) { - fprintf(out, "# Size is in %s.", cflag? "cylinders": "sectors"); - if (eflag) - fprintf(out, -" Use %%d%c, %%dK, %%dM or %%dG to specify in %s,\n" -"# kilobytes, megabytes or gigabytes respectively, or '*' to specify rest of\n" -"# disk.\n", - cflag? 's': 'c', - cflag? "sectors": "cylinders"); - else - putc('\n', out); - fprintf(out, "# Offset is in cylinders."); - if (eflag) - fprintf(out, -" Use '*' to calculate offsets automatically.\n" -"#\n"); - else - putc('\n', out); - } - if (havevtoc) - fprintf(out, -"# size offset tag flag\n" -"# ---------- ---------- ---------- ----\n" - ); - else - fprintf(out, -"# size offset\n" -"# ---------- ----------\n" - ); - - for (i = 0; i < SUN_NPART; i++) { - if (sl->sl_part[i].sdkp_nsectors == 0) - continue; - if (hflag) { - fprintf(out, " %c: %10s", - 'a' + i, - make_h_number((uintmax_t) - sl->sl_part[i].sdkp_nsectors * 512)); - fprintf(out, " %10s", - make_h_number((uintmax_t) - sl->sl_part[i].sdkp_cyloffset * 512 - * secpercyl)); - } else { - fprintf(out, " %c: %10ju %10u", - 'a' + i, - sl->sl_part[i].sdkp_nsectors / (cflag? secpercyl: 1), - sl->sl_part[i].sdkp_cyloffset); - } - if (havevtoc) - fprintf(out, " %11s %5s", - tagname(sl->sl_vtoc_map[i].svtoc_tag), - flagname(sl->sl_vtoc_map[i].svtoc_flag)); - putc('\n', out); - } -} - -static void -usage(void) -{ - - fprintf(stderr, "usage:" -"\t%s [-r] [-c | -h] disk\n" -"\t\t(to read label)\n" -"\t%s -B [-b boot1] [-n] disk\n" -"\t\t(to install boot program only)\n" -"\t%s -R [-B [-b boot1]] [-r] [-n] [-c] disk protofile\n" -"\t\t(to restore label)\n" -"\t%s -e [-B [-b boot1]] [-r] [-n] [-c] disk\n" -"\t\t(to edit label)\n" -"\t%s -w [-B [-b boot1]] [-r] [-n] disk type\n" -"\t\t(to write default label)\n", - __progname, - __progname, - __progname, - __progname, - __progname); - exit(1); -} - -/* - * Return VTOC tag and flag names for tag or flag ID, resp. - */ -static const char * -tagname(unsigned int tag) -{ - static char buf[32]; - size_t i; - struct tags *tp; - - for (i = 0, tp = knowntags; i < nitems(knowntags); i++, tp++) - if (tp->id == tag) - return (tp->name); - - sprintf(buf, "%u", tag); - - return (buf); -} - -static const char * -flagname(unsigned int flag) -{ - static char buf[32]; - size_t i; - struct tags *tp; - - for (i = 0, tp = knownflags; i < nitems(knownflags); i++, tp++) - if (tp->id == flag) - return (tp->name); - - sprintf(buf, "%u", flag); - - return (buf); -} - -static unsigned int -parse_tag(struct sun_disklabel *sl, int part, const char *tag) -{ - struct tags *tp; - char *endp; - size_t i; - unsigned long l; - - for (i = 0, tp = knowntags; i < nitems(knowntags); i++, tp++) - if (strcmp(tp->name, tag) == 0) { - sl->sl_vtoc_map[part].svtoc_tag = (uint16_t)tp->id; - return (0); - } - - l = strtoul(tag, &endp, 0); - if (*tag != '\0' && *endp == '\0') { - sl->sl_vtoc_map[part].svtoc_tag = (uint16_t)l; - return (0); - } - - return (-1); -} - -static unsigned int -parse_flag(struct sun_disklabel *sl, int part, const char *flag) -{ - struct tags *tp; - char *endp; - size_t i; - unsigned long l; - - for (i = 0, tp = knownflags; i < nitems(knownflags); i++, tp++) - if (strcmp(tp->name, flag) == 0) { - sl->sl_vtoc_map[part].svtoc_flag = (uint16_t)tp->id; - return (0); - } - - l = strtoul(flag, &endp, 0); - if (*flag != '\0' && *endp == '\0') { - sl->sl_vtoc_map[part].svtoc_flag = (uint16_t)l; - return (0); - } - - return (-1); -} - -/* - * Convert argument into `human readable' byte number form. - */ -static const char * -make_h_number(uintmax_t u) -{ - static char buf[32]; - double d; - - if (u == 0) { - strcpy(buf, "0B"); - } else if (u > 2000000000UL) { - d = (double)u / 1e9; - sprintf(buf, "%.1fG", d); - } else if (u > 2000000UL) { - d = (double)u / 1e6; - sprintf(buf, "%.1fM", d); - } else { - d = (double)u / 1e3; - sprintf(buf, "%.1fK", d); - } - - return (buf); -}