static int pipe_read(struct filedes *fd, void *buf, size_t count, off_t offset) { int ret; /* Verify the offset. */ if (offset < fd->offset) { ERROR("Can't seek backwards in pipe " "(offset %"PRIu64" => %"PRIu64").\n" " Make sure the WIM was captured as " "pipable.", fd->offset, offset); errno = ESPIPE; return WIMLIB_ERR_RESOURCE_ORDER; } /* Manually seek to the requested position. */ while (fd->offset != offset) { size_t bytes_to_read = min(offset - fd->offset, BUFFER_SIZE); u8 dummy[bytes_to_read]; ret = full_read(fd, dummy, bytes_to_read); if (ret) return ret; } /* Do the actual read. */ return full_read(fd, buf, count); }
/* Helios communications. */ static void worker_routine(void) { int n; char *buf; int *wbuf; int i; int checksum; int res; if (full_read(0, (char *) &n, sizeof(int)) != sizeof(int)) Fatal("worker routine, failed to receive initial data"); if (write(1, (char *) &n, sizeof(int)) != sizeof(int)) Fatal("worker routine, failed to send initial data."); buf = malloc(MaxCommsTransfer); if (buf == NULL) Fatal("worker routine, out of memory."); wbuf = (int *) buf; Signal(&ThreadsReady); forever { if (full_read(0, (char *) &n, sizeof(int)) != sizeof(int)) Fatal("worker routine, error %d getting data from the controller.", errno); if (n == 0) /* This is the termination condition */ break; if ((res = full_read(0, buf, n)) != n) Fatal("worker routine, read returned only %d bytes, not %d", res, n); for (i = 1, checksum = 0; i < (n / sizeof(int)); i++) checksum += wbuf[i]; if (checksum != wbuf[0]) Fatal("worker routine, message of %d bytes from the controller has been corrupted.", n); if (write(1, buf, n) != n) Fatal("worker routine, error writing back buffer."); } /* When the code gets here the controller has sent a terminate */ /* request. The Finished flag should be set and the various */ /* testing threads should detect this within a few seconds. */ /* They will update the results structure which must then be */ /* transferred back to the controller. */ Finished = TRUE; for (i = 1; i < NumberThreads; i++) /* this thread is included */ Wait(&ResultsReady); if (write(1, (char *) &Results, sizeof(Results)) != sizeof(Results)) Fatal("worker routine, failed to send back results."); }
/* the Results structure. */ static void link_receiver(int index, int linkno, int channel) { char *buf = NULL; int *wbuf; int checksum; int i; int size; int failures = 0; int iterations; buf = malloc(MaxLinkTransfer); if (buf == NULL) Fatal("receiver for link %d : out of memory.", linkno); wbuf = (int *) buf; /* Initial read to set up the pipe. */ if (full_read(channel, buf, sizeof(int)) != sizeof(int)) Fatal("receiver for link %d : failed to get initial data.",linkno); Signal(&ThreadsReady); /* checked by memory tester */ for (iterations = 0; ; iterations++) { if (full_read(channel, buf, sizeof(bool)) != sizeof(bool)) Fatal("receiver for link %d : read error %d getting Finished flag.", linkno, errno); if (*((bool *) buf)) /* Sending end's Finished flag */ break; for (size = 8; size <= MaxLinkTransfer; size *= 2) { if (full_read(channel, buf, size) != size) Fatal("receiver for link %d : read error %d getting block of %d bytes.", linkno, errno, size); for (i = 1, checksum = 0; i < (size / sizeof(int)); i++) checksum += wbuf[i]; if (checksum != wbuf[0]) failures++; } } /* The remote end has finished, it is time to update the */ /* results structure. */ Wait(&ResultsLock); Results.LinkStats[index].LinkNumber = linkno; Results.LinkStats[index].ReadIterations = iterations; Results.LinkStats[index].ReadFailures = failures; Signal(&ResultsLock); Signal(&ResultsReady); /* Receiver all done. */ }
void FAST_FUNC read_leases(const char *file) { struct dyn_lease lease; int64_t written_at, time_passed; int fd; #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1 unsigned i = 0; #endif fd = open_or_warn(file, O_RDONLY); if (fd < 0) return; if (full_read(fd, &written_at, sizeof(written_at)) != sizeof(written_at)) goto ret; written_at = SWAP_BE64(written_at); time_passed = time(NULL) - written_at; /* Strange written_at, or lease file from old version of udhcpd * which had no "written_at" field? */ if ((uint64_t)time_passed > 12 * 60 * 60) goto ret; while (full_read(fd, &lease, sizeof(lease)) == sizeof(lease)) { //FIXME: what if it matches some static lease? uint32_t y = ntohl(lease.lease_nip); if (y >= server_config.start_ip && y <= server_config.end_ip) { signed_leasetime_t expires = ntohl(lease.expires) - (signed_leasetime_t)time_passed; if (expires <= 0) continue; /* NB: add_lease takes "relative time", IOW, * lease duration, not lease deadline. */ if (add_lease(lease.lease_mac, lease.lease_nip, expires, lease.hostname, sizeof(lease.hostname) ) == 0 ) { bb_error_msg("too many leases while loading %s", file); break; } #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1 i++; #endif } } log1("Read %d leases", i); ret: close(fd); }
/* NB: does not preserve file position! */ static uint32_t find_cdf_offset(void) { cde_header_t cde_header; unsigned char *p; off_t end; unsigned char *buf = xzalloc(PEEK_FROM_END); end = xlseek(zip_fd, 0, SEEK_END); end -= PEEK_FROM_END; if (end < 0) end = 0; xlseek(zip_fd, end, SEEK_SET); full_read(zip_fd, buf, PEEK_FROM_END); p = buf; while (p <= buf + PEEK_FROM_END - CDE_HEADER_LEN - 4) { if (*p != 'P') { p++; continue; } if (*++p != 'K') continue; if (*++p != 5) continue; if (*++p != 6) continue; /* we found CDE! */ memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN); FIX_ENDIANNESS_CDE(cde_header); free(buf); return cde_header.formatted.cdf_offset; } //free(buf); bb_error_msg_and_die("can't find file table"); };
INT64_T link_stream_from_fd(struct link * link, int fd, INT64_T length, time_t stoptime) { char buffer[65536]; INT64_T total = 0; INT64_T ractual, wactual; while(length > 0) { INT64_T chunk = MIN(sizeof(buffer), length); ractual = full_read(fd, buffer, chunk); if(ractual <= 0) break; wactual = link_write(link, buffer, ractual, stoptime); if(wactual != ractual) { total = -1; break; } total += ractual; length -= ractual; } return total; }
static void archivefile(const char *path) { struct fileblock *start, *cur; struct fileblock **prev = &start; int fd, r; unsigned size = 0; struct stat s; /* buffer the file */ fd = xopen(path, O_RDONLY); do { cur = xzalloc(sizeof(*cur)); *prev = cur; prev = &cur->next; r = full_read(fd, cur->data, TAR_BLOCK_SIZE); if (r > 0) size += r; } while (r == TAR_BLOCK_SIZE); /* write archive header */ fstat(fd, &s); close(fd); s.st_size = size; writeheader(path, &s, '0'); /* dump file contents */ for (cur = start; (int)size > 0; size -= TAR_BLOCK_SIZE) { xwrite(STDOUT_FILENO, cur->data, TAR_BLOCK_SIZE); start = cur; cur = cur->next; free(start); } }
static ssize_t tail_read(int fd, char *buf, size_t count, int follow) { ssize_t r; if (follow) { /* tail -f keeps following files even if they are truncated */ off_t current; struct stat sbuf; /* /proc files report zero st_size, don't lseek them */ if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) { current = lseek(fd, 0, SEEK_CUR); if (sbuf.st_size < current) xlseek(fd, 0, SEEK_SET); } } r = full_read(fd, buf, count); if (r < 0) { bb_perror_msg(bb_msg_read_error); G.exitcode = EXIT_FAILURE; } return r; }
bool interval_tree_read(interval_tree tree, int fd, uint64_t n) { interval intervals[INTERVAL_COUNT]; int i, block; bool r; CHECK_MUTEX_LOCKED(tree->mutex); for (; n > 0; n -= block) { block = n > INTERVAL_COUNT ? INTERVAL_COUNT : n; r = full_read(fd, intervals, block * sizeof(interval)); if (!r) return false; for (i = 0; i < block; i++) { intervals[i].start = le_to_u64(intervals[i].start); intervals[i].end = le_to_u64(intervals[i].end); interval_tree_insert(tree, intervals[i].start, intervals[i].end); } } return true; }
char * guestfs_impl_read_file (guestfs_h *g, const char *path, size_t *size_r) { int fd = -1; size_t size; CLEANUP_UNLINK_FREE char *tmpfile = NULL; char *ret = NULL; struct stat statbuf; tmpfile = guestfs_int_make_temp_path (g, "cat", NULL); if (tmpfile == NULL) goto err; if (guestfs_download (g, path, tmpfile) == -1) goto err; fd = open (tmpfile, O_RDONLY|O_CLOEXEC); if (fd == -1) { perrorf (g, "open: %s", tmpfile); goto err; } /* Read the whole file into memory. */ if (fstat (fd, &statbuf) == -1) { perrorf (g, "stat: %s", tmpfile); goto err; } /* Don't use safe_malloc, because we want to return an errno to the caller. */ size = statbuf.st_size; ret = malloc (size + 1); if (!ret) { perrorf (g, "malloc: %zu bytes", size + 1); goto err; } if (full_read (fd, ret, size) != size) { perrorf (g, "full-read: %s: %zu bytes", tmpfile, size + 1); goto err; } ret[size] = '\0'; if (close (fd) == -1) { perrorf (g, "close: %s", tmpfile); goto err; } /* Mustn't touch *size_r until we are sure that we won't return any * error (RHBZ#589039). */ *size_r = size; return ret; err: free (ret); if (fd >= 0) close (fd); return NULL; }
/* TODO: use recursive_action? */ static NOINLINE void edir(const char *directory_name) { int wdir; DIR *dir; struct dirent *d; int fd; wdir = xopen(".", O_RDONLY | O_NDELAY); xchdir(directory_name); dir = xopendir("."); for (;;) { char buf[256]; char *tail; int size; errno = 0; d = readdir(dir); if (!d) { if (errno) bb_perror_msg_and_die("readdir %s", directory_name); break; } if (d->d_name[0] == '.') continue; fd = open(d->d_name, O_RDONLY | O_NDELAY); if (fd < 0) { if ((errno == EISDIR) && directory_name) { if (option_mask32 & OPT_v) bb_perror_msg("warning: %s/%s is a directory", directory_name, d->d_name); continue; } bb_perror_msg_and_die("open %s/%s", directory_name, d->d_name); } size = full_read(fd, buf, sizeof(buf)-1); close(fd); if (size < 0) bb_perror_msg_and_die("read %s/%s", directory_name, d->d_name); if (size == 0) { unsetenv(d->d_name); continue; } buf[size] = '\n'; tail = strchr(buf, '\n'); /* skip trailing whitespace */ while (1) { *tail = '\0'; tail--; if (tail < buf || !isspace(*tail)) break; } xsetenv(d->d_name, buf); } closedir(dir); xfchdir(wdir); close(wdir); }
int read_mesg_array(int fd, struct mesg_array *ma) { ssize_t len; len = (void *)&ma->array[0] - (void *)ma; if (full_read(fd, ma, len)) { return -1; } len = ma->count * sizeof ma->array[0]; if (full_read(fd, &ma->array[0], len)) { return -1; } return 0; }
int64_t copy_fd_to_fd(int in, int out) { int64_t total = 0; while(1) { char buffer[COPY_BUFFER_SIZE]; int64_t actual_read = full_read(in, buffer, COPY_BUFFER_SIZE); if(actual_read <= 0) { if (total == 0) return -1; else break; } int64_t actual_write = full_write(out, buffer, actual_read); if(actual_write == -1) { if (total == 0) return -1; else break; } total += actual_write; } return total; }
int64_t copy_fd_to_stream(int fd, FILE *output) { int64_t total = 0; while(1) { char buffer[COPY_BUFFER_SIZE]; int64_t actual_read = full_read(fd, buffer, sizeof(buffer)); if(actual_read <= 0) { if(total == 0) return -1; else break; } int64_t actual_write = full_fwrite(output, buffer, actual_read); if(actual_write == -1) { if(total == 0) return -1; else break; } total += actual_write; } return total; }
int64_t copy_file_to_buffer(const char *filename, char **buffer, size_t *len) { size_t _len; if (len == NULL) len = &_len; int fd = open(filename, O_RDONLY); if (fd == -1) return -1; struct stat info; if (fstat(fd, &info) == -1) { close(fd); return -1; } *len = info.st_size; *buffer = malloc(*len+1); if (*buffer == NULL) { close(fd); return -1; } memset(*buffer, 0, *len+1); int64_t total = full_read(fd, *buffer, *len); if (total == -1) { free(*buffer); } close(fd); return total; }
void random_init (void) { static int random_initialized = 0; if (random_initialized) return; int fd = open("/dev/urandom", O_RDONLY); if (fd == -1) { fd = open("/dev/random", O_RDONLY); } if (fd >= 0) { uint64_t seed[8]; if (full_read(fd, seed, sizeof(seed)) < (int64_t)sizeof(seed)) goto nasty_fallback; srand(seed[0]); twister_init_by_array64(seed, sizeof(seed)/sizeof(seed[0])); } else { uint64_t seed; nasty_fallback: debug(D_NOTICE, "warning: falling back to low-quality entropy"); seed = (uint64_t)getpid() ^ (uint64_t)time(NULL); seed |= (((uint64_t)(uintptr_t)&seed) << 32); /* using ASLR */ srand(seed); twister_init_genrand64(seed); } close(fd); random_initialized = 1; return; }
static SCM load_thunk_from_fd_using_read (int fd) #define FUNC_NAME "load-thunk-from-disk" { char *data; size_t len; struct stat st; int ret; ret = fstat (fd, &st); if (ret < 0) SCM_SYSERROR; len = st.st_size; data = scm_gc_malloc_pointerless (len, "objcode"); if (full_read (fd, data, len) != len) { int errno_save = errno; (void) close (fd); errno = errno_save; if (errno) SCM_SYSERROR; scm_misc_error (FUNC_NAME, "short read while loading objcode", SCM_EOL); } (void) close (fd); return load_thunk_from_memory (data, len); }
static char* read_env(int sock_fd) { MyString err; int bytes; int env_len; bytes = full_read(0, &env_len, sizeof(env_len)); if (bytes != sizeof(env_len)) { if (bytes == -1) { err.sprintf("read error getting env size: %s", strerror(errno)); } else { err.sprintf("short read of env size: %d of %lu bytes", bytes, sizeof(env_len)); } full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } if (env_len <= 0) { err.sprintf("invalid env size %d read from stdin", env_len); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } char* env_buf = new char[env_len]; if (env_buf == NULL) { err.sprintf("failure to allocate %d bytes", env_len); full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } bytes = full_read(0, env_buf, env_len); if (bytes != env_len) { if (bytes == -1) { err.sprintf("read error getting env: %s", strerror(errno)); } else { err.sprintf("short read of env: %d of %d bytes", bytes, env_len); } full_write(sock_fd, err.Value(), err.Length() + 1); exit(1); } return env_buf; }
static char* map_file_contents (int fd, size_t len, int *is_read_only) #define FUNC_NAME "load-thunk-from-file" { char *data; #ifdef HAVE_SYS_MMAN_H data = mmap (NULL, len, PROT_READ, MAP_PRIVATE, fd, 0); if (data == MAP_FAILED) SCM_SYSERROR; *is_read_only = 1; #else if (lseek (fd, 0, SEEK_START) < 0) { int errno_save = errno; (void) close (fd); errno = errno_save; SCM_SYSERROR; } /* Given that we are using the read fallback, optimistically assume that the .go files were made with 8-byte alignment. alignment. */ data = malloc (end); if (!data) { (void) close (fd); scm_misc_error (FUNC_NAME, "failed to allocate ~A bytes", scm_list_1 (scm_from_size_t (end))); } if (full_read (fd, data, end) != end) { int errno_save = errno; (void) close (fd); errno = errno_save; if (errno) SCM_SYSERROR; scm_misc_error (FUNC_NAME, "short read while loading objcode", SCM_EOL); } /* If our optimism failed, fall back. */ { unsigned alignment = sniff_elf_alignment (data, end); if (alignment != 8) { char *copy = copy_and_align_elf_data (data, end, alignment); free (data); data = copy; } } *is_read_only = 0; #endif return data; }
// Die with an error message if we can't read the entire buffer. void xread(int fd, void *buf, size_t count) { if (count) { ssize_t size = full_read(fd, buf, count); if (size != count) bb_error_msg_and_die("short read"); } }
ssize_t FAST_FUNC read_close(int fd, void *buf, size_t size) { /*int e;*/ size = full_read(fd, buf, size); /*e = errno;*/ close(fd); /*errno = e;*/ return size; }
int dumpleases_main(int argc UNUSED_PARAM, char **argv) { int fd; int i; unsigned opt; time_t expires; const char *file = LEASES_FILE; struct dhcpOfferedAddr lease; struct in_addr addr; enum { OPT_a = 0x1, // -a OPT_r = 0x2, // -r OPT_f = 0x4, // -f }; #if ENABLE_GETOPT_LONG static const char dumpleases_longopts[] ALIGN1 = "absolute\0" No_argument "a" "remaining\0" No_argument "r" "file\0" Required_argument "f" ; applet_long_options = dumpleases_longopts; #endif opt_complementary = "=0:a--r:r--a"; opt = getopt32(argv, "arf:", &file); fd = xopen(file, O_RDONLY); printf("Mac Address IP-Address Expires %s\n", (opt & OPT_a) ? "at" : "in"); /* "00:00:00:00:00:00 255.255.255.255 Wed Jun 30 21:49:08 1993" */ while (full_read(fd, &lease, sizeof(lease)) == sizeof(lease)) { printf(":%02x"+1, lease.chaddr[0]); for (i = 1; i < 6; i++) { printf(":%02x", lease.chaddr[i]); } addr.s_addr = lease.yiaddr; printf(" %-15s ", inet_ntoa(addr)); expires = ntohl(lease.expires); if (!(opt & OPT_a)) { /* no -a */ if (!expires) puts("expired"); else { unsigned d, h, m; d = expires / (24*60*60); expires %= (24*60*60); h = expires / (60*60); expires %= (60*60); m = expires / 60; expires %= 60; if (d) printf("%u days ", d); printf("%02u:%02u:%02u\n", h, m, (unsigned)expires); } } else /* -a */ fputs(ctime(&expires), stdout); } /* close(fd); */ return 0; }
int copyfile_slow( const char *source, const char *target ) { char *buffer; int buffer_size = 65536; int s, t; int result, actual; int nerrors = 0; struct stat64 info; s = open(source,O_RDONLY,0); if(s<0) { fprintf(stderr,"parrot_cp: couldn't open '%s' for reading: %s\n",source,strerror(errno)); return 1; } fstat64(s,&info); if(S_ISDIR(info.st_mode)) { errno = EISDIR; return -1; } t = open(target,O_WRONLY|O_CREAT|O_TRUNC,0777); if(t<0) { fprintf(stderr,"parrot_cp: couldn't open '%s' for writing: %s\n",target,strerror(errno)); return 1; } buffer = malloc(buffer_size); while(1) { result = full_read(s,buffer,buffer_size); if(result<0) { fprintf(stderr,"parrot_cp: error reading '%s': %s\n",source,strerror(errno)); nerrors++; break; } else if(result==0) { break; } actual = full_write(t,buffer,result); if(result!=actual) { fprintf(stderr,"parrot_cp: error writing '%s': %s\n",target,strerror(errno)); nerrors++; break; } } close(s); close(t); free(buffer); if(nerrors) { return -1; } else { return 0; } }
ssize_t ICACHE_FLASH_ATTR read_close(int fd, void *buf, size_t size) { /*int e;*/ size = full_read(fd, buf, size); /*e = errno;*/ close(fd); /*errno = e;*/ return size; }
/* Die with an error message if we can't read the entire buffer. */ void xread(struct mbreader_t *md, void *buf, ssize_t count) { if (count) { ssize_t size = full_read(md, buf, count); if (size != count) error_die("short read"); } }
static int lookup (confuga *C, const char *path, confuga_fid_t *fid, confuga_off_t *size, enum CONFUGA_FILE_TYPE *type) { int rc; int fd = -1; ssize_t n; char header[HEADER_LENGTH+1] = ""; struct stat64 info; fd = open(path, O_RDONLY); CATCHUNIX(fd); CATCHUNIX(fstat64(fd, &info)); if (S_ISDIR(info.st_mode)) CATCH(EISDIR); else if (!S_ISREG(info.st_mode)) CATCH(EINVAL); n = full_read(fd, header, HEADER_LENGTH); if (n < (ssize_t)HEADER_LENGTH) CATCH(EINVAL); debug(D_DEBUG, "read `%s'", header); /* debug chomps final newline */ const char *current = header; if (strncmp(current, "file:", strlen("file:")) == 0) *type = CONFUGA_FILE; else if (strncmp(current, "meta:", strlen("meta:")) == 0) *type = CONFUGA_FILE; else CATCH(EINVAL); current += 5; /* read hash */ int i; for (i = 0; i < (int)sizeof(fid->id); i += 1, current += 2) { char byte[3] = {current[0], current[1], '\0'}; unsigned long value = strtoul(byte, NULL, 16); fid->id[i] = value; } assert(current[0] == ':'); current += 1; /* read size */ if (size) { char *endptr; *size = strtoull(current, &endptr, 16); assert(*endptr == '\n'); } rc = 0; goto out; out: close(fd); return rc; }
/* Should make sure the queue is non-full prior to calling this. */ ssize_t byteq_full_read(ByteQ *bq, int fd) { ssize_t res = 0; res = full_read(fd, bq->buf+bq->cur, bq->max-bq->cur); if (res > 0) bq->cur += res; return res; }
ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned char *buf, size_t count) { ssize_t size; size = full_read(archive_handle->src_fd, buf, count); if (size != 0 && size != (ssize_t)count) { bb_error_msg_and_die("short read: %u of %u", (unsigned)size, (unsigned)count); } return size; }
static int create_pidfile(void) { /* Note: * No O_EXCL: we would happily overwrite stale pidfile from previous boot. * No O_TRUNC: we must first try to lock the file, and if lock fails, * there is another live abrtd. O_TRUNCing the file in this case * would be wrong - it'll erase the pid to empty string! */ int fd = open(VAR_RUN_PIDFILE, O_RDWR|O_CREAT, 0644); if (fd >= 0) { if (lockf(fd, F_TLOCK, 0) < 0) { perror_msg("Can't lock file '%s'", VAR_RUN_PIDFILE); /* should help with problems like rhbz#859724 */ char pid_str[sizeof(long)*3 + 4]; int r = full_read(fd, pid_str, sizeof(pid_str)); close(fd); /* File can contain garbage. Be careful interpreting it as PID */ if (r > 0) { pid_str[r] = '\0'; errno = 0; long locking_pid = strtol(pid_str, NULL, 10); if (!errno && locking_pid > 0 && locking_pid <= INT_MAX) { char *cmdline = get_cmdline(locking_pid); if (cmdline) { error_msg("Process %lu '%s' is holding the lock", locking_pid, cmdline); free(cmdline); } } } return -1; } close_on_exec_on(fd); /* write our pid to it */ char buf[sizeof(long)*3 + 2]; int len = sprintf(buf, "%lu\n", (long)getpid()); IGNORE_RESULT(write(fd, buf, len)); IGNORE_RESULT(ftruncate(fd, len)); /* we leak opened+locked fd intentionally */ return 0; } perror_msg("Can't open '%s'", VAR_RUN_PIDFILE); return -1; }
int FAST_FUNC check_signature16(transformer_aux_data_t *aux, int src_fd, unsigned magic16) { if (aux && aux->check_signature) { uint16_t magic2; if (full_read(src_fd, &magic2, 2) != 2 || magic2 != magic16) { bb_error_msg("invalid magic"); #if 0 /* possible future extension */ if (aux->check_signature > 1) xfunc_die(); #endif return -1; } } return 0; }