1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1991, 1993, 1994 5 * The Regents of the University of California. All rights reserved. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Keith Muller of the University of California, San Diego and Lance 9 * Visser of Convex Computer Corporation. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 3. Neither the name of the University nor the names of its contributors 20 * may be used to endorse or promote products derived from this software 21 * without specific prior written permission. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 33 * SUCH DAMAGE. 34 */ 35 36 #if 0 37 #ifndef lint 38 static char const copyright[] = 39 "@(#) Copyright (c) 1991, 1993, 1994\n\ 40 The Regents of the University of California. All rights reserved.\n"; 41 #endif /* not lint */ 42 43 #ifndef lint 44 static char sccsid[] = "@(#)dd.c 8.5 (Berkeley) 4/2/94"; 45 #endif /* not lint */ 46 #endif 47 #include <sys/cdefs.h> 48 __FBSDID("$FreeBSD$"); 49 50 #include <sys/param.h> 51 #include <sys/stat.h> 52 #include <sys/capsicum.h> 53 #include <sys/conf.h> 54 #include <sys/disklabel.h> 55 #include <sys/filio.h> 56 #include <sys/mtio.h> 57 #include <sys/time.h> 58 59 #include <assert.h> 60 #include <capsicum_helpers.h> 61 #include <ctype.h> 62 #include <err.h> 63 #include <errno.h> 64 #include <fcntl.h> 65 #include <inttypes.h> 66 #include <locale.h> 67 #include <stdio.h> 68 #include <stdlib.h> 69 #include <string.h> 70 #include <time.h> 71 #include <unistd.h> 72 73 #include "dd.h" 74 #include "extern.h" 75 76 static void dd_close(void); 77 static void dd_in(void); 78 static void getfdtype(IO *); 79 static void setup(void); 80 81 IO in, out; /* input/output state */ 82 STAT st; /* statistics */ 83 void (*cfunc)(void); /* conversion function */ 84 uintmax_t cpy_cnt; /* # of blocks to copy */ 85 static off_t pending = 0; /* pending seek if sparse */ 86 u_int ddflags = 0; /* conversion options */ 87 size_t cbsz; /* conversion block size */ 88 uintmax_t files_cnt = 1; /* # of files to copy */ 89 const u_char *ctab; /* conversion table */ 90 char fill_char; /* Character to fill with if defined */ 91 size_t speed = 0; /* maximum speed, in bytes per second */ 92 volatile sig_atomic_t need_summary; 93 volatile sig_atomic_t need_progress; 94 95 int 96 main(int argc __unused, char *argv[]) 97 { 98 struct itimerval itv = { { 1, 0 }, { 1, 0 } }; /* SIGALARM every second, if needed */ 99 100 (void)setlocale(LC_CTYPE, ""); 101 jcl(argv); 102 setup(); 103 104 caph_cache_catpages(); 105 if (caph_enter() < 0) 106 err(1, "unable to enter capability mode"); 107 108 (void)signal(SIGINFO, siginfo_handler); 109 if (ddflags & C_PROGRESS) { 110 (void)signal(SIGALRM, sigalarm_handler); 111 setitimer(ITIMER_REAL, &itv, NULL); 112 } 113 (void)signal(SIGINT, terminate); 114 115 atexit(summary); 116 117 while (files_cnt--) 118 dd_in(); 119 120 dd_close(); 121 /* 122 * Some devices such as cfi(4) may perform significant amounts 123 * of work when a write descriptor is closed. Close the out 124 * descriptor explicitly so that the summary handler (called 125 * from an atexit() hook) includes this work. 126 */ 127 close(out.fd); 128 exit(0); 129 } 130 131 static int 132 parity(u_char c) 133 { 134 int i; 135 136 i = c ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^ 137 (c >> 4) ^ (c >> 5) ^ (c >> 6) ^ (c >> 7); 138 return (i & 1); 139 } 140 141 static void 142 setup(void) 143 { 144 u_int cnt; 145 cap_rights_t rights; 146 unsigned long cmds[] = { FIODTYPE, MTIOCTOP }; 147 148 if (in.name == NULL) { 149 in.name = "stdin"; 150 in.fd = STDIN_FILENO; 151 } else { 152 in.fd = open(in.name, O_RDONLY, 0); 153 if (in.fd == -1) 154 err(1, "%s", in.name); 155 } 156 157 getfdtype(&in); 158 159 cap_rights_init(&rights, CAP_READ, CAP_SEEK); 160 if (cap_rights_limit(in.fd, &rights) == -1 && errno != ENOSYS) 161 err(1, "unable to limit capability rights"); 162 163 if (files_cnt > 1 && !(in.flags & ISTAPE)) 164 errx(1, "files is not supported for non-tape devices"); 165 166 cap_rights_set(&rights, CAP_FTRUNCATE, CAP_IOCTL, CAP_WRITE); 167 if (out.name == NULL) { 168 /* No way to check for read access here. */ 169 out.fd = STDOUT_FILENO; 170 out.name = "stdout"; 171 } else { 172 #define OFLAGS \ 173 (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC)) 174 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE); 175 /* 176 * May not have read access, so try again with write only. 177 * Without read we may have a problem if output also does 178 * not support seeks. 179 */ 180 if (out.fd == -1) { 181 out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE); 182 out.flags |= NOREAD; 183 cap_rights_clear(&rights, CAP_READ); 184 } 185 if (out.fd == -1) 186 err(1, "%s", out.name); 187 } 188 189 getfdtype(&out); 190 191 if (cap_rights_limit(out.fd, &rights) == -1 && errno != ENOSYS) 192 err(1, "unable to limit capability rights"); 193 if (cap_ioctls_limit(out.fd, cmds, nitems(cmds)) == -1 && 194 errno != ENOSYS) 195 err(1, "unable to limit capability rights"); 196 197 if (in.fd != STDIN_FILENO && out.fd != STDIN_FILENO) { 198 if (caph_limit_stdin() == -1) 199 err(1, "unable to limit capability rights"); 200 } 201 202 if (in.fd != STDOUT_FILENO && out.fd != STDOUT_FILENO) { 203 if (caph_limit_stdout() == -1) 204 err(1, "unable to limit capability rights"); 205 } 206 207 if (in.fd != STDERR_FILENO && out.fd != STDERR_FILENO) { 208 if (caph_limit_stderr() == -1) 209 err(1, "unable to limit capability rights"); 210 } 211 212 /* 213 * Allocate space for the input and output buffers. If not doing 214 * record oriented I/O, only need a single buffer. 215 */ 216 if (!(ddflags & (C_BLOCK | C_UNBLOCK))) { 217 if ((in.db = malloc((size_t)out.dbsz + in.dbsz - 1)) == NULL) 218 err(1, "input buffer"); 219 out.db = in.db; 220 } else if ((in.db = malloc(MAX((size_t)in.dbsz, cbsz) + cbsz)) == NULL || 221 (out.db = malloc(out.dbsz + cbsz)) == NULL) 222 err(1, "output buffer"); 223 224 /* dbp is the first free position in each buffer. */ 225 in.dbp = in.db; 226 out.dbp = out.db; 227 228 /* Position the input/output streams. */ 229 if (in.offset) 230 pos_in(); 231 if (out.offset) 232 pos_out(); 233 234 /* 235 * Truncate the output file. If it fails on a type of output file 236 * that it should _not_ fail on, error out. 237 */ 238 if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) && 239 out.flags & ISTRUNC) 240 if (ftruncate(out.fd, out.offset * out.dbsz) == -1) 241 err(1, "truncating %s", out.name); 242 243 if (ddflags & (C_LCASE | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) { 244 if (ctab != NULL) { 245 for (cnt = 0; cnt <= 0377; ++cnt) 246 casetab[cnt] = ctab[cnt]; 247 } else { 248 for (cnt = 0; cnt <= 0377; ++cnt) 249 casetab[cnt] = cnt; 250 } 251 if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) { 252 /* 253 * If the input is not EBCDIC, and we do parity 254 * processing, strip input parity. 255 */ 256 for (cnt = 200; cnt <= 0377; ++cnt) 257 casetab[cnt] = casetab[cnt & 0x7f]; 258 } 259 if (ddflags & C_LCASE) { 260 for (cnt = 0; cnt <= 0377; ++cnt) 261 casetab[cnt] = tolower(casetab[cnt]); 262 } else if (ddflags & C_UCASE) { 263 for (cnt = 0; cnt <= 0377; ++cnt) 264 casetab[cnt] = toupper(casetab[cnt]); 265 } 266 if ((ddflags & C_PARITY)) { 267 /* 268 * This should strictly speaking be a no-op, but I 269 * wonder what funny LANG settings could get us. 270 */ 271 for (cnt = 0; cnt <= 0377; ++cnt) 272 casetab[cnt] = casetab[cnt] & 0x7f; 273 } 274 if ((ddflags & C_PARSET)) { 275 for (cnt = 0; cnt <= 0377; ++cnt) 276 casetab[cnt] = casetab[cnt] | 0x80; 277 } 278 if ((ddflags & C_PAREVEN)) { 279 for (cnt = 0; cnt <= 0377; ++cnt) 280 if (parity(casetab[cnt])) 281 casetab[cnt] = casetab[cnt] | 0x80; 282 } 283 if ((ddflags & C_PARODD)) { 284 for (cnt = 0; cnt <= 0377; ++cnt) 285 if (!parity(casetab[cnt])) 286 casetab[cnt] = casetab[cnt] | 0x80; 287 } 288 289 ctab = casetab; 290 } 291 292 if (clock_gettime(CLOCK_MONOTONIC, &st.start)) 293 err(1, "clock_gettime"); 294 } 295 296 static void 297 getfdtype(IO *io) 298 { 299 struct stat sb; 300 int type; 301 302 if (fstat(io->fd, &sb) == -1) 303 err(1, "%s", io->name); 304 if (S_ISREG(sb.st_mode)) 305 io->flags |= ISTRUNC; 306 if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) { 307 if (ioctl(io->fd, FIODTYPE, &type) == -1) { 308 err(1, "%s", io->name); 309 } else { 310 if (type & D_TAPE) 311 io->flags |= ISTAPE; 312 else if (type & (D_DISK | D_MEM)) 313 io->flags |= ISSEEK; 314 if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0) 315 io->flags |= ISCHR; 316 } 317 return; 318 } 319 errno = 0; 320 if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) 321 io->flags |= ISPIPE; 322 else 323 io->flags |= ISSEEK; 324 } 325 326 /* 327 * Limit the speed by adding a delay before every block read. 328 * The delay (t_usleep) is equal to the time computed from block 329 * size and the specified speed limit (t_target) minus the time 330 * spent on actual read and write operations (t_io). 331 */ 332 static void 333 speed_limit(void) 334 { 335 static double t_prev, t_usleep; 336 double t_now, t_io, t_target; 337 338 t_now = secs_elapsed(); 339 t_io = t_now - t_prev - t_usleep; 340 t_target = (double)in.dbsz / (double)speed; 341 t_usleep = t_target - t_io; 342 if (t_usleep > 0) 343 usleep(t_usleep * 1000000); 344 else 345 t_usleep = 0; 346 t_prev = t_now; 347 } 348 349 static void 350 swapbytes(void *v, size_t len) 351 { 352 unsigned char *p = v; 353 unsigned char t; 354 355 while (len > 1) { 356 t = p[0]; 357 p[0] = p[1]; 358 p[1] = t; 359 p += 2; 360 len -= 2; 361 } 362 } 363 364 static void 365 dd_in(void) 366 { 367 ssize_t n; 368 369 for (;;) { 370 switch (cpy_cnt) { 371 case -1: /* count=0 was specified */ 372 return; 373 case 0: 374 break; 375 default: 376 if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt) 377 return; 378 break; 379 } 380 381 if (speed > 0) 382 speed_limit(); 383 384 /* 385 * Zero the buffer first if sync; if doing block operations, 386 * use spaces. 387 */ 388 if (ddflags & C_SYNC) { 389 if (ddflags & C_FILL) 390 memset(in.dbp, fill_char, in.dbsz); 391 else if (ddflags & (C_BLOCK | C_UNBLOCK)) 392 memset(in.dbp, ' ', in.dbsz); 393 else 394 memset(in.dbp, 0, in.dbsz); 395 } 396 397 n = read(in.fd, in.dbp, in.dbsz); 398 if (n == 0) { 399 in.dbrcnt = 0; 400 return; 401 } 402 403 /* Read error. */ 404 if (n == -1) { 405 /* 406 * If noerror not specified, die. POSIX requires that 407 * the warning message be followed by an I/O display. 408 */ 409 if (!(ddflags & C_NOERROR)) 410 err(1, "%s", in.name); 411 warn("%s", in.name); 412 summary(); 413 414 /* 415 * If it's a seekable file descriptor, seek past the 416 * error. If your OS doesn't do the right thing for 417 * raw disks this section should be modified to re-read 418 * in sector size chunks. 419 */ 420 if (in.flags & ISSEEK && 421 lseek(in.fd, (off_t)in.dbsz, SEEK_CUR)) 422 warn("%s", in.name); 423 424 /* If sync not specified, omit block and continue. */ 425 if (!(ddflags & C_SYNC)) 426 continue; 427 428 /* Read errors count as full blocks. */ 429 in.dbcnt += in.dbrcnt = in.dbsz; 430 ++st.in_full; 431 432 /* Handle full input blocks. */ 433 } else if ((size_t)n == (size_t)in.dbsz) { 434 in.dbcnt += in.dbrcnt = n; 435 ++st.in_full; 436 437 /* Handle partial input blocks. */ 438 } else { 439 /* If sync, use the entire block. */ 440 if (ddflags & C_SYNC) 441 in.dbcnt += in.dbrcnt = in.dbsz; 442 else 443 in.dbcnt += in.dbrcnt = n; 444 ++st.in_part; 445 } 446 447 /* 448 * POSIX states that if bs is set and no other conversions 449 * than noerror, notrunc or sync are specified, the block 450 * is output without buffering as it is read. 451 */ 452 if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) { 453 out.dbcnt = in.dbcnt; 454 dd_out(1); 455 in.dbcnt = 0; 456 continue; 457 } 458 459 if (ddflags & C_SWAB) { 460 if ((n = in.dbrcnt) & 1) { 461 ++st.swab; 462 --n; 463 } 464 swapbytes(in.dbp, (size_t)n); 465 } 466 467 in.dbp += in.dbrcnt; 468 (*cfunc)(); 469 if (need_summary) 470 summary(); 471 if (need_progress) 472 progress(); 473 } 474 } 475 476 /* 477 * Clean up any remaining I/O and flush output. If necessary, the output file 478 * is truncated. 479 */ 480 static void 481 dd_close(void) 482 { 483 if (cfunc == def) 484 def_close(); 485 else if (cfunc == block) 486 block_close(); 487 else if (cfunc == unblock) 488 unblock_close(); 489 if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) { 490 if (ddflags & C_FILL) 491 memset(out.dbp, fill_char, out.dbsz - out.dbcnt); 492 else if (ddflags & (C_BLOCK | C_UNBLOCK)) 493 memset(out.dbp, ' ', out.dbsz - out.dbcnt); 494 else 495 memset(out.dbp, 0, out.dbsz - out.dbcnt); 496 out.dbcnt = out.dbsz; 497 } 498 if (out.dbcnt || pending) 499 dd_out(1); 500 501 /* 502 * If the file ends with a hole, ftruncate it to extend its size 503 * up to the end of the hole (without having to write any data). 504 */ 505 if (out.seek_offset > 0 && (out.flags & ISTRUNC)) { 506 if (ftruncate(out.fd, out.seek_offset) == -1) 507 err(1, "truncating %s", out.name); 508 } 509 } 510 511 void 512 dd_out(int force) 513 { 514 u_char *outp; 515 size_t cnt, i, n; 516 ssize_t nw; 517 static int warned; 518 int sparse; 519 520 /* 521 * Write one or more blocks out. The common case is writing a full 522 * output block in a single write; increment the full block stats. 523 * Otherwise, we're into partial block writes. If a partial write, 524 * and it's a character device, just warn. If a tape device, quit. 525 * 526 * The partial writes represent two cases. 1: Where the input block 527 * was less than expected so the output block was less than expected. 528 * 2: Where the input block was the right size but we were forced to 529 * write the block in multiple chunks. The original versions of dd(1) 530 * never wrote a block in more than a single write, so the latter case 531 * never happened. 532 * 533 * One special case is if we're forced to do the write -- in that case 534 * we play games with the buffer size, and it's usually a partial write. 535 */ 536 outp = out.db; 537 538 /* 539 * If force, first try to write all pending data, else try to write 540 * just one block. Subsequently always write data one full block at 541 * a time at most. 542 */ 543 for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) { 544 cnt = n; 545 do { 546 sparse = 0; 547 if (ddflags & C_SPARSE) { 548 sparse = 1; /* Is buffer sparse? */ 549 for (i = 0; i < cnt; i++) 550 if (outp[i] != 0) { 551 sparse = 0; 552 break; 553 } 554 } 555 if (sparse && !force) { 556 pending += cnt; 557 nw = cnt; 558 } else { 559 if (pending != 0) { 560 /* 561 * Seek past hole. Note that we need to record the 562 * reached offset, because we might have no more data 563 * to write, in which case we'll need to call 564 * ftruncate to extend the file size. 565 */ 566 out.seek_offset = lseek(out.fd, pending, SEEK_CUR); 567 if (out.seek_offset == -1) 568 err(2, "%s: seek error creating sparse file", 569 out.name); 570 pending = 0; 571 } 572 if (cnt) { 573 nw = write(out.fd, outp, cnt); 574 out.seek_offset = 0; 575 } else { 576 return; 577 } 578 } 579 580 if (nw <= 0) { 581 if (nw == 0) 582 errx(1, "%s: end of device", out.name); 583 if (errno != EINTR) 584 err(1, "%s", out.name); 585 nw = 0; 586 } 587 588 outp += nw; 589 st.bytes += nw; 590 591 if ((size_t)nw == n && n == (size_t)out.dbsz) 592 ++st.out_full; 593 else 594 ++st.out_part; 595 596 if ((size_t) nw != cnt) { 597 if (out.flags & ISTAPE) 598 errx(1, "%s: short write on tape device", 599 out.name); 600 if (out.flags & ISCHR && !warned) { 601 warned = 1; 602 warnx("%s: short write on character device", 603 out.name); 604 } 605 } 606 607 cnt -= nw; 608 } while (cnt != 0); 609 610 if ((out.dbcnt -= n) < out.dbsz) 611 break; 612 } 613 614 /* Reassemble the output block. */ 615 if (out.dbcnt) 616 (void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt); 617 out.dbp = out.db + out.dbcnt; 618 } 619