Index: stable/12/lib/libsecureboot/vectx.c =================================================================== --- stable/12/lib/libsecureboot/vectx.c (revision 359910) +++ stable/12/lib/libsecureboot/vectx.c (revision 359911) @@ -1,364 +1,372 @@ /*- * Copyright (c) 2018, Juniper Networks, Inc. * * 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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 __FBSDID("$FreeBSD$"); #ifndef _STANDALONE /* Avoid unwanted userlandish components */ #define _KERNEL #include #undef _KERNEL #endif #include "libsecureboot-priv.h" #include /** * @file vectx.c * @brief api to verify file while reading * * This API allows the hash of a file to be computed as it is read. * Key to this is seeking by reading. * * On close an indication of the verification result is returned. */ struct vectx { br_hash_compat_context vec_ctx; /* hash ctx */ const br_hash_class *vec_md; /* hash method */ const char *vec_path; /* path we are verifying */ const char *vec_want; /* hash value we want */ off_t vec_off; /* current offset */ off_t vec_hashed; /* where we have hashed to */ size_t vec_size; /* size of path */ size_t vec_hashsz; /* size of hash */ int vec_fd; /* file descriptor */ int vec_status; /* verification status */ }; /** * @brief * verify an open file as we read it * * If the file has no fingerprint to match, we will still return a * verification context containing little more than the file * descriptor, and an error code in @c error. * * @param[in] fd * open descriptor * * @param[in] path * pathname to open * * @param[in] off * current offset * * @param[in] stp * pointer to struct stat * * @param[out] error * @li 0 all is good * @li ENOMEM out of memory * @li VE_FINGERPRINT_NONE no entry found * @li VE_FINGERPRINT_UNKNOWN no fingerprint in entry * * @return ctx or NULL on error. * NULL is only returned for non-files or out-of-memory. */ struct vectx * vectx_open(int fd, const char *path, off_t off, struct stat *stp, int *error, const char *caller) { struct vectx *ctx; struct stat st; size_t hashsz; char *cp; int rc; if (!stp) stp = &st; rc = verify_prep(fd, path, off, stp, __func__); DEBUG_PRINTF(2, ("vectx_open: caller=%s,fd=%d,name='%s',prep_rc=%d\n", caller, fd, path, rc)); switch (rc) { case VE_FINGERPRINT_NONE: case VE_FINGERPRINT_UNKNOWN: case VE_FINGERPRINT_WRONG: *error = rc; return (NULL); } ctx = malloc(sizeof(struct vectx)); if (!ctx) goto enomem; ctx->vec_fd = fd; ctx->vec_path = path; ctx->vec_size = stp->st_size; ctx->vec_off = 0; ctx->vec_hashed = 0; ctx->vec_want = NULL; ctx->vec_status = 0; ctx->vec_hashsz = hashsz = 0; if (rc == 0) { /* we are not verifying this */ *error = 0; return (ctx); } cp = fingerprint_info_lookup(fd, path); if (!cp) { ctx->vec_status = VE_FINGERPRINT_NONE; ve_error_set("%s: no entry", path); } else { if (strncmp(cp, "no_hash", 7) == 0) { ctx->vec_status = VE_FINGERPRINT_IGNORE; hashsz = 0; } else if (strncmp(cp, "sha256=", 7) == 0) { ctx->vec_md = &br_sha256_vtable; hashsz = br_sha256_SIZE; cp += 7; #ifdef VE_SHA1_SUPPORT } else if (strncmp(cp, "sha1=", 5) == 0) { ctx->vec_md = &br_sha1_vtable; hashsz = br_sha1_SIZE; cp += 5; #endif #ifdef VE_SHA384_SUPPORT } else if (strncmp(cp, "sha384=", 7) == 0) { ctx->vec_md = &br_sha384_vtable; hashsz = br_sha384_SIZE; cp += 7; #endif #ifdef VE_SHA512_SUPPORT } else if (strncmp(cp, "sha512=", 7) == 0) { ctx->vec_md = &br_sha512_vtable; hashsz = br_sha512_SIZE; cp += 7; #endif } else { ctx->vec_status = VE_FINGERPRINT_UNKNOWN; ve_error_set("%s: no supported fingerprint", path); } } *error = ctx->vec_status; ctx->vec_hashsz = hashsz; ctx->vec_want = cp; if (hashsz > 0) { ctx->vec_md->init(&ctx->vec_ctx.vtable); if (off > 0) { lseek(fd, 0, SEEK_SET); vectx_lseek(ctx, off, SEEK_SET); } } DEBUG_PRINTF(2, ("vectx_open: caller=%s,name='%s',hashsz=%lu,status=%d\n", caller, path, (unsigned long)ctx->vec_hashsz, ctx->vec_status)); return (ctx); enomem: /* unlikely */ *error = ENOMEM; free(ctx); return (NULL); } /** * @brief * read bytes from file and update hash * * It is critical that all file I/O comes through here. * We keep track of current offset. * We also track what offset we have hashed to, * so we won't replay data if we seek backwards. * * @param[in] pctx * pointer to ctx * * @param[in] buf * * @param[in] nbytes * * @return bytes read or error. */ ssize_t vectx_read(struct vectx *ctx, void *buf, size_t nbytes) { unsigned char *bp = buf; + int d; int n; int delta; int x; size_t off; if (ctx->vec_hashsz == 0) /* nothing to do */ return (read(ctx->vec_fd, buf, nbytes)); off = 0; do { - n = read(ctx->vec_fd, &bp[off], nbytes - off); - if (n < 0) + /* + * Do this in reasonable chunks so + * we don't timeout if doing tftp + */ + x = nbytes - off; + x = MIN(PAGE_SIZE, x); + d = n = read(ctx->vec_fd, &bp[off], x); + if (n < 0) { return (n); - if (n > 0) { + } + if (d > 0) { /* we may have seeked backwards! */ delta = ctx->vec_hashed - ctx->vec_off; if (delta > 0) { - x = MIN(delta, n); + x = MIN(delta, d); off += x; - n -= x; + d -= x; ctx->vec_off += x; } - if (n > 0) { - ctx->vec_md->update(&ctx->vec_ctx.vtable, &bp[off], n); - off += n; - ctx->vec_off += n; - ctx->vec_hashed += n; + if (d > 0) { + ctx->vec_md->update(&ctx->vec_ctx.vtable, &bp[off], d); + off += d; + ctx->vec_off += d; + ctx->vec_hashed += d; } } } while (n > 0 && off < nbytes); return (off); } /** * @brief * vectx equivalent of lseek * * When seeking forwards we actually call vectx_read * to reach the desired offset. * * We support seeking backwards. * * @param[in] pctx * pointer to ctx * * @param[in] off * desired offset * * @param[in] whence * We try to convert whence to ``SEEK_SET``. * We do not support ``SEEK_DATA`` or ``SEEK_HOLE``. * * @return offset or error. */ off_t vectx_lseek(struct vectx *ctx, off_t off, int whence) { unsigned char buf[PAGE_SIZE]; size_t delta; ssize_t n; if (ctx->vec_hashsz == 0) /* nothing to do */ return (lseek(ctx->vec_fd, off, whence)); /* * Convert whence to SEEK_SET */ if (whence == SEEK_END && off <= 0) { whence = SEEK_SET; off += ctx->vec_size; } else if (whence == SEEK_CUR) { whence = SEEK_SET; off += ctx->vec_off; } if (whence != SEEK_SET || (size_t)off > ctx->vec_size) { printf("ERROR: %s: unsupported operation: whence=%d off=%lld -> %lld\n", __func__, whence, (long long)ctx->vec_off, (long long)off); return (-1); } if (off < ctx->vec_hashed) { /* seeking backwards! just do it */ ctx->vec_off = lseek(ctx->vec_fd, off, whence); return (ctx->vec_off); } n = 0; do { delta = off - ctx->vec_off; if (delta > 0) { delta = MIN(PAGE_SIZE, delta); n = vectx_read(ctx, buf, delta); if (n < 0) return (n); } } while (ctx->vec_off < off && n > 0); return (ctx->vec_off); } /** * @brief * check that hashes match and cleanup * * We have finished reading file, compare the hash with what * we wanted. * * Be sure to call this before closing the file, since we may * need to seek to the end to ensure hashing is complete. * * @param[in] pctx * pointer to ctx * * @return 0 or an error. */ int vectx_close(struct vectx *ctx, int severity, const char *caller) { int rc; if (ctx->vec_hashsz == 0) { rc = ctx->vec_status; } else { #ifdef VE_PCR_SUPPORT /* * Only update pcr with things that must verify * these tend to be processed in a more deterministic * order, which makes our pseudo pcr more useful. */ ve_pcr_updating_set((severity == VE_MUST)); #endif /* make sure we have hashed it all */ vectx_lseek(ctx, 0, SEEK_END); rc = ve_check_hash(&ctx->vec_ctx, ctx->vec_md, ctx->vec_path, ctx->vec_want, ctx->vec_hashsz); } DEBUG_PRINTF(2, ("vectx_close: caller=%s,name='%s',rc=%d,severity=%d\n", caller,ctx->vec_path, rc, severity)); if (rc == VE_FINGERPRINT_WRONG) { printf("Unverified: %s\n", ve_error_get()); #if !defined(UNIT_TEST) && !defined(DEBUG_VECTX) /* we are generally called with VE_MUST */ if (severity > VE_WANT) panic("cannot continue"); #endif } else if (severity > VE_WANT) { printf("%serified %s\n", (rc <= 0) ? "Unv" : "V", ctx->vec_path); } free(ctx); return ((rc < 0) ? rc : 0); } Index: stable/12/stand/libsa/pkgfs.c =================================================================== --- stable/12/stand/libsa/pkgfs.c (revision 359910) +++ stable/12/stand/libsa/pkgfs.c (revision 359911) @@ -1,809 +1,822 @@ /*- * Copyright (c) 2007-2014, Juniper Networks, Inc. * 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 __FBSDID("$FreeBSD$"); #include "stand.h" #include #include #include #include #ifdef PKGFS_DEBUG #define DBG(x) printf x #else #define DBG(x) #endif static int pkg_open(const char *, struct open_file *); static int pkg_close(struct open_file *); static int pkg_read(struct open_file *, void *, size_t, size_t *); static off_t pkg_seek(struct open_file *, off_t, int); static int pkg_stat(struct open_file *, struct stat *); static int pkg_readdir(struct open_file *, struct dirent *); static off_t pkg_atol(const char *, unsigned); struct fs_ops pkgfs_fsops = { "pkg", pkg_open, pkg_close, pkg_read, null_write, pkg_seek, pkg_stat, pkg_readdir }; #define PKG_BUFSIZE 512 -#define PKG_MAXCACHESZ 16384 +#define PKG_MAXCACHESZ (16384 * 3) #define PKG_FILEEXT ".tgz" /* * Layout of POSIX 'ustar' header. */ struct ustar_hdr { char ut_name[100]; char ut_mode[8]; char ut_uid[8]; char ut_gid[8]; char ut_size[12]; char ut_mtime[12]; char ut_checksum[8]; char ut_typeflag[1]; char ut_linkname[100]; char ut_magic[6]; /* For POSIX: "ustar\0" */ char ut_version[2]; /* For POSIX: "00" */ char ut_uname[32]; char ut_gname[32]; char ut_rdevmajor[8]; char ut_rdevminor[8]; union { struct { char prefix[155]; } posix; struct { char atime[12]; char ctime[12]; char offset[12]; char longnames[4]; char unused[1]; struct gnu_sparse { char offset[12]; char numbytes[12]; } sparse[4]; char isextended[1]; char realsize[12]; } gnu; } u; u_char __padding[12]; }; struct package; struct tarfile { struct package *tf_pkg; struct tarfile *tf_next; struct ustar_hdr tf_hdr; off_t tf_ofs; off_t tf_size; off_t tf_fp; size_t tf_cachesz; void *tf_cache; }; struct package { struct package *pkg_chain; int pkg_fd; off_t pkg_ofs; z_stream pkg_zs; struct tarfile *pkg_first; struct tarfile *pkg_last; u_char pkg_buf[PKG_BUFSIZE]; }; static struct package *package = NULL; static int new_package(int, struct package **); +static int cache_data(struct tarfile *tf, int); void pkgfs_cleanup(void) { struct package *chain; struct tarfile *tf, *tfn; while (package != NULL) { inflateEnd(&package->pkg_zs); close(package->pkg_fd); tf = package->pkg_first; while (tf != NULL) { tfn = tf->tf_next; if (tf->tf_cachesz > 0) free(tf->tf_cache); free(tf); tf = tfn; } chain = package->pkg_chain; free(package); package = chain; } } int pkgfs_init(const char *pkgname, struct fs_ops *proto) { struct package *pkg; int error, fd; pkg = NULL; if (proto != &pkgfs_fsops) pkgfs_cleanup(); exclusive_file_system = proto; fd = open(pkgname, O_RDONLY); exclusive_file_system = NULL; if (fd == -1) return (errno); error = new_package(fd, &pkg); if (error) { close(fd); return (error); } if (pkg == NULL) return (EDOOFUS); pkg->pkg_chain = package; package = pkg; exclusive_file_system = &pkgfs_fsops; return (0); } static int get_mode(struct tarfile *); static int get_zipped(struct package *, void *, size_t); static int new_package(int, struct package **); static struct tarfile *scan_tarfile(struct package *, struct tarfile *); static int pkg_open(const char *fn, struct open_file *f) { struct tarfile *tf; if (fn == NULL || f == NULL) return (EINVAL); if (package == NULL) return (ENXIO); /* * We can only read from a package, so reject request to open * for write-only or read-write. */ if (f->f_flags != F_READ) return (EPERM); /* * Scan the file headers for the named file. We stop scanning * at the first filename that has the .pkg extension. This is * a package within a package. We assume we have all the files * we need up-front and without having to dig within nested * packages. * * Note that we preserve streaming properties as much as possible. */ while (*fn == '/') fn++; /* * Allow opening of the root directory for use by readdir() * to support listing files in the package. */ if (*fn == '\0') { f->f_fsdata = NULL; return (0); } tf = scan_tarfile(package, NULL); while (tf != NULL) { if (strcmp(fn, tf->tf_hdr.ut_name) == 0) { f->f_fsdata = tf; tf->tf_fp = 0; /* Reset the file pointer. */ return (0); } tf = scan_tarfile(package, tf); } return (errno); } static int pkg_close(struct open_file *f) { struct tarfile *tf; tf = (struct tarfile *)f->f_fsdata; if (tf == NULL) return (0); /* * Free up the cache if we read all of the file. */ if (tf->tf_fp == tf->tf_size && tf->tf_cachesz > 0) { free(tf->tf_cache); tf->tf_cachesz = 0; } return (0); } static int pkg_read(struct open_file *f, void *buf, size_t size, size_t *res) { struct tarfile *tf; char *p; off_t fp; size_t sz; tf = (struct tarfile *)f->f_fsdata; if (tf == NULL) { if (res != NULL) *res = size; return (EBADF); } + if (tf->tf_cachesz == 0) + cache_data(tf, 1); + fp = tf->tf_fp; p = buf; sz = 0; while (size > 0) { sz = tf->tf_size - fp; if (fp < tf->tf_cachesz && tf->tf_cachesz < tf->tf_size) sz = tf->tf_cachesz - fp; if (size < sz) sz = size; if (sz == 0) break; if (fp < tf->tf_cachesz) { /* Satisfy the request from cache. */ memcpy(p, tf->tf_cache + fp, sz); fp += sz; p += sz; size -= sz; continue; } if (get_zipped(tf->tf_pkg, p, sz) == -1) { sz = -1; break; } fp += sz; p += sz; size -= sz; - - if (tf->tf_cachesz != 0) - continue; - - tf->tf_cachesz = (sz <= PKG_MAXCACHESZ) ? sz : PKG_MAXCACHESZ; - tf->tf_cache = malloc(tf->tf_cachesz); - if (tf->tf_cache != NULL) - memcpy(tf->tf_cache, buf, tf->tf_cachesz); - else - tf->tf_cachesz = 0; } tf->tf_fp = fp; if (res != NULL) *res = size; return ((sz == -1) ? errno : 0); } static off_t pkg_seek(struct open_file *f, off_t ofs, int whence) { char buf[512]; struct tarfile *tf; off_t delta; off_t nofs; size_t sz, res; int error; tf = (struct tarfile *)f->f_fsdata; if (tf == NULL) { errno = EBADF; return (-1); } switch (whence) { case SEEK_SET: delta = ofs - tf->tf_fp; break; case SEEK_CUR: delta = ofs; break; case SEEK_END: delta = tf->tf_size - tf->tf_fp + ofs; break; default: errno = EINVAL; return (-1); } if (delta < 0) { /* seeking backwards - ok if within cache */ if (tf->tf_cachesz > 0 && tf->tf_fp <= tf->tf_cachesz) { nofs = tf->tf_fp + delta; if (nofs >= 0) { tf->tf_fp = nofs; return (tf->tf_fp); } } DBG(("%s: negative file seek (%jd)\n", __func__, (intmax_t)delta)); errno = ESPIPE; return (-1); } while (delta > 0 && tf->tf_fp < tf->tf_size) { sz = (delta > sizeof(buf)) ? sizeof(buf) : delta; error = pkg_read(f, buf, sz, &res); if (error != 0) { errno = error; return (-1); } delta -= sz - res; } return (tf->tf_fp); } static int pkg_stat(struct open_file *f, struct stat *sb) { struct tarfile *tf; tf = (struct tarfile *)f->f_fsdata; if (tf == NULL) return (EBADF); memset(sb, 0, sizeof(*sb)); sb->st_mode = get_mode(tf); if ((sb->st_mode & S_IFMT) == 0) { /* tar file bug - assume regular file */ sb->st_mode |= S_IFREG; } sb->st_size = tf->tf_size; sb->st_blocks = (tf->tf_size + 511) / 512; sb->st_mtime = pkg_atol(tf->tf_hdr.ut_mtime, 12); sb->st_dev = (off_t)tf->tf_pkg; sb->st_ino = tf->tf_ofs; /* unique per tf_pkg */ return (0); } static int pkg_readdir(struct open_file *f, struct dirent *d) { struct tarfile *tf; tf = (struct tarfile *)f->f_fsdata; if (tf != NULL) return (EBADF); tf = scan_tarfile(package, NULL); if (tf == NULL) return (ENOENT); d->d_fileno = 0; d->d_reclen = sizeof(*d); d->d_type = DT_REG; memcpy(d->d_name, tf->tf_hdr.ut_name, sizeof(d->d_name)); return (0); } /* * Low-level support functions. */ static int get_byte(struct package *pkg, off_t *op) { int c; if (pkg->pkg_zs.avail_in == 0) { c = read(pkg->pkg_fd, pkg->pkg_buf, PKG_BUFSIZE); if (c <= 0) return (-1); pkg->pkg_zs.avail_in = c; pkg->pkg_zs.next_in = pkg->pkg_buf; } c = *pkg->pkg_zs.next_in; pkg->pkg_zs.next_in++; pkg->pkg_zs.avail_in--; (*op)++; return (c); } static int get_zipped(struct package *pkg, void *buf, size_t bufsz) { int c; pkg->pkg_zs.next_out = buf; pkg->pkg_zs.avail_out = bufsz; while (pkg->pkg_zs.avail_out) { if (pkg->pkg_zs.avail_in == 0) { c = read(pkg->pkg_fd, pkg->pkg_buf, PKG_BUFSIZE); if (c <= 0) { errno = EIO; return (-1); } pkg->pkg_zs.avail_in = c; pkg->pkg_zs.next_in = pkg->pkg_buf; } c = inflate(&pkg->pkg_zs, Z_SYNC_FLUSH); if (c != Z_OK && c != Z_STREAM_END) { errno = EIO; return (-1); } } pkg->pkg_ofs += bufsz; return (0); } +/** + * @brief + * cache data of a tarfile + * + * @param[in] tf + * tarfile pointer + * + * @param[in] force + * If file size > PKG_MAXCACHESZ, cache that much + * + * @return 0, -1 (errno set to error value) + */ static int -cache_data(struct tarfile *tf) +cache_data(struct tarfile *tf, int force) { struct package *pkg; size_t sz; if (tf == NULL) { DBG(("%s: no file to cache data for?\n", __func__)); errno = EINVAL; return (-1); } pkg = tf->tf_pkg; if (pkg == NULL) { DBG(("%s: no package associated with file?\n", __func__)); errno = EINVAL; return (-1); } + if (tf->tf_cachesz > 0) { + DBG(("%s: data already cached\n", __func__)); + errno = EINVAL; + return (-1); + } + if (tf->tf_ofs != pkg->pkg_ofs) { - DBG(("%s: caching after partial read of file %s?\n", + DBG(("%s: caching after force read of file %s?\n", __func__, tf->tf_hdr.ut_name)); errno = EINVAL; return (-1); } /* We don't cache everything... */ - if (tf->tf_size > PKG_MAXCACHESZ) { - errno = ENOMEM; + if (tf->tf_size > PKG_MAXCACHESZ && !force) { + errno = ENOBUFS; return (-1); } + sz = tf->tf_size < PKG_MAXCACHESZ ? tf->tf_size : PKG_MAXCACHESZ; /* All files are padded to a multiple of 512 bytes. */ - sz = (tf->tf_size + 0x1ff) & ~0x1ff; + sz = (sz + 0x1ff) & ~0x1ff; tf->tf_cache = malloc(sz); if (tf->tf_cache == NULL) { DBG(("%s: could not allocate %d bytes\n", __func__, (int)sz)); errno = ENOMEM; return (-1); } tf->tf_cachesz = sz; return (get_zipped(pkg, tf->tf_cache, sz)); } /* * Note that this implementation does not (and should not!) obey * locale settings; you cannot simply substitute strtol here, since * it does obey locale. */ static off_t pkg_atol8(const char *p, unsigned char_cnt) { int64_t l, limit, last_digit_limit; int digit, sign, base; base = 8; limit = INT64_MAX / base; last_digit_limit = INT64_MAX % base; while (*p == ' ' || *p == '\t') p++; if (*p == '-') { sign = -1; p++; } else sign = 1; l = 0; digit = *p - '0'; while (digit >= 0 && digit < base && char_cnt-- > 0) { if (l>limit || (l == limit && digit > last_digit_limit)) { l = UINT64_MAX; /* Truncate on overflow. */ break; } l = (l * base) + digit; digit = *++p - '0'; } return (sign < 0) ? -l : l; } /* * Parse a base-256 integer. This is just a straight signed binary * value in big-endian order, except that the high-order bit is * ignored. Remember that "int64_t" may or may not be exactly 64 * bits; the implementation here tries to avoid making any assumptions * about the actual size of an int64_t. It does assume we're using * twos-complement arithmetic, though. */ static int64_t pkg_atol256(const char *_p, unsigned char_cnt) { int64_t l, upper_limit, lower_limit; const unsigned char *p = (const unsigned char *)_p; upper_limit = INT64_MAX / 256; lower_limit = INT64_MIN / 256; /* Pad with 1 or 0 bits, depending on sign. */ if ((0x40 & *p) == 0x40) l = (int64_t)-1; else l = 0; l = (l << 6) | (0x3f & *p++); while (--char_cnt > 0) { if (l > upper_limit) { l = INT64_MAX; /* Truncate on overflow */ break; } else if (l < lower_limit) { l = INT64_MIN; break; } l = (l << 8) | (0xff & (int64_t)*p++); } return (l); } static off_t pkg_atol(const char *p, unsigned char_cnt) { /* * Technically, GNU pkg considers a field to be in base-256 * only if the first byte is 0xff or 0x80. */ if (*p & 0x80) return (pkg_atol256(p, char_cnt)); return (pkg_atol8(p, char_cnt)); } static int get_mode(struct tarfile *tf) { return (pkg_atol(tf->tf_hdr.ut_mode, sizeof(tf->tf_hdr.ut_mode))); } /* GZip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define RESERVED 0xE0 /* bits 5..7: reserved */ static int new_package(int fd, struct package **pp) { struct package *pkg; off_t ofs; int flags, i, error; pkg = malloc(sizeof(*pkg)); if (pkg == NULL) return (ENOMEM); bzero(pkg, sizeof(*pkg)); pkg->pkg_fd = fd; /* * Parse the header. */ error = EFTYPE; ofs = 0; /* Check megic. */ if (get_byte(pkg, &ofs) != 0x1f || get_byte(pkg, &ofs) != 0x8b) goto fail; /* Check method. */ if (get_byte(pkg, &ofs) != Z_DEFLATED) goto fail; /* Check flags. */ flags = get_byte(pkg, &ofs); if (flags & RESERVED) goto fail; /* Skip time, xflags and OS code. */ for (i = 0; i < 6; i++) { if (get_byte(pkg, &ofs) == -1) goto fail; } /* Skip extra field. */ if (flags & EXTRA_FIELD) { i = (get_byte(pkg, &ofs) & 0xff) | ((get_byte(pkg, &ofs) << 8) & 0xff); while (i-- > 0) { if (get_byte(pkg, &ofs) == -1) goto fail; } } /* Skip original file name. */ if (flags & ORIG_NAME) { do { i = get_byte(pkg, &ofs); } while (i != 0 && i != -1); if (i == -1) goto fail; } /* Print the comment if it's there. */ if (flags & COMMENT) { while (1) { i = get_byte(pkg, &ofs); if (i == -1) goto fail; if (i == 0) break; putchar(i); } } /* Skip the CRC. */ if (flags & HEAD_CRC) { if (get_byte(pkg, &ofs) == -1) goto fail; if (get_byte(pkg, &ofs) == -1) goto fail; } /* * Done parsing the ZIP header. Spkgt the inflation engine. */ error = inflateInit2(&pkg->pkg_zs, -15); if (error != Z_OK) goto fail; *pp = pkg; return (0); fail: free(pkg); return (error); } static struct tarfile * scan_tarfile(struct package *pkg, struct tarfile *last) { char buf[512]; struct tarfile *cur; off_t ofs; size_t sz; cur = (last != NULL) ? last->tf_next : pkg->pkg_first; if (cur == NULL) { ofs = (last != NULL) ? last->tf_ofs + last->tf_size : pkg->pkg_ofs; ofs = (ofs + 0x1ff) & ~0x1ff; /* Check if we've reached EOF. */ if (ofs < pkg->pkg_ofs) { errno = ENOSPC; return (NULL); } if (ofs != pkg->pkg_ofs) { if (last != NULL && pkg->pkg_ofs == last->tf_ofs) { - if (cache_data(last) == -1) + if (cache_data(last, 0) == -1) return (NULL); } else { sz = ofs - pkg->pkg_ofs; while (sz != 0) { if (sz > sizeof(buf)) sz = sizeof(buf); if (get_zipped(pkg, buf, sz) == -1) return (NULL); sz = ofs - pkg->pkg_ofs; } } } cur = malloc(sizeof(*cur)); if (cur == NULL) return (NULL); memset(cur, 0, sizeof(*cur)); cur->tf_pkg = pkg; while (1) { if (get_zipped(pkg, &cur->tf_hdr, sizeof(cur->tf_hdr)) == -1) { free(cur); return (NULL); } /* * There are always 2 empty blocks appended to * a PKG. It marks the end of the archive. */ if (strncmp(cur->tf_hdr.ut_magic, "ustar", 5) != 0) { free(cur); errno = ENOSPC; return (NULL); } cur->tf_ofs = pkg->pkg_ofs; cur->tf_size = pkg_atol(cur->tf_hdr.ut_size, sizeof(cur->tf_hdr.ut_size)); if (cur->tf_hdr.ut_name[0] != '+') break; /* * Skip package meta-files. */ ofs = cur->tf_ofs + cur->tf_size; ofs = (ofs + 0x1ff) & ~0x1ff; while (pkg->pkg_ofs < ofs) { if (get_zipped(pkg, buf, sizeof(buf)) == -1) { free(cur); return (NULL); } } } if (last != NULL) last->tf_next = cur; else pkg->pkg_first = cur; pkg->pkg_last = cur; } return (cur); } Index: stable/12/stand/libsa/tftp.c =================================================================== --- stable/12/stand/libsa/tftp.c (revision 359910) +++ stable/12/stand/libsa/tftp.c (revision 359911) @@ -1,754 +1,761 @@ /* $NetBSD: tftp.c,v 1.4 1997/09/17 16:57:07 drochner Exp $ */ /* * Copyright (c) 1996 * Matthias Drochner. 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project * by Matthias Drochner. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 __FBSDID("$FreeBSD$"); /* * Simple TFTP implementation for libsa. * Assumes: * - socket descriptor (int) at open_file->f_devdata * - server host IP in global servip * Restrictions: * - read only * - lseek only with SEEK_SET or SEEK_CUR * - no big time differences between transfers ( #include #include #include #include #include #include #include "stand.h" #include "net.h" #include "netif.h" #include "tftp.h" struct tftp_handle; struct tftprecv_extra; static ssize_t recvtftp(struct iodesc *, void **, void **, time_t, void *); static int tftp_open(const char *, struct open_file *); static int tftp_close(struct open_file *); static int tftp_parse_oack(struct tftp_handle *, char *, size_t); static int tftp_read(struct open_file *, void *, size_t, size_t *); static off_t tftp_seek(struct open_file *, off_t, int); static int tftp_set_blksize(struct tftp_handle *, const char *); static int tftp_stat(struct open_file *, struct stat *); struct fs_ops tftp_fsops = { .fs_name = "tftp", .fo_open = tftp_open, .fo_close = tftp_close, .fo_read = tftp_read, .fo_write = null_write, .fo_seek = tftp_seek, .fo_stat = tftp_stat, .fo_readdir = null_readdir }; extern struct in_addr servip; static int tftpport = 2000; static int is_open = 0; /* * The legacy TFTP_BLKSIZE value was SEGSIZE(512). * TFTP_REQUESTED_BLKSIZE of 1428 is (Ethernet MTU, less the TFTP, UDP and * IP header lengths). */ #define TFTP_REQUESTED_BLKSIZE 1428 /* * Choose a blksize big enough so we can test with Ethernet * Jumbo frames in the future. */ #define TFTP_MAX_BLKSIZE 9008 +#define TFTP_TRIES 2 struct tftp_handle { struct iodesc *iodesc; int currblock; /* contents of lastdata */ - int islastblock; /* flag */ + int islastblock:1; /* flag */ + int tries:4; /* number of read attempts */ int validsize; int off; char *path; /* saved for re-requests */ unsigned int tftp_blksize; unsigned long tftp_tsize; void *pkt; struct tftphdr *tftp_hdr; }; struct tftprecv_extra { struct tftp_handle *tftp_handle; unsigned short rtype; /* Received type */ }; #define TFTP_MAX_ERRCODE EOPTNEG static const int tftperrors[TFTP_MAX_ERRCODE + 1] = { 0, /* ??? */ ENOENT, EPERM, ENOSPC, EINVAL, /* ??? */ EINVAL, /* ??? */ EEXIST, EINVAL, /* ??? */ EINVAL, /* Option negotiation failed. */ }; static int tftp_getnextblock(struct tftp_handle *h); /* send error message back. */ static void tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg) { struct { u_char header[HEADER_SIZE]; struct tftphdr t; u_char space[63]; /* +1 from t */ } __packed __aligned(4) wbuf; char *wtail; int len; len = strlen(msg); if (len > sizeof(wbuf.space)) len = sizeof(wbuf.space); wbuf.t.th_opcode = htons((u_short)ERROR); wbuf.t.th_code = htons(errcode); wtail = wbuf.t.th_msg; bcopy(msg, wtail, len); wtail[len] = '\0'; wtail += len + 1; sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t); } static void tftp_sendack(struct tftp_handle *h, u_short block) { struct { u_char header[HEADER_SIZE]; struct tftphdr t; } __packed __aligned(4) wbuf; char *wtail; wbuf.t.th_opcode = htons((u_short)ACK); wtail = (char *)&wbuf.t.th_block; wbuf.t.th_block = htons(block); wtail += 2; sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t); } static ssize_t recvtftp(struct iodesc *d, void **pkt, void **payload, time_t tleft, void *recv_extra) { struct tftprecv_extra *extra; struct tftp_handle *h; struct tftphdr *t; void *ptr = NULL; ssize_t len; errno = 0; extra = recv_extra; h = extra->tftp_handle; len = readudp(d, &ptr, (void **)&t, tleft); if (len < 4) { free(ptr); return (-1); } extra->rtype = ntohs(t->th_opcode); switch (ntohs(t->th_opcode)) { case DATA: { int got; if (htons(t->th_block) < (u_short)d->xid) { /* * Apparently our ACK was missed, re-send. */ tftp_sendack(h, htons(t->th_block)); free(ptr); return (-1); } if (htons(t->th_block) != (u_short)d->xid) { /* * Packet from the future, drop this. */ free(ptr); return (-1); } if (d->xid == 1) { /* * First data packet from new port. */ struct udphdr *uh; uh = (struct udphdr *)t - 1; d->destport = uh->uh_sport; } got = len - (t->th_data - (char *)t); *pkt = ptr; *payload = t; return (got); } case ERROR: if ((unsigned)ntohs(t->th_code) > TFTP_MAX_ERRCODE) { printf("illegal tftp error %d\n", ntohs(t->th_code)); errno = EIO; } else { #ifdef TFTP_DEBUG printf("tftp-error %d\n", ntohs(t->th_code)); #endif errno = tftperrors[ntohs(t->th_code)]; } free(ptr); return (-1); case OACK: { struct udphdr *uh; int tftp_oack_len; /* * Unexpected OACK. TFTP transfer already in progress. * Drop the pkt. */ if (d->xid != 1) { free(ptr); return (-1); } /* * Remember which port this OACK came from, because we need * to send the ACK or errors back to it. */ uh = (struct udphdr *)t - 1; d->destport = uh->uh_sport; /* Parse options ACK-ed by the server. */ tftp_oack_len = len - sizeof(t->th_opcode); if (tftp_parse_oack(h, t->th_u.tu_stuff, tftp_oack_len) != 0) { tftp_senderr(h, EOPTNEG, "Malformed OACK"); errno = EIO; free(ptr); return (-1); } *pkt = ptr; *payload = t; return (0); } default: #ifdef TFTP_DEBUG printf("tftp type %d not handled\n", ntohs(t->th_opcode)); #endif free(ptr); return (-1); } } /* send request, expect first block (or error) */ static int tftp_makereq(struct tftp_handle *h) { struct { u_char header[HEADER_SIZE]; struct tftphdr t; u_char space[FNAME_SIZE + 6]; } __packed __aligned(4) wbuf; struct tftprecv_extra recv_extra; char *wtail; int l; ssize_t res; void *pkt; struct tftphdr *t; char *tftp_blksize = NULL; int blksize_l; /* * Allow overriding default TFTP block size by setting * a tftp.blksize environment variable. */ if ((tftp_blksize = getenv("tftp.blksize")) != NULL) { tftp_set_blksize(h, tftp_blksize); } wbuf.t.th_opcode = htons((u_short)RRQ); wtail = wbuf.t.th_stuff; l = strlen(h->path); #ifdef TFTP_PREPEND_PATH if (l > FNAME_SIZE - (sizeof(TFTP_PREPEND_PATH) - 1)) return (ENAMETOOLONG); bcopy(TFTP_PREPEND_PATH, wtail, sizeof(TFTP_PREPEND_PATH) - 1); wtail += sizeof(TFTP_PREPEND_PATH) - 1; #else if (l > FNAME_SIZE) return (ENAMETOOLONG); #endif bcopy(h->path, wtail, l + 1); wtail += l + 1; bcopy("octet", wtail, 6); wtail += 6; bcopy("blksize", wtail, 8); wtail += 8; blksize_l = sprintf(wtail, "%d", h->tftp_blksize); wtail += blksize_l + 1; bcopy("tsize", wtail, 6); wtail += 6; bcopy("0", wtail, 2); wtail += 2; h->iodesc->myport = htons(tftpport + (getsecs() & 0x3ff)); h->iodesc->destport = htons(IPPORT_TFTP); h->iodesc->xid = 1; /* expected block */ h->currblock = 0; h->islastblock = 0; h->validsize = 0; pkt = NULL; recv_extra.tftp_handle = h; res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t, &recvtftp, &pkt, (void **)&t, &recv_extra); if (res == -1) { free(pkt); return (errno); } free(h->pkt); h->pkt = pkt; h->tftp_hdr = t; if (recv_extra.rtype == OACK) return (tftp_getnextblock(h)); /* Server ignored our blksize request, revert to TFTP default. */ h->tftp_blksize = SEGSIZE; switch (recv_extra.rtype) { case DATA: { h->currblock = 1; h->validsize = res; h->islastblock = 0; if (res < h->tftp_blksize) { h->islastblock = 1; /* very short file */ tftp_sendack(h, h->currblock); } return (0); } case ERROR: default: return (errno); } } /* ack block, expect next */ static int tftp_getnextblock(struct tftp_handle *h) { struct { u_char header[HEADER_SIZE]; struct tftphdr t; } __packed __aligned(4) wbuf; struct tftprecv_extra recv_extra; char *wtail; int res; void *pkt; struct tftphdr *t; wbuf.t.th_opcode = htons((u_short)ACK); wtail = (char *)&wbuf.t.th_block; wbuf.t.th_block = htons((u_short)h->currblock); wtail += 2; h->iodesc->xid = h->currblock + 1; /* expected block */ pkt = NULL; recv_extra.tftp_handle = h; res = sendrecv(h->iodesc, &sendudp, &wbuf.t, wtail - (char *)&wbuf.t, &recvtftp, &pkt, (void **)&t, &recv_extra); if (res == -1) { /* 0 is OK! */ free(pkt); return (errno); } free(h->pkt); h->pkt = pkt; h->tftp_hdr = t; h->currblock++; h->validsize = res; if (res < h->tftp_blksize) h->islastblock = 1; /* EOF */ if (h->islastblock == 1) { /* Send an ACK for the last block */ wbuf.t.th_block = htons((u_short)h->currblock); sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t); } return (0); } static int tftp_open(const char *path, struct open_file *f) { struct tftp_handle *tftpfile; struct iodesc *io; int res; size_t pathsize; const char *extraslash; if (netproto != NET_TFTP) return (EINVAL); if (f->f_dev->dv_type != DEVT_NET) return (EINVAL); if (is_open) return (EBUSY); tftpfile = calloc(1, sizeof(*tftpfile)); if (!tftpfile) return (ENOMEM); tftpfile->tftp_blksize = TFTP_REQUESTED_BLKSIZE; tftpfile->iodesc = io = socktodesc(*(int *)(f->f_devdata)); if (io == NULL) { free(tftpfile); return (EINVAL); } io->destip = servip; tftpfile->off = 0; pathsize = (strlen(rootpath) + 1 + strlen(path) + 1) * sizeof(char); tftpfile->path = malloc(pathsize); if (tftpfile->path == NULL) { free(tftpfile); return (ENOMEM); } if (rootpath[strlen(rootpath) - 1] == '/' || path[0] == '/') extraslash = ""; else extraslash = "/"; res = snprintf(tftpfile->path, pathsize, "%s%s%s", rootpath, extraslash, path); if (res < 0 || res > pathsize) { free(tftpfile->path); free(tftpfile); return (ENOMEM); } res = tftp_makereq(tftpfile); if (res) { free(tftpfile->path); free(tftpfile->pkt); free(tftpfile); return (res); } f->f_fsdata = tftpfile; is_open = 1; return (0); } static int tftp_read(struct open_file *f, void *addr, size_t size, size_t *resid /* out */) { struct tftp_handle *tftpfile; size_t res; int rc; rc = 0; res = size; tftpfile = f->f_fsdata; /* Make sure we will not read past file end */ if (tftpfile->tftp_tsize > 0 && tftpfile->off + size > tftpfile->tftp_tsize) { size = tftpfile->tftp_tsize - tftpfile->off; } while (size > 0) { int needblock, count; twiddle(32); needblock = tftpfile->off / tftpfile->tftp_blksize + 1; if (tftpfile->currblock > needblock) { /* seek backwards */ tftp_senderr(tftpfile, 0, "No error: read aborted"); rc = tftp_makereq(tftpfile); if (rc != 0) break; } while (tftpfile->currblock < needblock) { rc = tftp_getnextblock(tftpfile); if (rc) { /* no answer */ #ifdef TFTP_DEBUG printf("tftp: read error\n"); #endif - return (rc); + if (tftpfile->tries > TFTP_TRIES) { + return (rc); + } else { + tftpfile->tries++; + tftp_makereq(tftpfile); + } } if (tftpfile->islastblock) break; } if (tftpfile->currblock == needblock) { int offinblock, inbuffer; offinblock = tftpfile->off % tftpfile->tftp_blksize; inbuffer = tftpfile->validsize - offinblock; if (inbuffer < 0) { #ifdef TFTP_DEBUG printf("tftp: invalid offset %d\n", tftpfile->off); #endif return (EINVAL); } count = (size < inbuffer ? size : inbuffer); bcopy(tftpfile->tftp_hdr->th_data + offinblock, addr, count); addr = (char *)addr + count; tftpfile->off += count; size -= count; res -= count; if ((tftpfile->islastblock) && (count == inbuffer)) break; /* EOF */ } else { #ifdef TFTP_DEBUG printf("tftp: block %d not found\n", needblock); #endif return (EINVAL); } } if (resid != NULL) *resid = res; return (rc); } static int tftp_close(struct open_file *f) { struct tftp_handle *tftpfile; tftpfile = f->f_fsdata; /* let it time out ... */ if (tftpfile) { free(tftpfile->path); free(tftpfile->pkt); free(tftpfile); } is_open = 0; return (0); } static int tftp_stat(struct open_file *f, struct stat *sb) { struct tftp_handle *tftpfile; tftpfile = f->f_fsdata; sb->st_mode = 0444 | S_IFREG; sb->st_nlink = 1; sb->st_uid = 0; sb->st_gid = 0; sb->st_size = tftpfile->tftp_tsize; return (0); } static off_t tftp_seek(struct open_file *f, off_t offset, int where) { struct tftp_handle *tftpfile; tftpfile = f->f_fsdata; switch (where) { case SEEK_SET: tftpfile->off = offset; break; case SEEK_CUR: tftpfile->off += offset; break; default: errno = EOFFSET; return (-1); } return (tftpfile->off); } static int tftp_set_blksize(struct tftp_handle *h, const char *str) { char *endptr; int new_blksize; int ret = 0; if (h == NULL || str == NULL) return (ret); new_blksize = (unsigned int)strtol(str, &endptr, 0); /* * Only accept blksize value if it is numeric. * RFC2348 specifies that acceptable values are 8-65464. * Let's choose a limit less than MAXRSPACE. */ if (*endptr == '\0' && new_blksize >= 8 && new_blksize <= TFTP_MAX_BLKSIZE) { h->tftp_blksize = new_blksize; ret = 1; } return (ret); } /* * In RFC2347, the TFTP Option Acknowledgement package (OACK) * is used to acknowledge a client's option negotiation request. * The format of an OACK packet is: * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+ * | opc | opt1 | 0 | value1 | 0 | optN | 0 | valueN | 0 | * +-------+---~~---+---+---~~---+---+---~~---+---+---~~---+---+ * * opc * The opcode field contains a 6, for Option Acknowledgment. * * opt1 * The first option acknowledgment, copied from the original * request. * * value1 * The acknowledged value associated with the first option. If * and how this value may differ from the original request is * detailed in the specification for the option. * * optN, valueN * The final option/value acknowledgment pair. */ static int tftp_parse_oack(struct tftp_handle *h, char *buf, size_t len) { /* * We parse the OACK strings into an array * of name-value pairs. */ char *tftp_options[128] = { 0 }; char *val = buf; int i = 0; int option_idx = 0; int blksize_is_set = 0; int tsize = 0; unsigned int orig_blksize; while (option_idx < 128 && i < len) { if (buf[i] == '\0') { if (&buf[i] > val) { tftp_options[option_idx] = val; val = &buf[i] + 1; ++option_idx; } } ++i; } /* Save the block size we requested for sanity check later. */ orig_blksize = h->tftp_blksize; /* * Parse individual TFTP options. * * "blksize" is specified in RFC2348. * * "tsize" is specified in RFC2349. */ for (i = 0; i < option_idx; i += 2) { if (strcasecmp(tftp_options[i], "blksize") == 0) { if (i + 1 < option_idx) blksize_is_set = tftp_set_blksize(h, tftp_options[i + 1]); } else if (strcasecmp(tftp_options[i], "tsize") == 0) { if (i + 1 < option_idx) tsize = strtol(tftp_options[i + 1], NULL, 10); if (tsize != 0) h->tftp_tsize = tsize; } else { /* * Do not allow any options we did not expect to be * ACKed. */ printf("unexpected tftp option '%s'\n", tftp_options[i]); return (-1); } } if (!blksize_is_set) { /* * If TFTP blksize was not set, try defaulting * to the legacy TFTP blksize of SEGSIZE(512) */ h->tftp_blksize = SEGSIZE; } else if (h->tftp_blksize > orig_blksize) { /* * Server should not be proposing block sizes that * exceed what we said we can handle. */ printf("unexpected blksize %u\n", h->tftp_blksize); return (-1); } #ifdef TFTP_DEBUG printf("tftp_blksize: %u\n", h->tftp_blksize); printf("tftp_tsize: %lu\n", h->tftp_tsize); #endif return (0); }