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 (caph_rights_limit(in.fd, &rights) == -1) 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 (ddflags & C_FSYNC) 168 cap_rights_set(&rights, CAP_FSYNC); 169 if (out.name == NULL) { 170 /* No way to check for read access here. */ 171 out.fd = STDOUT_FILENO; 172 out.name = "stdout"; 173 } else { 174 #define OFLAGS \ 175 (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC)) 176 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE); 177 /* 178 * May not have read access, so try again with write only. 179 * Without read we may have a problem if output also does 180 * not support seeks. 181 */ 182 if (out.fd == -1) { 183 out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE); 184 out.flags |= NOREAD; 185 cap_rights_clear(&rights, CAP_READ); 186 } 187 if (out.fd == -1) 188 err(1, "%s", out.name); 189 } 190 191 getfdtype(&out); 192 193 if (caph_rights_limit(out.fd, &rights) == -1) 194 err(1, "unable to limit capability rights"); 195 if (caph_ioctls_limit(out.fd, cmds, nitems(cmds)) == -1) 196 err(1, "unable to limit capability rights"); 197 198 if (in.fd != STDIN_FILENO && out.fd != STDIN_FILENO) { 199 if (caph_limit_stdin() == -1) 200 err(1, "unable to limit capability rights"); 201 } 202 203 if (in.fd != STDOUT_FILENO && out.fd != STDOUT_FILENO) { 204 if (caph_limit_stdout() == -1) 205 err(1, "unable to limit capability rights"); 206 } 207 208 if (in.fd != STDERR_FILENO && out.fd != STDERR_FILENO) { 209 if (caph_limit_stderr() == -1) 210 err(1, "unable to limit capability rights"); 211 } 212 213 /* 214 * Allocate space for the input and output buffers. If not doing 215 * record oriented I/O, only need a single buffer. 216 */ 217 if (!(ddflags & (C_BLOCK | C_UNBLOCK))) { 218 if ((in.db = malloc((size_t)out.dbsz + in.dbsz - 1)) == NULL) 219 err(1, "input buffer"); 220 out.db = in.db; 221 } else if ((in.db = malloc(MAX((size_t)in.dbsz, cbsz) + cbsz)) == NULL || 222 (out.db = malloc(out.dbsz + cbsz)) == NULL) 223 err(1, "output buffer"); 224 225 /* dbp is the first free position in each buffer. */ 226 in.dbp = in.db; 227 out.dbp = out.db; 228 229 /* Position the input/output streams. */ 230 if (in.offset) 231 pos_in(); 232 if (out.offset) 233 pos_out(); 234 235 /* 236 * Truncate the output file. If it fails on a type of output file 237 * that it should _not_ fail on, error out. 238 */ 239 if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) && 240 out.flags & ISTRUNC) 241 if (ftruncate(out.fd, out.offset * out.dbsz) == -1) 242 err(1, "truncating %s", out.name); 243 244 if (ddflags & (C_LCASE | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) { 245 if (ctab != NULL) { 246 for (cnt = 0; cnt <= 0377; ++cnt) 247 casetab[cnt] = ctab[cnt]; 248 } else { 249 for (cnt = 0; cnt <= 0377; ++cnt) 250 casetab[cnt] = cnt; 251 } 252 if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) { 253 /* 254 * If the input is not EBCDIC, and we do parity 255 * processing, strip input parity. 256 */ 257 for (cnt = 200; cnt <= 0377; ++cnt) 258 casetab[cnt] = casetab[cnt & 0x7f]; 259 } 260 if (ddflags & C_LCASE) { 261 for (cnt = 0; cnt <= 0377; ++cnt) 262 casetab[cnt] = tolower(casetab[cnt]); 263 } else if (ddflags & C_UCASE) { 264 for (cnt = 0; cnt <= 0377; ++cnt) 265 casetab[cnt] = toupper(casetab[cnt]); 266 } 267 if ((ddflags & C_PARITY)) { 268 /* 269 * This should strictly speaking be a no-op, but I 270 * wonder what funny LANG settings could get us. 271 */ 272 for (cnt = 0; cnt <= 0377; ++cnt) 273 casetab[cnt] = casetab[cnt] & 0x7f; 274 } 275 if ((ddflags & C_PARSET)) { 276 for (cnt = 0; cnt <= 0377; ++cnt) 277 casetab[cnt] = casetab[cnt] | 0x80; 278 } 279 if ((ddflags & C_PAREVEN)) { 280 for (cnt = 0; cnt <= 0377; ++cnt) 281 if (parity(casetab[cnt])) 282 casetab[cnt] = casetab[cnt] | 0x80; 283 } 284 if ((ddflags & C_PARODD)) { 285 for (cnt = 0; cnt <= 0377; ++cnt) 286 if (!parity(casetab[cnt])) 287 casetab[cnt] = casetab[cnt] | 0x80; 288 } 289 290 ctab = casetab; 291 } 292 293 if (clock_gettime(CLOCK_MONOTONIC, &st.start)) 294 err(1, "clock_gettime"); 295 } 296 297 static void 298 getfdtype(IO *io) 299 { 300 struct stat sb; 301 int type; 302 303 if (fstat(io->fd, &sb) == -1) 304 err(1, "%s", io->name); 305 if (S_ISREG(sb.st_mode)) 306 io->flags |= ISTRUNC; 307 if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) { 308 if (ioctl(io->fd, FIODTYPE, &type) == -1) { 309 err(1, "%s", io->name); 310 } else { 311 if (type & D_TAPE) 312 io->flags |= ISTAPE; 313 else if (type & (D_DISK | D_MEM)) 314 io->flags |= ISSEEK; 315 if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0) 316 io->flags |= ISCHR; 317 } 318 return; 319 } 320 errno = 0; 321 if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) 322 io->flags |= ISPIPE; 323 else 324 io->flags |= ISSEEK; 325 } 326 327 /* 328 * Limit the speed by adding a delay before every block read. 329 * The delay (t_usleep) is equal to the time computed from block 330 * size and the specified speed limit (t_target) minus the time 331 * spent on actual read and write operations (t_io). 332 */ 333 static void 334 speed_limit(void) 335 { 336 static double t_prev, t_usleep; 337 double t_now, t_io, t_target; 338 339 t_now = secs_elapsed(); 340 t_io = t_now - t_prev - t_usleep; 341 t_target = (double)in.dbsz / (double)speed; 342 t_usleep = t_target - t_io; 343 if (t_usleep > 0) 344 usleep(t_usleep * 1000000); 345 else 346 t_usleep = 0; 347 t_prev = t_now; 348 } 349 350 static void 351 swapbytes(void *v, size_t len) 352 { 353 unsigned char *p = v; 354 unsigned char t; 355 356 while (len > 1) { 357 t = p[0]; 358 p[0] = p[1]; 359 p[1] = t; 360 p += 2; 361 len -= 2; 362 } 363 } 364 365 static void 366 dd_in(void) 367 { 368 ssize_t n; 369 370 for (;;) { 371 switch (cpy_cnt) { 372 case -1: /* count=0 was specified */ 373 return; 374 case 0: 375 break; 376 default: 377 if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt) 378 return; 379 break; 380 } 381 382 if (speed > 0) 383 speed_limit(); 384 385 /* 386 * Zero the buffer first if sync; if doing block operations, 387 * use spaces. 388 */ 389 if (ddflags & C_SYNC) { 390 if (ddflags & C_FILL) 391 memset(in.dbp, fill_char, in.dbsz); 392 else if (ddflags & (C_BLOCK | C_UNBLOCK)) 393 memset(in.dbp, ' ', in.dbsz); 394 else 395 memset(in.dbp, 0, in.dbsz); 396 } 397 398 n = read(in.fd, in.dbp, in.dbsz); 399 if (n == 0) { 400 in.dbrcnt = 0; 401 return; 402 } 403 404 /* Read error. */ 405 if (n == -1) { 406 /* 407 * If noerror not specified, die. POSIX requires that 408 * the warning message be followed by an I/O display. 409 */ 410 if (!(ddflags & C_NOERROR)) 411 err(1, "%s", in.name); 412 warn("%s", in.name); 413 summary(); 414 415 /* 416 * If it's a seekable file descriptor, seek past the 417 * error. If your OS doesn't do the right thing for 418 * raw disks this section should be modified to re-read 419 * in sector size chunks. 420 */ 421 if (in.flags & ISSEEK && 422 lseek(in.fd, (off_t)in.dbsz, SEEK_CUR)) 423 warn("%s", in.name); 424 425 /* If sync not specified, omit block and continue. */ 426 if (!(ddflags & C_SYNC)) 427 continue; 428 429 /* Read errors count as full blocks. */ 430 in.dbcnt += in.dbrcnt = in.dbsz; 431 ++st.in_full; 432 433 /* Handle full input blocks. */ 434 } else if ((size_t)n == (size_t)in.dbsz) { 435 in.dbcnt += in.dbrcnt = n; 436 ++st.in_full; 437 438 /* Handle partial input blocks. */ 439 } else { 440 /* If sync, use the entire block. */ 441 if (ddflags & C_SYNC) 442 in.dbcnt += in.dbrcnt = in.dbsz; 443 else 444 in.dbcnt += in.dbrcnt = n; 445 ++st.in_part; 446 } 447 448 /* 449 * POSIX states that if bs is set and no other conversions 450 * than noerror, notrunc or sync are specified, the block 451 * is output without buffering as it is read. 452 */ 453 if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) { 454 out.dbcnt = in.dbcnt; 455 dd_out(1); 456 in.dbcnt = 0; 457 continue; 458 } 459 460 if (ddflags & C_SWAB) { 461 if ((n = in.dbrcnt) & 1) { 462 ++st.swab; 463 --n; 464 } 465 swapbytes(in.dbp, (size_t)n); 466 } 467 468 in.dbp += in.dbrcnt; 469 (*cfunc)(); 470 if (need_summary) 471 summary(); 472 if (need_progress) 473 progress(); 474 } 475 } 476 477 /* 478 * Clean up any remaining I/O and flush output. If necessary, the output file 479 * is truncated. 480 */ 481 static void 482 dd_close(void) 483 { 484 if (cfunc == def) 485 def_close(); 486 else if (cfunc == block) 487 block_close(); 488 else if (cfunc == unblock) 489 unblock_close(); 490 if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) { 491 if (ddflags & C_FILL) 492 memset(out.dbp, fill_char, out.dbsz - out.dbcnt); 493 else if (ddflags & (C_BLOCK | C_UNBLOCK)) 494 memset(out.dbp, ' ', out.dbsz - out.dbcnt); 495 else 496 memset(out.dbp, 0, out.dbsz - out.dbcnt); 497 out.dbcnt = out.dbsz; 498 } 499 if (out.dbcnt || pending) 500 dd_out(1); 501 502 /* 503 * If the file ends with a hole, ftruncate it to extend its size 504 * up to the end of the hole (without having to write any data). 505 */ 506 if (out.seek_offset > 0 && (out.flags & ISTRUNC)) { 507 if (ftruncate(out.fd, out.seek_offset) == -1) 508 err(1, "truncating %s", out.name); 509 } 510 511 if (ddflags & C_FSYNC) { 512 if (fsync(out.fd) == -1) 513 err(1, "fsyncing %s", out.name); 514 } 515 } 516 517 void 518 dd_out(int force) 519 { 520 u_char *outp; 521 size_t cnt, n; 522 ssize_t nw; 523 static int warned; 524 int sparse; 525 526 /* 527 * Write one or more blocks out. The common case is writing a full 528 * output block in a single write; increment the full block stats. 529 * Otherwise, we're into partial block writes. If a partial write, 530 * and it's a character device, just warn. If a tape device, quit. 531 * 532 * The partial writes represent two cases. 1: Where the input block 533 * was less than expected so the output block was less than expected. 534 * 2: Where the input block was the right size but we were forced to 535 * write the block in multiple chunks. The original versions of dd(1) 536 * never wrote a block in more than a single write, so the latter case 537 * never happened. 538 * 539 * One special case is if we're forced to do the write -- in that case 540 * we play games with the buffer size, and it's usually a partial write. 541 */ 542 outp = out.db; 543 544 /* 545 * If force, first try to write all pending data, else try to write 546 * just one block. Subsequently always write data one full block at 547 * a time at most. 548 */ 549 for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) { 550 cnt = n; 551 do { 552 sparse = 0; 553 if (ddflags & C_SPARSE) { 554 /* Is buffer sparse? */ 555 sparse = BISZERO(outp, cnt); 556 } 557 if (sparse && !force) { 558 pending += cnt; 559 nw = cnt; 560 } else { 561 if (pending != 0) { 562 /* 563 * Seek past hole. Note that we need to record the 564 * reached offset, because we might have no more data 565 * to write, in which case we'll need to call 566 * ftruncate to extend the file size. 567 */ 568 out.seek_offset = lseek(out.fd, pending, SEEK_CUR); 569 if (out.seek_offset == -1) 570 err(2, "%s: seek error creating sparse file", 571 out.name); 572 pending = 0; 573 } 574 if (cnt) { 575 nw = write(out.fd, outp, cnt); 576 out.seek_offset = 0; 577 } else { 578 return; 579 } 580 } 581 582 if (nw <= 0) { 583 if (nw == 0) 584 errx(1, "%s: end of device", out.name); 585 if (errno != EINTR) 586 err(1, "%s", out.name); 587 nw = 0; 588 } 589 590 outp += nw; 591 st.bytes += nw; 592 593 if ((size_t)nw == n && n == (size_t)out.dbsz) 594 ++st.out_full; 595 else 596 ++st.out_part; 597 598 if ((size_t) nw != cnt) { 599 if (out.flags & ISTAPE) 600 errx(1, "%s: short write on tape device", 601 out.name); 602 if (out.flags & ISCHR && !warned) { 603 warned = 1; 604 warnx("%s: short write on character device", 605 out.name); 606 } 607 } 608 609 cnt -= nw; 610 } while (cnt != 0); 611 612 if ((out.dbcnt -= n) < out.dbsz) 613 break; 614 } 615 616 /* Reassemble the output block. */ 617 if (out.dbcnt) 618 (void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt); 619 out.dbp = out.db + out.dbcnt; 620 } 621