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