pax_global_header 0000666 0000000 0000000 00000000064 15263245305 0014517 g ustar 00root root 0000000 0000000 52 comment=f2d2b5d88ca3f329abe32f6366eae78a2ccb0ae7
tftp-hpa-7.2+20261013/ 0000775 0000000 0000000 00000000000 15263245305 0014004 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/.editorconfig 0000664 0000000 0000000 00000000236 15263245305 0016462 0 ustar 00root root 0000000 0000000 root = true
[*]
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
[{*.c,*.h}]
indent_style = space
indent_size = 4
tab_width = 8
tftp-hpa-7.2+20261013/.github/ 0000775 0000000 0000000 00000000000 15263245305 0015344 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/.github/copilot-instructions.md 0000664 0000000 0000000 00000011721 15263245305 0022103 0 ustar 00root root 0000000 0000000 # Copilot instructions
## Build, configure, and clean
This is a portable C project built with GNU make and Autoconf. The normal in-tree workflow is:
```sh
./configure
make
```
Use `./configure --help` for the complete option list. Important package-specific switches include:
```sh
./configure --without-tcpwrappers --without-remap --without-readline
./configure --disable-ipv6
./configure --enable-debug --enable-profiling --enable-lto --enable-sanitizer
./configure --enable-werror
```
Set `CC`, `CFLAGS`, `CPPFLAGS`, `LDFLAGS`, or `LIBS` on the `configure` command line when targeting a non-default compiler or dependency location. The default installation prefix is `/usr`; the client is installed under `bindir` and `in.tftpd` under `sbindir`. Packaging builds can use `make INSTALLROOT=/path install`.
Useful targets:
```sh
make # build lib, common, tftp, and tftpd
make SUB=tftp # build only selected top-level subdirectories
make clean
make distclean
make install
```
`configure` generates `config/MCONFIG` and `config/config.h`; the build also generates `version.h` and rendered man pages. Do not hand-edit generated files. If changing `configure.ac` or Autoconf macros, regenerate with `make autoconf` (or `./autogen.sh` as appropriate) and review generated changes.
## Tests
The available automated test is an integration smoke test for bidirectional transfers. Build first, then run:
```sh
./tests/test-tftp.sh ./tftpd/tftpd ./tftp/tftp
```
The optional third argument selects the UDP port, for example:
```sh
./tests/test-tftp.sh ./tftpd/tftpd ./tftp/tftp 6970
```
The script starts standalone `tftpd` on localhost, exercises downloads and uploads for text and binary files, compares the results, and cleans up temporary data. It accepts custom client/server paths; when omitted, it defaults to the binaries in this tree. There is no separate unit-test runner or per-case selector.
## Architecture
- `tftp/` contains the interactive and command-line TFTP client. `main.c` parses options and implements the command interface; `tftp.c` implements RRQ/WRQ transfer loops, retransmission handling, packet tracing, and netascii/octet file I/O.
- `tftpd/` contains the server daemon. `tftpd.c` handles request dispatch, option negotiation, privilege/security modes, logging, and per-transfer processing. `listen.c` and `recvfrom.c` handle listening sockets, local-address discovery, and platform-specific UDP behavior. `path.c` validates and canonicalizes requested paths. `remap.c` implements optional regex-based filename remapping.
- `common/` builds `libcommon.a`, shared by both programs. It provides buffered read-ahead/write-behind transfer I/O, timeout packet draining, address helpers, allocation wrappers, program-name handling, and the select/poll abstraction.
- `lib/` supplies portability fallbacks and compatibility routines selected by configure checks. `config/` contains Autoconf templates and generated configuration definitions. `autoconf/` contains project-specific Autoconf macros and helper scripts.
- The top-level `Makefile` delegates to the subdirectory Makefiles in dependency order: `lib` and `common` support both executables, then `tftp` and `tftpd` link against `common/libcommon.a`. `MRULES` provides the shared compilation and dependency rules.
The server supports both inetd-style invocation and standalone mode. Security-sensitive behavior is concentrated in `tftpd/path.c` and the access logic in `tftpd/tftpd.c`: secure/chroot mode, Unix-permission mode, file creation, user/group dropping, path restrictions, and optional remapping must remain consistent when changing request handling.
## Repository conventions
- Preserve the existing Autoconf portability model. Add platform-dependent behavior through configure checks/macros and generated `config/config.h` definitions rather than assuming a specific Unix API.
- Include `config.h` first in server/platform-sensitive sources where the existing files do so, and use the shared types/helpers in `common/tftpsubs.h` for socket addresses, packet sizing, allocation, and transfer buffering.
- Keep client and server protocol changes aligned: both implement TFTP packet framing, retransmission/synchronization, option negotiation, and netascii/octet semantics, while sharing buffering primitives from `common/`.
- TFTP packet buffers must account for negotiated block sizes (`MAX_SEGSIZE + 4`); do not reuse the client's smaller request buffer for full negotiated data packets.
- Preserve the project’s C style and portability constraints: four-space indentation in C, tabs at width eight where applicable, LF endings, and the existing SPDX header/copyright conventions. Use the compiler warning set configured by `configure.ac`; `--enable-werror` is available for stricter builds.
- Runtime and security changes should be checked against `README.security`, the relevant manual page source (`tftp/*.1.in` or `tftpd/*.8.in`), and the integration script. Remapping behavior and its rule syntax are daemon features, not client features.
tftp-hpa-7.2+20261013/.gitignore 0000664 0000000 0000000 00000000434 15263245305 0015775 0 ustar 00root root 0000000 0000000 /config/MCONFIG
/config/config.h
/config/config.h.in
/autoconf/aclocal.m4
/autoconf/clean.sh
/autoconf/helpers/
/autom4te.cache
/config.log
/config.status
/configure
/version.h
/tftp/tftp
/tftpd/tftpd
*.1
*.8
*.a
*.o
*.i
*.s
*.lib
*.obj
*.exe
*.dep
*~
\#*
.\#*
*.bak
*.pcap
*.pcap.gz
tftp-hpa-7.2+20261013/CHANGES 0000664 0000000 0000000 00000051603 15263245305 0015004 0 ustar 00root root 0000000 0000000 Changes in 7.3:
tftp: add --verbosity option to match tftpd, remove the
never-working option to --verbose (incorrectly implemented,
never worked.)
tests: add better controls for logging, tracing and verbosity.
tftpd: add example configuration files for systemd activation.
tftpd: allow logging to stdout as well as stderr.
tftpd: add --logfile option to send the log output to a
specific file.
tftpd: add --logformat option to allow logs sent to stdout,
stderr or a log file to have standard machine-readable <#>
priority level prefixes instead of human readable.
tftpd: keep the executable suffix (e.g. ".exe") when running
"make install" on a platform which uses suffixed executables.
Changes in 7.2:
tftpd: the server now only accepts 0 and 1 as valid values for
the "rollover" option. Earlier versions accepted any 16-bit
value, but together with the "windowsize" option this can
cause serious confusion and possibly break the protocol. As
there are no known users for this option that use any other
values than 0 and 1, simply constrain the valid range
accordingly.
tftpd: on Linux, if the server is started as root, or
otherwise privileged, it now drops any capabilities it no
longer needs, and deasserts any capabilities it is not
actively using. (Implementations for other operating systems
will be happily accepted.)
tftpd: supplementary groups are now initialized early, to
reduce the need to access naming services late.
tftpd: add an experimental TFTP "cookie" option to help a
client associate request and reply, and a server detect
duplicated request packets.
tftpd: adjust the level of some important server log messages.
tftpd: better checks for failure to drop permissions.
tftpd: fix running in standalone listening mode without an -a
(address) argument, or when an address argument contains a :
but no service name/port number.
tftpd: fix a serious bug in options negotiation, which could
cause an invalid block size to be returned to the client and
prevented the timeout options from working at all.
Changes in 7.1:
A C99 compiler and standard library are now required to build
tftp-hpa.
The --blocksize (-B) option to both the server and the client
can now be specified as "mtu" or "mtu-nnn" where nnn is a
number of additional bytes to reserve; this bases the maximum
block size on the MTU as obtained from the kernel (if
possible; otherwise the Ethernet MTU of 1500 is assumed.)
The tftp client will now reject reply packets received from an
address other than the targeted server. Use --unsafe (-U) to
override this behavior (required by some older TFTP servers
when multihomed.)
The tftp client now defaults to "--blocksize mtu --windowsize 64"
for better performance when the TFTP server supports these
options.
The tftp client now requests the "tsize" option from the
server and, if received, uses it to validate the length of the
received data file. Use the --no-tsize (-T) option to disable
this behavior.
The tftp client now has an option --no-options (-N) to disable
TFTP options entirely. No options will be requested from the
server. This is equivalent to
"--blocksize 512 --windowsize 1 --no-tsize".
The tftp client now defaults to octet (binary) mode.
The server now has an option --validate to force path name
validation even if --secure or --jail is used.
The server now has a --read-only option to unconditionally
refuse all write requests.
The server now has a --max-upload option to limit the maximum
size of a file accepted for upload.
If --create is specified, the server will now delete a failed
upload file.
If --create a specified, if the host operating system support
O_NOFOLLOW, the server will not permit a file to be written to
through a symbolic link.
Changes in 7.0:
The memory footprint of the server has been optimized,
reducing the burden of serving many clients.
The client adds mget and mput commands for unambiguous multi-file
transfers to or from a specified directory. Command help and
selection have also been reorganized for clearer interactive use.
Command-mode failures, including transfer timeouts and interrupts,
now return a nonzero exit status.
tftpd adds --jail as an alternative to --secure on Linux systems
with openat2(2). It confines file access without chrooting, so the
daemon can retain access to configuration files and /dev/log and
does not need to start as root.
A new --normalize[=none|root|path] option can be used to
transform pathnames to standard form without needing explicit
filename remapping rules. Normalization happens after filename
remapping, and --normalize=path with --path-prefix can provide
secure-like path restrictions without a chroot or a complete
remapping rules file.
The --map-test option is now available in builds without regular
expression remapping support, allowing filename normalization to be
tested.
tftpd now logs successful and failed transfers, and stderr logging
includes the process ID. Improve listener behavior for IPv6-only
sockets and ensure invalid path requests do not leak file
descriptors.
The client now sends the tsize option (if possible) unless
explicitly disabled by the user.
Changes in 6.1:
The client and server now use a shared transfer implementation,
improving consistency for block/window handling, retransmission,
option negotiation, rollover, and netascii/octet transfers.
Improve windowed-transfer recovery. Delayed, duplicate, and
out-of-order packets are processed instead of flushing the receive
queue, avoiding loss of valid acknowledgements.
The client now uses the daemon's exponential retransmission timeout
behavior, with a one-second initial timeout and six retry attempts.
Fix netascii transfers when a CR sequence spans a data-packet or
window boundary.
Client transfer statistics now report correct elapsed time and use
human-friendly byte and bit-rate units; use verbosity level 2 for
unscaled values.
tftpd's threaded transfer I/O is now optional. Configure with
--disable-threads for a build without pthread support.
Update project URLs to HTTPS and direct bug reports to GitHub.
Changes in 6.0:
*** IMPORTANT: See note about tcpwrappers below ***
The TFTP windowsize option (RFC 7440) is now supported. The
--windowsize and --window-bytes options to tftpd can be used
to limit the permitted window size.
If pthreads are available, tftpd now performs I/O in a
separate thread, to avoid transfer slowdowns due to I/O
bottlenecks.
Support for tcpwrappers has been dropped. Use kernel-level
firewalling if per-IP client access control is
desired. tcpwrappers has not been widely used for some time,
so this should only affect a small number of users in the
first place.
The --timeout option is now also supported when running
standalone.
The --pidfile option is now also supported when not running
standalone.
Fix the --stderr option with --secure.
Do not fail a transfer because the client requested unknown
options.
Add the --reject-all option to disable RFC 2347 option
negotiation completely.
The client now supports the blksize and windowsize options.
Add support for long command line options to the client.
Add interactive blocksize and windowsize commands to the client.
tftpd now supports multiple --address arguments to bind to
multiple addresses. Furthermore, if --address is given a
domain name that resolves to multiple addresses, tftpd will
bind to all those addresses.
tftpd can now use systemd socket activation with the
--systemd option. The service accepts the descriptors passed
by systemd and remains in the foreground; --address and
--systemd cannot be used together.
The default UDP service used for listeners without an explicit
port can now be overridden with --service, --port, or -S. The
--ports alias is also available for --port-range, and --chroot
is an alias for --secure.
tftpd now builds correctly when IPv6 support is disabled with
--disable-ipv6.
Improve validation of tftp -c commands: an empty or missing
command now fails with a usage error instead of entering
interactive mode or crashing. If -c is passed a single
argument, it is split into tokens as if it had been entered
from the interactive command line.
Improve diagnostics for invalid wildcard listener addresses.
Fix handling of jump labels in the rewrite file.
Handle binding to an address which has not yet been configured
on platforms which support it. This can avoid race conditions
during startup.
Various configure and make improvements (see ./configure --help).
Changes in 5.4:
*** Read the man page for important details ***
Much stricter validation of path names when operating in
non-chroot mode.
The remap engine now allows labels/jump targets for more
complex, multi-step rule processing.
The remap engine can now probe for the existence of a file.
New "gg" modifier to the "r" remapping rule.
Cleaner handling of restricted user namespaces on Linux.
Source code cleanups.
Add --enable-werror configure option.
Fix several security-relevant bugs in path validation
(tftpd/path.c): an uninitialized buffer read and a broken
path tokenizer could let a crafted or unlucky request bypass
path restrictions or crash the daemon.
Fix buffer overflows in the tftp client: an unbounded strcpy()
when building requests, an out-of-bounds write when putting
multiple files to a remote directory, and an unbounded write
into the interactive command-line argument array.
Fix an out-of-bounds read while scanning request fields in
tftpd, and an incorrect address family used when creating the
per-transfer socket on platforms without recvmsg().
Fix the --map-steps option, which rejected all valid numeric
arguments due to an inverted validity check.
Fix the \x remap macro returning the wrong substitution
length, which could corrupt or drop its expansion in remap
rules.
Fix synchnet() passing the wrong nfds argument to select(),
which silently disabled its protection against the Sorcerer's
Apprentice retransmit bug.
Fix tftpd failing to build/link on platforms lacking
recvmsg()/msghdr::msg_control support.
Fix several portability library bugs: a dup2() fallback with
incorrect semantics (removed as obsolete), a heap buffer
overflow and build failure in the getaddrinfo() fallback, a
build failure in the inet_ntop() fallback, a file descriptor
leak in daemon() on dup2() failure, and undefined pointer
arithmetic in getopt_long().
Add IPv6 support on MacOS X.
Fix groff formatting warnings in the tftp and tftpd man pages.
Changes in 5.3:
Allow separate IPv4 and IPv6 remapping rules.
Properly convert IPv6-mapped IPv4 addresses as IPv4 during
remapping.
Better detection of local addresses, trying to ensure that
the proper response address is used for a multihomed host.
Changes in 5.2:
Fix breakage on newer Linux when a single interface has
multiple IP addresses.
Changes in 5.1:
Add -P option to write a PID file. Patch by Ferenc Wagner.
Bounce the tftpd_log socket in standalone mode, in case the
tftpd_log daemon has been restarted. Patch by Ferenc Wagner.
Build fixes.
Fix handling of block number wraparound after a successful
options negotiation.
Fix a buffer overflow in option parsing.
Changes in 5.0:
Try to on platforms with getaddrinfo() without AI_ADDRCONFIG or
AI_CANONNAME.
Implement the "rollover" option, for clients which want block
number to rollover to anything other than zero.
Correctly disable PMTU in standalone mode. Patch by Florian
Lohoff.
Changes in 0.49:
Add IPv6 support. Patch by Karsten Keil.
Support systems with editline instead of readline.
Support long options in the server.
Changes in 0.48:
Unbreak -l -s in the server, which was broken in 0.47.
Changes in 0.47:
Add -L option to the server to run standalone without
detaching from the shell.
Parallel make fix.
Changes in 0.46:
Minor portability improvements.
Changes in 0.45:
Add -l (literal) option to the client, to override the special
treatment of the colon (:) character as a hostname separator.
Changes in 0.44:
Allow the client to specify a range of local port numbers,
just like the server can.
Fix sending SIGHUP to update the regular expression table.
Changes in 0.43:
Fix double-free error on ^c in client.
Try to deal with clients that send TFTP requests to broadcasts
(apparently some recent Sun boxes do this instead of using the
address told by DHCP. Bad Sun! Bad Sun!)
Portability fixes.
Changes in 0.42:
Try to disable path MTU discovery for TFTP connections (it's
useless anyway.)
Add a hack to allow the admin to specify a range of local port
numbers to use.
Fix local IP number handling on systems which present
IP_RECVDSTADDR in recvmsg().
Changes in 0.41:
Fix bug by which patterns of the form \U\1 weren't converted
correctly.
Changes in 0.40.1:
Solaris build fix.
Changes in 0.40:
Fix bug which would cause "r" remapping rules to be
incorrectly rejected.
Changes in 0.39:
Support Perl-style \U...\E and \L...\E, as well as allow
matching rules to be inverted (execute if rule *doesn't*
match.)
Fix a timeout bug.
Add an RPM spec file.
Changes in 0.38:
Portability fixes.
Changes in 0.37:
Fix a pathology where a client sending ACKs for the wrong
packet can prevent proper retransmission.
Changes in 0.36:
Portability fixes.
Changes in 0.35:
Add an option to control the maximum value of blksize
negotiated.
Removed workaround for obsolete Cygwin problem.
Don't use getopt() -- the -c option doesn't work correctly
since it depends on the ordering of arguments and options. It
is now possible to do:
tftp -m binary hostname -c get filename
This was previous possible by doing:
tftp -m binary -c get hostname:filename
... but it seemed that was counterintuitive to people.
Somewhat improved configure scripts.
Changes in 0.34:
Additional Solaris gcc compiler bug workarounds; these
actually make the code somewhat cleaner.
Changes in 0.33:
Even better error messages.
Work around a suspect Solaris gcc bug.
Configuration fix: readline needs termcap.
Support running the tftp client from the command line. For
example:
tftp -m binary -c get hostname:file
Changes in 0.32:
Better error messages; including the capability to send a
custom error message to the client when hitting an "a" rule in
a remapping table.
Changes in 0.31:
Put in a check to make sure xinetd (in particular) doesn't
pass us an IPv6 socket.
Fix some problems related to timeout negotiation.
Allow the user to set the default timeout speed.
Changes in 0.30:
(Hopefully) better timeout algorithm.
Add a "utimeout" option; like "timeout" but in microseconds.
Change the log level of client-side errors to LOG_WARNING.
autoconf portability improvements.
Minor bugfixes.
Changes in 0.29:
Posixly correctness.
Now compiles and runs on Win32 systems using Cygwin
(http://www.cygwin.com/).
().
Fixed a bug which could cause a standalone server to exit with
a "recvfrom: Interrupted system call" log message if signals
arrive at a particularly inopportune moment.
Fix a macro substitution bug (thanks to Richard Nyberg.)
Changes in 0.28:
Fix stupid one-liner bug which broke standalone mode (-l).
Changes in 0.27:
Make the Digital Unix 4.0F platform work again. Thanks to
Alan Sundell for helping out with this platform!
Make the AIX 4.3 platform work again. Thanks to Josef Siemes
for helping out with this platform!
Allow replacement patterns to include the IP address of the
requesting host (\i).
Allow relying on Unix permissions rather than o+r magic if the
-p option is specified. As part of this, set all groups if
initgroups() is specified on the platform.
Clean up race conditions inherited from the BSD source base.
Changes in 0.26:
Fix the configuration process so tftpd doesn't end up
depending on readline, which apparently could happen on some
platforms before.
Make parallel builds (make -j) work correctly.
Improve parsing of the "connect" command in the tftp client.
Add a -V option to both tftp and tftpd to print the version
number on stdout and immediately exit.
Add a -v option to tftp to start out in verbose mode.
Rewrite the man pages using standard "man" troff macros.
Enable the (limited) use of readline on systems which don't
have readline/history.h.
Support compiling under MacOS X with fink (see
). Thanks for Justin Hallett
and Eric Eslinger for their help in getting this working!
Changes in 0.25:
Fixed Sorcerer's Apprentice bug in both the client and the
server. These bugs were inherited from the original BSD code.
Changes in 0.24:
Fix bugs in both client and server dealing with block number
wraparound, usually manifesting themselves as failure to
handle files over 32 MB in size.
Officially make the client a part of the tftp-hpa project.
Changes in 0.23:
Correct memory overwrite bug in the tftp client when compiled
with readline.
Changes in 0.22:
Even more portability improvements: FreeBSD and
Tru64/Digital Unix.
Fix tsize option on systems on which off_t is "long long".
Support large files on systems which need _LARGE_FILE_BITS or
similar.
Some source cleanups; change to autoconf 2.52.
Add support for readline command-line editing in tftp.
Changes in 0.21:
Support running in standalone mode, without inetd.
Even more portability improvements. Now known to compile and
run on Linux, Solaris 5, 5.1, 6, 7 and 8, and AIX. Reports of
success or failure on other modern systems always appreciated.
Clean and modernize some really ugly old code.
Fix a potential illegal memory access when running in "totally
insecure mode" - no -s, no directories listed.
Changes in 0.20:
Portability improvements. Now known to compile and run on
Solaris 8.
Changes in 0.19:
Fork before performing tcpwrappers check.
Don't rely on nonstandard bsd_signal() function, instead
require that the platform has sigaction(). This is 2001,
after all. This may resolve some potential portability
problems.
Log a message if memory allocation fails, instead of dying
silently.
Clean up the main dispatch loop.
Use for exit codes, if it exists.
Add support for debugging remapping rulefiles; if logging with
-vvv tftpd will log all rules actions.
Correct the error code issued by an "abort" rule.
Changes in 0.18:
Support (almost) arbitrary filename remappings via regular
expression-based rulesets.
Added -v option for more verbose logging.
Changes in 0.17:
Add support for tcpwrapper checking (/etc/hosts.allow;
/etc/hosts.deny) in tftpd.
Compile correctly on glibc 2.1.2.
Add -u option to specify the user id to run as (default
"nobody".)
Operate in "daemon mode" as long as we keep getting requests.
This should speed up handling large amounts of requests at
once, as can happen when a client starts up, and avoids inetd
misconfiguration problems.
Changes in 0.16:
Correct massive lossage from 0.15: apparently 0.15 was based
on an out-of-date CVS repository, somehow.
Fix for ACKs in TFTP PUT; patch by Roger Venning.
Changes in 0.15:
If the operating system allows, try to obtain the local
address used for the request packet, and reply using the same
local IP address. Some embedded TFTP clients are (probably
incorrectly) picky about this.
Changes in 0.14:
Hacks to signal handling to avoid "zombie servers."
Changes in 0.13:
Added the non-standard option "blksize2". The "blksize"
option is limited in its usability, since TFTP is designed to
be implemented in a ROM, and ROM code might find it painful to
deal with packets that don't meet certain alignment
restrictions.
The "blksize2" option tells the server that the block size
must be a power of 2 to be usable to the client. The server
SHALL respond with a block size that is a power of two, up to
a maximum of 32768, or reject the option. Furthermore, the
server SHALL grant a block size that is no smaller than 512
bytes unless the client explicitly requested a smaller block
size. If the client request both options, the server MAY
accept one or the other, but not both. At some point I will
probably write up an IETF draft for this option.
General information on the tftp-hpa series:
The core software was taken from OpenBSD (CVS source as of
1999-09-21). I believe this was the most secure source base available
at the time I obtained this code, and it included support for the -s
and -c options.
The un-BSD-ized Makefiles and a lot of the configure macros were taken
from netkit-tftp-0.10 by David Holland; I also followed this example
and modernized the code style throughout.
Patches by Markus Gutschke and Gero Kuhlmann were the basis for the
option negotiation as well as the "blksize" and "tsize" option
support, although I made a fair amount of mostly stylistic changes to
their code.
Adding the -r option (disable a specific option), the "timeout"
option, converting to using autoconf for setup, and any additions
listed in the Changes list above, has all been my own code, as are any
bugs introduced in the merge.
tftp-hpa-7.2+20261013/INSTALL 0000664 0000000 0000000 00000022230 15263245305 0015034 0 ustar 00root root 0000000 0000000 Basic Installation
==================
These are generic installation instructions. See the file
INSTALL.tftp for specific install instructions for this package.
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, and a
file `config.log' containing compiler output (useful mainly for
debugging `configure').
It can also use an optional file (typically called `config.cache'
and enabled with `--cache-file=config.cache' or simply `-C') that saves
the results of its tests to speed up reconfiguring. (Caching is
disabled by default to prevent problems with accidental use of stale
cache files.)
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If you are using the cache, and at
some point `config.cache' contains results you don't want to keep, you
may remove or edit it.
The file `configure.ac' (or `configure.in') is used to create
`configure' by a program called `autoconf'. You only need
`configure.ac' if you want to change it or regenerate `configure' using
a newer version of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system. If you're
using `csh' on an old version of System V, you might need to type
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes awhile. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.
3. Optionally, type `make check' to run any self-tests that come with
the package.
4. Type `make install' to install the programs and any data files and
documentation.
5. You can remove the program binaries and object files from the
source code directory by typing `make clean'. To also remove the
files that `configure' created (so you can compile the package for
a different kind of computer), type `make distclean'. There is
also a `make maintainer-clean' target, but that is intended mainly
for the package's developers. If you use it, you may have to get
all sorts of other programs in order to regenerate files that came
with the distribution.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. Run `./configure --help'
for details on some of the pertinent environment variables.
You can give `configure' initial values for variables by setting
them in the environment. You can do that on the command line like this:
./configure CC=c99 CFLAGS=-O2 LIBS=-lposix
This package requires a compiler and C library with C99 support.
*Note Environment Variables::, for more details.
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you must use a version of `make' that
supports the `VPATH' variable, such as GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'.
If you have to use a `make' that does not support the `VPATH'
variable, you have to compile the package for one architecture at a time
in the source code directory. After you have installed the package for
one architecture, use `make distclean' before reconfiguring for another
architecture.
Installation Names
==================
By default, `make install' will install the package's files in
`/usr/local/bin', `/usr/local/man', etc. You can specify an
installation prefix other than `/usr/local' by giving `configure' the
option `--prefix=PATH'.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
give `configure' the option `--exec-prefix=PATH', the package will use
PATH as the prefix for installing programs and libraries.
Documentation and other data files will still use the regular prefix.
In addition, if you use an unusual directory layout you can give
options like `--bindir=PATH' to specify different values for particular
kinds of files. Run `configure --help' for a list of the directories
you can set and what kinds of files go in them.
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Optional Features
=================
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Specifying the System Type
==========================
There may be some features `configure' cannot figure out
automatically, but needs to determine by the type of host the package
will run on. Usually `configure' can figure that out, but if it prints
a message saying it cannot guess the host type, give it the
`--build=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name which has the form:
CPU-COMPANY-SYSTEM
where SYSTEM can have one of these forms:
OS
KERNEL-OS
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the host type.
If you are _building_ compiler tools for cross-compiling, you should
use the `--target=TYPE' option to select the type of system they will
produce code for.
If you want to _use_ a cross compiler, that generates code for a
platform different from the build platform, you should specify the host
platform (i.e., that on which the generated programs will eventually be
run) with `--host=TYPE'. In this case, you should also specify the
build platform with `--build=TYPE', because, in this case, it may not
be possible to guess the build platform (it sometimes involves
compiling and running simple test programs, and this can't be done if
the compiler is a cross compiler).
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Environment Variables
=====================
Variables not defined in a site shell script can be set in the
environment passed to configure. However, some packages may run
configure again during the build, and the customized values of these
variables may be lost. In order to avoid this problem, you should set
them in the `configure' command line, using `VAR=value'. For example:
./configure CC=/usr/local2/bin/gcc
will cause the specified gcc to be used as the C compiler (unless it is
overridden in the site shell script).
`configure' Invocation
======================
`configure' recognizes the following options to control how it
operates.
`--help'
`-h'
Print a summary of the options to `configure', and exit.
`--version'
`-V'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`--cache-file=FILE'
Enable the cache: use and save the results of the tests in FILE,
traditionally `config.cache'. FILE defaults to `/dev/null' to
disable caching.
`--config-cache'
`-C'
Alias for `--cache-file=config.cache'.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made. To
suppress all normal output, redirect it to `/dev/null' (any error
messages will still be shown).
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`configure' also accepts some other, not widely useful, options. Run
`configure --help' for more details.
tftp-hpa-7.2+20261013/INSTALL.tftp 0000664 0000000 0000000 00000002162 15263245305 0016012 0 ustar 00root root 0000000 0000000 Specific installation instructions
==================================
In addition to what is described in the INSTALL file, the following
specifics apply to the tftp-hpa package:
The tftp-hpa package supports the following options to ./configure:
--without-remap
Disables the use of regular-expression-based filename
remapping (the -m option to tftpd).
--without-readline
Disables the use of the readline command-line editing library
in the tftp client.
For additional options see ./configure --help.
The default prefix for the tftp-hpa package is /usr, with the tftp
client installing as /usr/bin/tftp and the tftpd server installing as
/usr/sbin/in.tftpd on most systems. This can be overridden by setting
--bindir and --sbindir.
"make install" supports specifying an INSTALLROOT, which points to
what will be the root of the filesystem at runtime; this is typically
used when preparing packages for package-management systems.
You almost certainly will need GNU make to build tftp-hpa. If you
don't already have it, you can find GNU make at:
ftp://ftp.gnu.org/pub/make/
or
ftp://mirrors.kernel.org/gnu/make/
tftp-hpa-7.2+20261013/LICENSES/ 0000775 0000000 0000000 00000000000 15263245305 0015211 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/LICENSES/BSD-3-Clause.txt 0000664 0000000 0000000 00000002714 15263245305 0017740 0 ustar 00root root 0000000 0000000 Copyright (c) {{YEAR}}, {{OWNER}}
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduqce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of {{the ORGANIZATION nor the names of its
contributors}} may be used to endorse or promote products derived from
this software without specific prior written permission.
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 HOLDER 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.
tftp-hpa-7.2+20261013/LICENSES/BSD-4-Clause-UC.txt 0000664 0000000 0000000 00000005543 15263245305 0020251 0 ustar 00root root 0000000 0000000 BSD-4-Clause (University of California-Specific)
Copyright 1983, 1990, 1993, 1994
The Regents of the University of California. 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 by the University of California,
Berkeley and its contributors.
4. Neither the name of the University nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
---- ---- ---- ----
Clause 3 made inoperative by:
July 22, 1999
To All Licensees, Distributors of Any Version of BSD:
As you know, certain of the Berkeley Software Distribution ("BSD")
source code files require that further distributions of products
containing all or portions of the software, acknowledge within their
advertising materials that such products contain software developed by
UC Berkeley and its contributors.
Specifically, the provision reads:
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors."
Effective immediately, licensees and distributors are no longer
required to include the acknowledgement within advertising
materials. Accordingly, the foregoing paragraph of those BSD Unix
files containing it is hereby deleted in its entirety.
William Hoskins
Director, Office of Technology Licensing
University of California, Berkeley
tftp-hpa-7.2+20261013/MRULES 0000664 0000000 0000000 00000001224 15263245305 0014735 0 ustar 00root root 0000000 0000000 # Standard compilation rules (don't use make builtins)
.SUFFIXES: .c .cc .o .s .S .i
# Always the default rule, make sure it gets listed first
all:
.c.o:
$(CC) $(CFLAGS) -c $<
.c.s:
$(CC) $(CFLAGS) -S -o $@ $<
.c.i:
$(CC) $(CFLAGS) -E -o $@ $<
.cc.o:
$(CXX) $(CXXFLAGS) -c $<
.cc.s:
$(CXX) $(CXXFLAGS) -S -o $@ $<
.cc.i:
$(CXX) $(CXXFLAGS) -E -o $@ $<
# Common clean patterns
clean_common:
-rm -f *.o *.obj *.dep *.exe *.a *.lib
distclean_common: clean
-rm -f *.bak *~ \#* \.#* *.orig *.rej
clean: clean_common
distclean: distclean_common
# Dependency output file pattern
DEPENDFILE = $@.dep
# Include any dependency files
-include *.dep
tftp-hpa-7.2+20261013/Makefile 0000664 0000000 0000000 00000003211 15263245305 0015441 0 ustar 00root root 0000000 0000000 # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 1999-2006 H. Peter Anvin
# Copyright (c) 2024 Intel Corporation; Author: H. Peter Anvin
# You can do "make SUB=blah" to make only a few, or edit here, or both
# You can also run make directly in the subdirs you want.
SUB = lib common tftp tftpd
%.build: config/MCONFIG config/config.h version.h
$(MAKE) -C $(patsubst %.build, %, $@)
%.install: config/MCONFIG config/config.h version.h
$(MAKE) -C $(patsubst %.install, %, $@) install
%.clean:
$(MAKE) -C $(patsubst %.clean, %, $@) clean
%.distclean:
$(MAKE) -C $(patsubst %.distclean, %, $@) distclean
all: config/MCONFIG $(patsubst %, %.build, $(SUB))
tftp.build: lib.build common.build
tftpd.build: lib.build common.build
install: config/MCONFIG $(patsubst %, %.install, $(SUB))
clean: localclean $(patsubst %, %.clean, $(SUB))
localclean:
rm -f version.h
distclean: localdistclean $(patsubst %, %.distclean, $(SUB))
localdistclean: localclean
rm -f config/MCONFIG config.status config.log config/config.h
rm -rf *.cache
spotless: distclean
rm -f configure config/config.h.in tftp.spec
autoconf: configure config/config.h.in
config: config/MCONFIG config/config.h
release:
$(MAKE) autoconf
$(MAKE) distclean
config/MCONFIG: configure config/MCONFIG.in config/config.h.in
if test -x config.status; then \
./config.status --recheck && ./config.status ; \
else \
./configure ; \
fi
config/config.h: config/MCONFIG
: Generated by side effect
configure: configure.ac
sh autogen.sh
config/config.h.in: configure
: Generated by side effect
version.h: version
echo \#define VERSION \"tftp-hpa `cat version`\" > version.h
tftp-hpa-7.2+20261013/README 0000664 0000000 0000000 00000001444 15263245305 0014667 0 ustar 00root root 0000000 0000000 This is tftp-hpa, a conglomerate of a number of versions of the BSD
TFTP code, changed around to port to a whole collection of operating
systems. The goal is to work on any reasonably modern Unix with
sockets.
The tftp-hpa series is maintained by H. Peter Anvin .
The latest version of this collection can be found at:
https://www.kernel.org/pub/software/network/tftp/
See the file CHANGES for a list of changes between versions.
Please see the INSTALL and INSTALL.tftp files for compilation and
installation instructions, and README.security for important security
information.
The development git tree can be found at:
https://git.kernel.org/pub/scm/network/tftp/tftp-hpa.git/
https://github.com/hpax/tftp-hpa
To report a bug, please file a Github issue at the above URL.
tftp-hpa-7.2+20261013/README.security 0000664 0000000 0000000 00000007522 15263245305 0016540 0 ustar 00root root 0000000 0000000 Starting in version 6.2, tftp-hpa has a --path-prefix option to
prepend a path string to the requested file *after* remapping and
filename validation. This may be used as an alternative to -s that
does not require the daemon to be run as root, but make sure that all
implications of this are understood, such as the consequences of
symbolic links.
The --normalize option can be used to add a slash to the beginning of the
client's requested path if the client did not include one already, and
to handle "." and ".." filename options.
On Linux systems with openat2(2), then new --jail option supports
functionality similar to --secure without requiring the daemon to run
as root.
=======================================
Starting in version 6.0, tftp-hpa no longer supports using tcpwrappers
for client permit/denial. If this is desired, use kernel-level
firewalling on the TFTP listen port.
As TFTP only uses the listen port for the request packet, the
performance cost is neglible, and far less than having tftpd search
the tcpwrapper configuration.
=======================================
Starting in version 0.27, tftp-hpa has the option of a "use Unix
permissions" mode. In this mode, tftpd can access any file accessible
by the tftpd effective user, specified via the -u option. This means
that files no longer need to be set to o+r or o+w.
If file creation is enabled (via the -c option), the -p option also
changes the default umask from 0 (anyone can read or write) to
"unchanged" (inherited from the calling process.) The -U option can
be used to override the default umask; this is recommended.
The sanest setup, from a security standpoint, for tftpd to run in is
probably the following:
1. Create a separate "tftpd" user and group only used for tftpd;
2. Have all your boot files in a single directory tree (usually called
/tftpboot).
3. Specify "-p -u tftpd -s /tftpboot" on the tftpd command line; if
you want clients to be able to create files use
"-p -c -U 002 -u tftpd -s /tftpboot" (replace 002 with whatever
umask is appropriate for your setup.)
When the -s (chroot) option is used, tftpd needs to be started as
root. On Linux (at least), restricted mount trees and socket
activation (via inetd or systemd) set up before tftpd is even started
can avoid the need to run as root at all.
=======================================
Starting in version 0.17, tftp-hpa operates in genuine "wait" mode,
which means that an in.tftpd process hangs around for some time after
the last service request has arrived. This speeds up servicing a
subsequent request, which apparently has been a problem in the past,
resulting in "request storms" as the client keeps retrying, resulting
in multiple connections on the server which the client has already
abandoned.
This also means that spawning tftp via tcpd is useless (in fact, this
indirection seems to be part of the reason for these "request
storms.") Instead, tftp-hpa supports calling the tcpwrapper library
directly. Thus, if your /etc/inetd.conf looks like this (all on one
line):
tftp dgram udp wait root /usr/sbin/tcpd
/usr/sbin/in.tftpd -s /tftpboot -r blksize
... it's better to change to ...
tftp dgram udp wait root /usr/sbin/in.tftpd
in.tftpd -s /tftpboot -r blksize
You should make sure that you are using "wait" option in tftpd; you
also need to have tftpd spawned as root in order for chroot (-s) to
work. tftpd automatically drops privilege and changes user ID to
"nobody" by default; the appropriate user ID for tftpd can be
specified with the -u option (e.g. "-u tftpuser").
If you are running a busy boot server, I would suggest to instead use
kernel-based firewalling rules, and to compile tftpd without
tcpwrapper support, in order to provide significantly better
performance. To do so, specify the --without-tcpwrappers option to
configure when compiling; see the INSTALL.tftp file for more information.
tftp-hpa-7.2+20261013/autoconf/ 0000775 0000000 0000000 00000000000 15263245305 0015622 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/autoconf/m4/ 0000775 0000000 0000000 00000000000 15263245305 0016142 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/autoconf/m4/pa_add_cflags.m4 0000664 0000000 0000000 00000001030 15263245305 0021125 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ADD_CFLAGS(flag [,actual_flag [,success [,failure]]]])
dnl
dnl Attempt to add the given option to xFLAGS, if it doesn't break
dnl compilation. If the option to be tested is different than the
dnl option that should actually be added, add the option to be
dnl actually added as a second argument.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ADD_CFLAGS], [PA_ADD_FLAGS(CFLAGS, [$1], [$2], [$3], [$4])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_add_flags.m4 0000664 0000000 0000000 00000003023 15263245305 0020766 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ADD_FLAGS(flagvar, flags [,actual_flags [,success [,failure]]]])
dnl
dnl Add [flags] or [actual_flags] to the variable [flagvar] if and only
dnl if it is accepted by all languages previously seen in the script
dnl that are affected by [flagvar].
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ADD_FLAGS],
[ AS_VAR_PUSHDEF([old],[PA_SHSYM([_$0_$1_orig])])
AS_VAR_PUSHDEF([flags], [$1])
AS_VAR_PUSHDEF([cache],[PA_SHSYM([pa_cv_$1_$2])])
AS_VAR_COPY([old],[flags])
AC_CACHE_VAL([cache],
[AS_VAR_APPEND([flags],[' $2'])
AS_VAR_SET([cache],[yes])
PA_LANG_FOREACH([PA_FLAGS_LANGLIST($1)],
[AS_VAR_IF([cache],[yes],
[AC_MSG_CHECKING([whether $]_AC_CC[ accepts $2])
m4_case([$1],
[LDFLAGS],
[AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],
[],[AS_VAR_SET([cache],[no])])],
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]],[[]])],
[],[AS_VAR_SET([cache],[no])])])
AC_MSG_RESULT([$cache])
])])
AS_VAR_COPY([flags],[old])
])
AS_VAR_IF([cache],[yes],
[m4_define([_pa_add_flags_newflags],[m4_default([$3],[$2])])dnl
AS_VAR_APPEND([flags],[' _pa_add_flags_newflags'])
m4_foreach_w([_pa_add_flags_flag],[_pa_add_flags_newflags],
[AC_DEFINE(PA_SYM([$1_]_pa_add_flags_flag), 1,
[Define to 1 if compiled with ]_pa_add_flags_flag[ in $1])])
$4],[$5])
AS_VAR_POPDEF([cache])
AS_VAR_POPDEF([flags])
AS_VAR_POPDEF([old])
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_add_headers.m4 0000664 0000000 0000000 00000000770 15263245305 0021313 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ADD_HEADERS(headers...)
dnl
dnl Call AC_CHECK_HEADERS_ONCE(), and add to ac_includes_default if found
dnl --------------------------------------------------------------------------
AC_DEFUN([_PA_ADD_HEADER],
[AC_CHECK_HEADERS_ONCE([$1])
AS_IF([test "x$]PA_SHSYM([ac_cv_header_$1])[" = xyes],
[ac_includes_default="$ac_includes_default
#include <$1>"
])
])
AC_DEFUN([PA_ADD_HEADERS],[m4_map_args([_PA_ADD_HEADER],$@)])
tftp-hpa-7.2+20261013/autoconf/m4/pa_add_langflags.m4 0000664 0000000 0000000 00000000660 15263245305 0021634 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ADD_LANGFLAGS(flag...)
dnl
dnl Attempt to add the first accepted option in the given list to each
dnl compiler flags (CFLAGS, CXXFLAGS, ...).
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ADD_LANGFLAGS],
[PA_LANG_FOREACH(PA_LANG_HAVE_FLAGVAR_LIST,
[PA_FIND_FLAGS(m4_quote(PA_LANG_FLAGVAR),[$@])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_add_ldflags.m4 0000664 0000000 0000000 00000001045 15263245305 0021310 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ADD_LDFLAGS(variable, flag [,actual_flag [,success [,failure]]]])
dnl
dnl Attempt to add the given option to xFLAGS, if it doesn't break
dnl compilation. If the option to be tested is different than the
dnl option that should actually be added, add the option to be
dnl actually added as a second argument.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ADD_LDFLAGS], [PA_ADD_FLAGS(LDFLAGS, [$1], [$2], [$3], [$4])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_arg_bool.m4 0000664 0000000 0000000 00000001616 15263245305 0020654 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ARG_BOOL(option,helptext,default,enabled_action,disabled_action)
dnl
dnl The last three arguments are optional; default can be yes or no.
dnl
dnl Simpler-to-use versions of AC_ARG_ENABLED, that include the
dnl test for $enableval and the AS_HELP_STRING definition. This is only
dnl to be used for boolean options.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ARG_BOOL],
[m4_pushdef([pa_default],m4_default(m4_normalize([$3]),[no]))
m4_pushdef([pa_option],m4_case(pa_default,[yes],[disable],[enable]))
AC_ARG_ENABLE([$1],
[AS_HELP_STRING([--]m4_defn([pa_option])[-$1],[$2])],
[pa_arg_bool_enableval="$enableval"],
[pa_arg_bool_enableval="]m4_defn([pa_default])["])
m4_popdef([pa_option], [pa_default])
AS_IF([test x"$pa_arg_bool_enableval" != xno], [$4], [$5])
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_arg_disabled.m4 0000664 0000000 0000000 00000000445 15263245305 0021467 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ARG_DISABLED(option,helptext,disabled_action,enabled_action)
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ARG_DISABLED],[PA_ARG_BOOL([$1],[$2],yes,[$4],[$3])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_arg_enabled.m4 0000664 0000000 0000000 00000000442 15263245305 0021307 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_ARG_ENABLED(option,helptext,enabled_action,disabled_action)
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_ARG_ENABLED],[PA_ARG_BOOL([$1],[$2],no,[$3],[$4])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_c_c99_check.m4 0000664 0000000 0000000 00000002226 15263245305 0021131 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_C_C99_CHECK
dnl
dnl Check for a C99 minimum compiler level support
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([_PA_C_C99],
[AC_CACHE_CHECK([if $CC supports C99],
[pa_cv_c_c99],
[AC_REQUIRE([AC_PROG_CC])
AC_BEFORE([AC_USE_SYSTEM_EXTENSIONS], [$0])
pa_cv_c_c99=no
AC_LINK_IFELSE([AC_LANG_SOURCE([[
#include
#include
#include
#include
const char print_format[] = "%"PRIuMAX"%"PRId16;
struct c99_flex_array {
unsigned long long llvalue;
int value;
char flex@<:@@:>@;
};
static inline bool
c99_supported(const uint16_t values[static 1], uintmax_t *restrict result)
{
*result = strtoumax("0", NULL, 10);
return values[0] == 0;
}
int
main(void)
{
uint16_t values[] = { [0] = 0 };
uintmax_t result;
return !c99_supported(values, &result);
}
]])],[pa_cv_c_c99=yes])])])
AC_DEFUN([PA_C_C99_CHECK],
[AC_REQUIRE([_PA_C_C99])
AS_IF([test x$pa_cv_c_c99 != xyes],
[AC_MSG_FAILURE([this package requires a C99 compiler and library])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_c_extension.m4 0000664 0000000 0000000 00000002170 15263245305 0021402 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_C_EXTENSION
dnl
dnl Test to see if "__extension__" exists, and define the macro "extension"
dnl accordingly, to flag extensions that are explicitly enabled under
dnl conditionals.
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([_PA_C_EXTENSION],
[AC_REQUIRE([AC_PROG_CC])
AC_BEFORE([AC_USE_SYSTEM_EXTENSIONS],[$0])
AC_CACHE_CHECK([if $CC has a way to flag standards extensions], [pa_cv_c_extension],
[pa_cv_c_extension=no
# This is written as a loop to make it easier to add other variants
for pa_extension_try in __extension__
do
AS_IF([test x$pa_cv_c_extension = xno],
[AC_COMPILE_IFELSE([AC_LANG_SOURCE([
$pa_extension_try unsigned long dummy;
])], [pa_cv_c_extension="$pa_extension_try"])])
done
])])
AC_DEFUN([PA_C_EXTENSION],
[AC_REQUIRE([_PA_C_EXTENSION])
AS_CASE([x$pa_cv_c_extension],
[xno], [pa_extension=""],
[*], [pa_extension="$pa_cv_c_extension"])
AC_DEFINE_UNQUOTED([extension], [$pa_extension],
[Define to a keyword to flag C standard extensions, or empty.])
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_c_noreturn.m4 0000664 0000000 0000000 00000002762 15263245305 0021251 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_C_NORETURN
dnl
dnl How to declare a noreturn function
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([_PA_C_NORETURN],
[AC_CACHE_CHECK([how $CC declares noreturn functions], [pa_cv_c_noreturn],
[AC_REQUIRE([AC_PROG_CC])
AC_BEFORE([AC_USE_SYSTEM_EXTENSIONS],[$0])
AC_REQUIRE([PA_FN_TRIM_WHITESPACE])
AC_REQUIRE([_PA_C_EXTENSION])
pa_cv_c_noreturn=no
for pa_noreturn_extension_try in "$pa_cv_c_extension" ""
do
AS_IF([test "x$pa_noreturn_extension_try" != xno],
[for pa_noreturn_try in ["[[$pa_noreturn_extension_try __noreturn__]]" \
"$pa_noreturn_extension_try _Noreturn" \
"__attribute__(($pa_noreturn_extension_try __noreturn__))" \
"$pa_noreturn_extension_try __declspec(noreturn)"]
do
AS_IF([test "x$pa_cv_c_noreturn" = xno],
[AC_COMPILE_IFELSE([AC_LANG_SOURCE([
AC_INCLUDES_DEFAULT
#define noreturn $pa_noreturn_try
noreturn void here(void);
noreturn void there(void);
noreturn void here(void)
{
while (1)
printf("Loop forever\n");
}
])],[pa_cv_c_noreturn=`pa_fn_trim_whitespace "$pa_noreturn_try"`])])
done
])
done])])
AC_DEFUN([PA_C_NORETURN],
[AC_REQUIRE([_PA_C_NORETURN])
AC_REQUIRE([PA_C_EXTENSION])
AS_IF([test "x$pa_cv_c_noreturn" = xno],
[pa_c_noreturn=""], [pa_c_noreturn="$pa_cv_c_noreturn"])
AC_DEFINE_UNQUOTED([noreturn], [$pa_c_noreturn],
[Define to the best way to declare noreturn functions on this compiler])
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_c_typeof.m4 0000664 0000000 0000000 00000001772 15263245305 0020703 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_C_TYPEOF
dnl
dnl Find if typeof() exists, or an equivalent (__typeof__, decltype,
dnl __decltype__)
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_C_TYPEOF],
[AC_CACHE_CHECK([if $CC supports typeof], [pa_cv_typeof],
[pa_cv_typeof=no
for pa_typeof_try in typeof __typeof __typeof__ decltype __decltype __decltype__ _Decltype
do
AS_IF([test $pa_cv_typeof = no],
[AC_COMPILE_IFELSE([AC_LANG_SOURCE([
AC_INCLUDES_DEFAULT
int testme(int x);
int testme(int x)
{
$pa_typeof_try(x) y = x*x;
return y;
}
])],
[pa_cv_typeof=$pa_typeof_try])])
done
])
AS_IF([test $pa_cv_typeof = no],
[],
[AC_DEFINE([HAVE_TYPEOF], 1,
[Define to 1 if you have some version of the typeof operator.])
AS_IF([test $pa_cv_typeof = typeof],
[],
[AC_DEFINE_UNQUOTED([typeof], [$pa_cv_typeof],
[Define if your typeof operator is not named `typeof'.])])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_cross_compile.m4 0000664 0000000 0000000 00000002377 15263245305 0021736 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_CROSS_COMPILE
dnl
dnl Get the canonical name for the build and host (runtime) systems;
dnl then figure out if this is cross-compilation. Specifically, this
dnl disables invoking WINE on non-Windows systems which are configured
dnl to run WINE automatically.
dnl
dnl Use PA_CROSS_COMPILE_TOOL if the target system (output of a code-
dnl generation tool) is applicable.
dnl
dnl This doesn't explicitly print any messages as that is automatically
dnl done elsewhere.
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([PA_CROSS_COMPILE],
[
AC_BEFORE([$0], [AC_LANG_COMPILER])
AC_BEFORE([$0], [AC_LANG])
AC_BEFORE([$0], [AC_PROG_CC])
AC_BEFORE([$0], [AC_PROG_CPP])
AC_BEFORE([$0], [AC_PROG_CXX])
AC_BEFORE([$0], [AC_PROG_CXXCPP])
AC_BEFORE([$0], [AC_PROG_OBJC])
AC_BEFORE([$0], [AC_PROG_OBJCPP])
AC_BEFORE([$0], [AC_PROG_OBJCXX])
AC_BEFORE([$0], [AC_PROG_OBJCXXCPP])
AC_BEFORE([$0], [AC_PROG_F77])
AC_BEFORE([$0], [AC_PROG_FC])
AC_BEFORE([$0], [AC_PROG_GO])
# Disable WINE
WINELOADER=/dev/null
export WINELOADER
WINESERVER=/dev/null
export WINESERVER
WINEPREFIX=/dev/null
export WINEPREFIX
AC_CANONICAL_BUILD
AC_CANONICAL_HOST
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_csym.m4 0000664 0000000 0000000 00000001145 15263245305 0020040 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_CSYM(prefix, string)
dnl
dnl Convert a (semi-) arbitrary string to a CPP symbol
dnl Convert non-C characters to underscore, except + which is converted
dnl to X (so C++ -> CXX). Unlike PA_SYM(), do not compact multiple
dnl underscores.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_CSYM],
[m4_bpatsubsts(m4_quote(m4_toupper(m4_normalize([$*]))),
[[ ]+],[],[\+],[X],[^\(.\)\([0123456789].*\)$],[[[\1_\2]]],
[[^ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]],[_],
[^._\(.*\)_.$],[[[\1]]])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_depend.m4 0000664 0000000 0000000 00000001300 15263245305 0020315 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_DEPEND
dnl
dnl Add a dependency generation pattern to each langflag that is
dnl supported. DEPENDFILE should be set in the Makefile to the
dnl desired pattern for the dependency file name.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_DEPEND],
[
dnl This is super ugly: during autoconf this will create a file
dnl literally named ${DEPENDFILE}, but it does get expanded during make.
dnl The DEPENDFILE setting below only affects the output message.
DEPENDFILE=file.dep
PA_ADD_LANGFLAGS([-MMD -MF ${DEPENDFILE}],[-MD -MF ${DEPENDFILE}])
rm -f '${DEPENDFILE}'
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_find_flags.m4 0000664 0000000 0000000 00000001123 15263245305 0021155 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_FIND_FLAGS(flagvar, flags_list)
dnl
dnl Add the first set of flags in flags_list that is accepted by
dnl by all languages affected by [flagvar], if those languages have
dnl been previously seen in the script.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_FIND_FLAGS],
[_pa_find_flags_done=no
m4_foreach([_pa_find_flags_flag],[$2],
[
AS_IF([test x$_pa_find_flags_done != xyes],
[PA_ADD_FLAGS([$1],m4_quote(_pa_find_flags_flag),,[_pa_find_flags_done=yes])])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_flags_langlist.m4 0000664 0000000 0000000 00000001342 15263245305 0022055 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_FLAGS_LANGLIST(flagvar)
dnl
dnl Return a list of languages affected by the variable flagvar.
dnl If flagvar is unknown, assume it affects the current language.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_FLAGS_LANGLIST],
[m4_case([$1],
[CPPFLAGS], [[C],[C++],[Objective C],[Objective C++]],
[CFLAGS], [[C]],
[CXXFLAGS], [[C++]],
[FFLAGS], [[Fortran 77]],
[FCFLAGS], [[Fortran]],
[ERLCFLAGS], [[Erlang]],
[OBJCFLAGS], [[Objective C]],
[OBJCXXFLAGS], [[Objective C++]],
[GOFLAGS], [[Go]],
[LDFLAGS], [[C],[C++],[Fortran 77],[Fortran],[Objective C],[Objective C++],[Go]],
m4_quote(_AC_LANG))])
tftp-hpa-7.2+20261013/autoconf/m4/pa_fn_trim_whitespace.m4 0000664 0000000 0000000 00000000613 15263245305 0022736 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_FN_TRIM_WHITESPACE
dnl
dnl A shell function to trim whilespace from a list of arguments
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([PA_FN_TRIM_WHITESPACE],
[pa_fn_trim_whitespace ()
{
printf "%s\n" "[$]*" | sed '
s/ / /g
s/^ *//
s/ *$//
s/ */ /g
'
}])
tftp-hpa-7.2+20261013/autoconf/m4/pa_lang_flagvar.m4 0000664 0000000 0000000 00000001437 15263245305 0021514 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_LANG_FLAGVAR([language])
dnl
dnl Return the name of the compiler flag variable for the current or
dnl specified language. Returns empty if the variable name is not known.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_LANG_FLAGVAR],
[m4_case(m4_quote(m4_default([$1],m4_quote(_AC_LANG))),
[C], [CFLAGS],
[C++], [CXXFLAGS],
[Fortran 77], [FFLAGS],
[Fortran], [FCFLAGS],
[Erlang], [ERLCFLAGS],
[Objective C], [OBJCFLAGS],
[Objective C++], [OBJCXXFLAGS],
[Go], [GOFLAGS],
[m4_fatal([PA_LANG_FLAGVAR: Unknown language: $1])])])
AC_DEFUN([PA_LANG_HAVE_FLAGVAR_LIST],
[[[C], [C++], [Fortran 77], [Fortran], [Erlang],
[Objective C], [Objective C++], [Go]]])
tftp-hpa-7.2+20261013/autoconf/m4/pa_lang_foreach.m4 0000664 0000000 0000000 00000001167 15263245305 0021501 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_LANG_FOREACH(subset, body)
dnl
dnl Expand [body] for each language encountered in the configure script also
dnl present in [subset], or all if [subset] is empty
dnl --------------------------------------------------------------------------
AC_DEFUN([_PA_LANG_FOREACH],
[m4_pushdef([pa_lang_for_each])dnl
m4_foreach([pa_lang_for_each],$1,[dnl
AC_LANG_PUSH(pa_lang_for_each)
$2
AC_LANG_POP(pa_lang_for_each)
])dnl
m4_popdef([pa_lang_for_each])])
AC_DEFUN([PA_LANG_FOREACH],
[_PA_LANG_FOREACH(m4_dquote(PA_LANG_SEEN_LIST(m4_dquote($1))),[$2])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_lang_seen_list.m4 0000664 0000000 0000000 00000001416 15263245305 0022054 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_LANG_SEEN_LIST(subset)
dnl
dnl List of the language lang has been used in the configuration
dnl script so far, possibly subset by [subset].
dnl
dnl This relies on overriding _AC_LANG_SET(from, to),
dnl the internal implementation of _AC_LANG.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_LANG_SEEN_LIST],
[m4_ifblank([$1],
[m4_define([_pa_lang_seen_list_out],m4_dquote(m4_set_list(PA_LANG_SEEN_SET)))],
[m4_set_delete([_pa_lang_seen_subset])dnl
m4_set_add_all([_pa_lang_seen_subset],$1)dnl
m4_define([_pa_lang_seen_list_out],m4_dquote(m4_cdr(m4_set_intersection([_pa_lang_seen_subset],PA_LANG_SEEN_SET))))dnl
m4_dquote(_pa_lang_seen_list_out)])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_lang_seen_set.m4 0000664 0000000 0000000 00000001366 15263245305 0021700 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_LANG_SEEN_SET
dnl
dnl Set of the languages that have been used in the configuration.
dnl
dnl This relies on overriding _AC_LANG_SET(from, to),
dnl the internal implementation of _AC_LANG.
dnl
dnl The very first language transition [] -> [C] is ignored, because
dnl it is done from AC_INIT regardless of any user specified language.
dnl --------------------------------------------------------------------------
m4_ifndef([_PA_LANG_SET],
[m4_rename([_AC_LANG_SET], [_PA_LANG_SET])
m4_set_delete([_pa_lang_seen_set])
m4_defun([_AC_LANG_SET],
[m4_ifnblank([$1],[m4_set_add([_pa_lang_seen_set],[$2])])_PA_LANG_SET($@)])])
AC_DEFUN([PA_LANG_SEEN_SET],[[_pa_lang_seen_set]])
tftp-hpa-7.2+20261013/autoconf/m4/pa_option_debug.m4 0000664 0000000 0000000 00000001100 15263245305 0021532 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_OPTION_DEBUG(with_debug, without_debug)
dnl
dnl Set debug flags and optimization flags depending on if
dnl --enable-debug is set or not. Some flags are set regardless...
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_OPTION_DEBUG],
[PA_ADD_LANGFLAGS([-g3])
PA_ARG_DISABLED([gdb], [disable gdb debug extensions],,
[PA_ADD_LANGFLAGS([-ggdb])])
PA_ARG_ENABLED([debug], [optimize for debugging],
[PA_ADD_LANGFLAGS([-Og],[-O0])
$1],
[$2])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_option_gc.m4 0000664 0000000 0000000 00000001053 15263245305 0021044 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_OPTION_GC
dnl
dnl Option to compile with garbage collection; currently only supports
dnl gcc/ELF. Enabled by default.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_OPTION_GC],
[PA_ARG_DISABLED([gc],
[do not compile with dead code garbage collection support],
[],
[PA_ADD_LDFLAGS([-Wl,--as-needed])
PA_ADD_LANGFLAGS([-ffunction-sections])
PA_ADD_LANGFLAGS([-fdata-sections])
PA_ADD_LDFLAGS([-Wl,--gc-sections])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_option_lto.m4 0000664 0000000 0000000 00000002357 15263245305 0021261 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_OPTION_LTO(default)
dnl
dnl Try to enable link-time optimization. Enable it by default if
dnl the "default" argument is set to "yes"; currently the default is "no",
dnl but that could change in the future -- to force disabled by default,
dnl set to "no".
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_OPTION_LTO],
[
dnl Careful here: AR or RANLIB may already have already been probed for.
dnl If not, do it now to prevent it from getting down further down.
dnl Do it unconditionally to avoid inconsistent behavior with or
dnl without --enable-lto.
AS_IF([test -z "$AR"], [AC_CHECK_TOOL(AR, ar)])
AS_IF([test -z "$RANLIB"], [AC_CHECK_TOOL(RANLIB, ranlib, :)])
PA_ARG_BOOL([lto],
[Try to enable link-time optimization for this compiler],
[m4_default([$1],[no])],
[PA_FIND_FLAGS([-flto=auto],[-flto])
PA_FIND_FLAGS([-ffat-lto-objects])
PA_FIND_FLAGS([-fuse-linker-plugin])
dnl Add here if there are any other toolchains that need special magic
AS_IF([test x$ac_compiler_gnu = xyes],
[AC_CHECK_TOOL(CC_AR, gcc-ar)
AR="${CC_AR:-$AR}"
AC_CHECK_TOOL(CC_RANLIB, gcc-ranlib)
RANLIB="${CC_RANLIB:-$RANLIB}"])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_option_profiling.m4 0000664 0000000 0000000 00000000630 15263245305 0022444 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_OPTION_PROFILING(with_profiling, without_profiling)
dnl
dnl Try to enable profiling if --enable-profiling is set.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_OPTION_PROFILING],
[PA_ARG_ENABLED([profiling], [compile with profiling (-pg option)],
[PA_ADD_LANGFLAGS([-pg])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_option_sanitizer.m4 0000664 0000000 0000000 00000000720 15263245305 0022463 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_OPTION_SANITIZER
dnl
dnl Option to compile with sanitizers enabled.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_OPTION_SANITIZER],
[PA_ARG_ENABLED([sanitizer],
[compile with sanitizers enabled],
[PA_ADD_LANGFLAGS([-fno-omit-frame-pointer])
PA_ADD_LANGFLAGS([-fsanitize=address])
PA_ADD_LANGFLAGS([-fsanitize=undefined])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_prog_cc.m4 0000664 0000000 0000000 00000001375 15263245305 0020506 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_PROG_CC()
dnl
dnl Similar to AC_PROG_CC, but add a prototype for main() to
dnl AC_INCLUDES_DEFAULT to avoid -Werror from breaking compilation.
dnl (Very odd!)
dnl
dnl It can optionally take lists of CFLAGS to be added. For each argument,
dnl only the *first* flag accepted is added.
dnl
dnl BUG: this expands AC_CHECK_HEADERS_ONCE() before the flags get
dnl probed. Don't know yet how to fix that.
dnl --------------------------------------------------------------------------
AC_DEFUN_ONCE([PA_PROG_CC],
[AC_REQUIRE([AC_PROG_CC])
AC_USE_SYSTEM_EXTENSIONS
ac_includes_default="$ac_includes_default
#ifndef __cplusplus
extern int main(void);
#endif"
PA_FIND_FLAGS(CFLAGS,[$1])
])
tftp-hpa-7.2+20261013/autoconf/m4/pa_pthread.m4 0000664 0000000 0000000 00000001504 15263245305 0020513 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_PTHREAD
dnl
dnl Look for threads and define HAVE_PTHREAD if available, adding
dnl the appropriate options to *FLAGS.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_PTHREAD],
[AC_CHECK_HEADERS_ONCE([pthread.h])
AS_IF([test "x$ac_cv_header_pthread_h" = xyes],
[PA_ADD_LANGFLAGS([-pthread], [-pthreads])
AC_SEARCH_LIBS(pthread_create, [pthread pthreads])
AC_MSG_CHECKING([that POSIX threads work])
AC_LINK_IFELSE(
[AC_LANG_PROGRAM([[
#include
]],
[[pthread_t thread;
return pthread_create(&thread, NULL, NULL, NULL);]])],
[AC_MSG_RESULT([yes])
AC_DEFINE([HAVE_PTHREAD], 1,
[Define to 1 if your have working POSIX threads.])],
[AC_MSG_RESULT([no])])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_search_libs_and_add.m4 0000664 0000000 0000000 00000001124 15263245305 0022772 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_SEARCH_LIBS_AND_ADD
dnl
dnl PA_SEARCH_LIBS_AND_ADD(function, libraries [,function to add])
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_SEARCH_LIBS_AND_ADD],
[
AH_TEMPLATE(AS_TR_CPP(HAVE_$1), [Define if $1 function was found])
AC_SEARCH_LIBS($1, $2,
[
AC_DEFINE_UNQUOTED(AS_TR_CPP(HAVE_$1))
pa_add_$1=false;
],
[
XTRA=true;
if test $# -eq 3; then
AC_LIBOBJ($3)
else
AC_LIBOBJ($1)
fi
pa_add_$1=true;
])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_shsym.m4 0000664 0000000 0000000 00000001227 15263245305 0020231 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_SHSYM(...)
dnl
dnl Convert a (semi-) arbitrary string to a shell symbol
dnl Convert non-shell characters to underscores, except + which is converted
dnl to x (so C++ -> cxx). Unlike PA_SYM(), do not compact multiple
dnl underscores.
dnl
dnl This currently differs from PA_CSYM only in not doing case conversion.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_SHSYM],
[m4_bpatsubsts(m4_quote(m4_normalize([$*])),
[[ ]+],[],[\+],[x],[[^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]],[_],
[^._\(.*\)_.$],[[[\1]]])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_sigsetjmp.m4 0000664 0000000 0000000 00000001246 15263245305 0021074 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_SIGSETJMP
dnl
dnl Do we have sigsetjmp/siglongjmp? (AC_CHECK_FUNCS doesn't seem to work
dnl for these particular functions.)
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_SIGSETJMP],
[AC_MSG_CHECKING([for sigsetjmp])
AC_LINK_IFELSE([AC_LANG_SOURCE(
[
AC_INCLUDES_DEFAULT
#include
int main(void) {
sigjmp_buf buf;
if (sigsetjmp(buf,1))
return 0;
siglongjmp(buf,2);
return 1;
}
])],
[AC_MSG_RESULT([yes])
AC_DEFINE([HAVE_SIGSETJMP], 1,
[Define to 1 if your system has sigsetjmp/siglongjmp])],
[AC_MSG_RESULT([no])])])
tftp-hpa-7.2+20261013/autoconf/m4/pa_sym.m4 0000664 0000000 0000000 00000000732 15263245305 0017676 0 ustar 00root root 0000000 0000000 dnl --------------------------------------------------------------------------
dnl PA_SYM(prefix, string)
dnl
dnl Convert a (semi-) arbitrary string to a CPP symbol
dnl Compact underscores and convert non-C characters to underscore,
dnl except + which is converted to X (so C++ -> CXX).
dnl
dnl Contract multiple underscores together.
dnl --------------------------------------------------------------------------
AC_DEFUN([PA_SYM],[m4_bpatsubsts(PA_CSYM([$*]),[__+],[_])])
tftp-hpa-7.2+20261013/autogen.sh 0000775 0000000 0000000 00000005117 15263245305 0016011 0 ustar 00root root 0000000 0000000 #!/bin/sh -x
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2009-2024 Intel Corporation; Author: H. Peter Anvin
#
# Run this script to regenerate autoconf files
#
recheck=false
for arg; do
case x"$arg" in
x--recheck)
recheck=true
config=$(sh config.status --config 2>/dev/null)
;;
x--clearenv)
unset AUTOCONF AUTOMAKE ACLOCAL AUTOHEADER ACLOCAL_PATH
;;
*)
echo "$0: unknown option: $arg" 1>&2
;;
esac
done
# This allows for overriding the default autoconf programs
AUTOCONF="${AUTOCONF:-${AUTOTOOLS_PREFIX}autoconf}"
AUTOMAKE="${AUTOMAKE:-${AUTOTOOLS_PREFIX}automake}"
ACLOCAL="${ACLOCAL:-${AUTOTOOLS_PREFIX}aclocal}"
AUTOHEADER="${AUTOHEADER:-${AUTOTOOLS_PREFIX}autoheader}"
mkdir -p autoconf autoconf/helpers config
autolib="`"$AUTOMAKE" --print-libdir`"
if test ! x"$autolib" = x; then
for prg in install-sh compile config.guess config.sub; do
# Update autoconf helpers if and only if newer ones are available
if test -f "$autolib"/"$prg" && \
( set -e ; \
test -f autoconf/helpers/"$prg" && sed -n \
-e 's/^scriptver=/scriptversion=/' \
-e 's/^timestamp=/scriptversion=/' \
-e 's/^scriptversion=['\''"]?\([^'\''"]*\).*$/\1/p' \
"$autolib"/"$prg" autoconf/helpers/"$prg" | \
sort -c 2>/dev/null ; \
test $? -ne 0 )
then
cp -f "$autolib"/"$prg" autoconf/helpers
fi
done
fi
mv -f autoconf/aclocal.m4 autoconf/aclocal.m4.old
mkdir -p autoconf/m4.old autoconf/m4
mv -f autoconf/m4/*.m4 autoconf/m4.old/ 2>/dev/null || true
ACLOCAL_PATH="${ACLOCAL_PATH}${ACLOCAL_PATH:+:}`pwd`/autoconf/m4.old"
export ACLOCAL_PATH
"$ACLOCAL" --install --output=autoconf/aclocal.m4 -I autoconf/m4
if test ! -f autoconf/aclocal.m4; then
# aclocal failed, revert to previous files
mv -f autoconf/m4.old/*.m4 autoconf/m4/
mv -f autoconf/aclocal.m4.old autoconf/aclocal.m4
exit 1
fi
rm -rf autoconf/*m4.old
"$AUTOHEADER" -B autoconf
"$AUTOCONF" -B autoconf
(
echo '#!/bin/sh'
"$AUTOCONF" -B autoconf \
-t AC_CONFIG_HEADERS:'rm -f $*' \
-t AC_CONFIG_FILES:'rm -f $*'
echo 'rm -f config.log config.status'
echo 'rm -rf autom4te.cache'
) > autoconf/clean.sh
chmod +x autoconf/clean.sh
sh autoconf/clean.sh
rm -f configure~ || true
# Try to regenerate unconfig.h if Perl is available and unconfig.pl
# is present in the autoconf directory.
if [ -n "$(which perl)" -a -f autoconf/unconfig.pl ]; then
perl autoconf/unconfig.pl . config/config.h.in config/unconfig.h
fi
if $recheck; then
# This bizarre statement has to do with how config.status quotes its output
echo exec sh configure $config | sh -
fi
tftp-hpa-7.2+20261013/common/ 0000775 0000000 0000000 00000000000 15263245305 0015274 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/common/Makefile 0000664 0000000 0000000 00000001204 15263245305 0016731 0 ustar 00root root 0000000 0000000 # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2006 H. Peter Anvin
# Copyright (c) 2024-2026 Intel Corporation; Author: H. Peter Anvin
SRCROOT = ..
VERSION = $(shell cat ../version)
-include ../config/MCONFIG
include ../MRULES
OBJS = tftpsubs.$(O) tftp-xfer.$(O) tftp-io.$(O) signal.$(O) \
xalloc.$(O) xasprintf.$(O) progname.$(O) pollset.$(O) \
clock.$(O) address.$(O) random.$(O) error.$(O) parsenum.$(O)
LIB = libcommon.a
all: $(LIB)
$(LIB): $(OBJS)
-rm -f $(LIB)
$(AR) $(LIB) $(OBJS)
$(RANLIB) $(LIB)
$(OBJS): tftpsubs.h
tftp-xfer.$(O): tftp-xfer.h
tftp-io.$(O): tftp-io.h tftp-xfer.h
install:
clean:
rm -f $(LIB)
tftp-hpa-7.2+20261013/common/address.c 0000664 0000000 0000000 00000003507 15263245305 0017072 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2026 H. Peter Anvin
*/
#include "config.h"
#include "tftpsubs.h"
/*
* Returns a constant string for the socket family
*/
const char *net_family(sa_family_t ai_fam)
{
switch (ai_fam) {
case AF_INET:
return "IPv4 ";
#ifdef HAVE_IPV6
case AF_INET6:
return "IPv6 ";
#endif
#ifdef AF_UNIX
case AF_UNIX:
return "Unix";
#endif
#ifdef AF_UNSPEC
case AF_UNSPEC:
return "";
#endif
default:
return "unknown family";
}
}
/*
* Produce a string containing both the address and the port number
* of a sockaddr.
*/
#ifdef HAVE_IPV6
#define ADDRESS_SIZE (INET6_ADDRSTRLEN+8)
#else
#define ADDRESS_SIZE (INET_ADDRSTRLEN+6)
#endif
char *net_address(const struct sockaddr *addr, socklen_t len)
{
const union sock_addr *sa = (const union sock_addr *)addr;
char buf[ADDRESS_SIZE];
char *p, *q;
sa_family_t family = sa->sa.sa_family;
(void)len; /* Not needed... yet */
switch (family) {
case AF_INET:
if (!inet_ntop(family, &sa->si.sin_addr, buf, sizeof buf - 6))
return NULL;
p = strchr(buf, '\0');
p += snprintf(p, sizeof buf - (p - buf), ":%u",
ntohs(sa->si.sin_port));
break;
#ifdef HAVE_IPV6
case AF_INET6:
if (!inet_ntop(family, &sa->s6.sin6_addr, buf+1, sizeof buf - 8))
return NULL;
p = strchr(buf, '\0');
buf[0] = '[';
p = strchr(buf, '\0');
p += snprintf(p, sizeof buf - (p - buf), "]:%u",
ntohs(sa->s6.sin6_port));
break;
#endif
default:
p = buf + snprintf(buf, sizeof buf, "[unknown family %u]", family);
break;
}
*p++ = '\0';
q = xmalloc(p - buf);
return memcpy(q, buf, p - buf);
}
tftp-hpa-7.2+20261013/common/clock.c 0000664 0000000 0000000 00000003545 15263245305 0016542 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2026 H. Peter Anvin
*/
#include "config.h"
#include "clock.h"
/*
* Get the current time as an integer number of microseconds. If
* clock_gettime() is available, get a monotone clock instead of
* real time clock, to avoid strange effects around leap seconds
* or clock adjustments.
*/
#ifdef HAVE_CLOCK_GETTIME
uintmax_t clock_us(void)
{
/* Clocks in order of preference */
static const clockid_t clocks[] = {
#ifdef CLOCK_MONOTONIC
CLOCK_MONOTONIC,
#endif
#ifdef CLOCK_BOOTTIME
CLOCK_BOOTTIME,
#endif
#ifdef CLOCK_MONOTONIC_RAW
CLOCK_MONOTONIC_RAW,
#endif
#ifdef CLOCK_TAI
CLOCK_TAI,
#endif
#ifdef CLOCK_REALTIME
CLOCK_REALTIME,
#endif
#ifdef CLOCK_MONOTONIC_COARSE
CLOCK_MONOTONIC_COARSE,
#endif
#ifdef CLOCK_BOOTTIME_COARSE
CLOCK_BOOTTIME_COARSE,
#endif
#ifdef CLOCK_TAI_COARSE
CLOCK_TAI_COARSE,
#endif
#ifdef CLOCK_REALTIME_COARSE
CLOCK_REALTIME_COARSE,
#endif
};
static const clockid_t * volatile clock_id = clocks;
struct timespec ts;
const clockid_t *clk_p = clock_id;
if (clock_gettime(*clk_p, &ts)) {
/*
* If the pre-selected clock doesn't work, try all the clocks
* from the beginning (in order to cope with a transient failure.)
*/
for (clk_p = clocks; clk_p < ARRAY_END(clocks); clk_p++) {
if (!clock_gettime(*clk_p, &ts)) {
clock_id = clk_p; /* Remember which one worked */
goto ok;
}
}
/* No working clocks!!! */
return 0; /* Failure */
}
ok:
return timespec_to_us(&ts);
}
#else
uintmax_t clock_us(void)
{
struct timeval tv;
if (!gettimeofday(&tv, NULL))
return timeval_to_us(&tv);
return 0; /* Failure */
}
#endif
tftp-hpa-7.2+20261013/common/clock.h 0000664 0000000 0000000 00000002010 15263245305 0016531 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2026 H. Peter Anvin
*/
#ifndef TFTP_CLOCK_H
#define TFTP_CLOCK_H 1
#include "config.h"
#define USEC_PER_SEC 1000000UL
#define NSEC_PER_SEC 1000000000UL
#define NSEC_PER_USEC 1000UL
#define USEC_PER_MSEC 1000UL
#ifdef HAVE_STRUCT_TIMESPEC
static inline uintmax_t timespec_to_us(const struct timespec *ts)
{
return ((uintmax_t)ts->tv_sec * USEC_PER_SEC) +
(ts->tv_nsec / NSEC_PER_USEC);
}
static inline struct timespec *
us_to_timespec(uintmax_t us, struct timespec *ts)
{
ts->tv_sec = us / USEC_PER_SEC;
ts->tv_nsec = (us % USEC_PER_SEC) * NSEC_PER_USEC;
return ts;
}
#endif
static inline uintmax_t timeval_to_us(const struct timeval *tv)
{
return ((uintmax_t)tv->tv_sec * USEC_PER_SEC) + tv->tv_usec;
}
static inline struct timeval *
us_to_timeval(uintmax_t us, struct timeval *tv)
{
tv->tv_sec = us / USEC_PER_SEC;
tv->tv_usec = us % USEC_PER_SEC;
return tv;
}
uintmax_t clock_us(void);
#endif /* TFTP_CLOCK_H */
tftp-hpa-7.2+20261013/common/error.c 0000664 0000000 0000000 00000007020 15263245305 0016570 0 ustar 00root root 0000000 0000000 /*
* Convert a TFTP error packet safely printable string by converting
* control characters to spaces, limiting the length, and including
* an explanation of the error code.
*
* Returns a newly allocated buffer.
*/
#include "config.h"
#include "tftpsubs.h"
const char * const packet_types[PTYPE_CNT] = {
"null",
"RRQ",
"WRQ",
"DATA",
"ACK",
"ERROR",
"OACK"
};
const char * const errmsgs[ETYPE_CNT] = {
"unspecified error", /* 0 - EUNDEF */
"file not found", /* 1 - ENOTFOUND */
"access denied", /* 2 - EACCESS */
"insufficient space for upload", /* 3 - ENOSPACE */
"invalid TFTP operation", /* 4 - EBADOP */
"unknown transfer ID", /* 5 - EBADID */
"file already exists", /* 6 - EEXISTS */
"no such user", /* 7 - ENOUSER */
"options negotiation failure" /* 8 - EOPTNEG */
};
const char *error_msg(int err)
{
const char *msg;
if (err < 0) {
int xerr = errno; /* In case strerror() mucks with errno */
msg = strerror(-err);
errno = xerr;
} else if (err < ETYPE_CNT) {
msg = errmsgs[err];
} else {
msg = "";
}
return msg;
}
char *errpkt_to_string(const struct tftphdr *tp, int n)
{
const char *p, *ep;
char *msg;
uint16_t opcode = ntohs(tp->th_opcode);
uint16_t nerr;
if (n < 2)
return xstrdup("packet too short");
if (opcode != ERROR) {
if (opcode >= PTYPE_CNT)
xasprintf(&msg, "invalid packet type %u", opcode);
else
xasprintf(&msg, "unexpected %s packet", packet_type(opcode));
return msg;
}
if (n < 4)
return xstrdup("error packet too short");
nerr = ntohs(tp->th_code);
/* Truncate a message at control characters or end of packet */
p = tp->th_msg;
ep = (const char *)tp + n;
while (p < ep) {
if (*p < ' ' || *p == 127)
break;
p++;
}
/*
* Emit an ellipsis if the message was truncated somehow (the string
* should be null-terminated in the last position in the packet)
*/
ep = (p != ep-1 || *p) ? "..." : "";
n = p - tp->th_msg;
if (n) {
p = tp->th_msg;
} else {
static const char no_msg[] = "(no message)";
p = no_msg;
n = sizeof no_msg;
}
if (nerr >= ETYPE_CNT)
xasprintf(&msg, "unknown error %u: %*s%s", nerr, n, p, ep);
else
xasprintf(&msg, "%s: %*s%s", errmsgs[nerr], n, p, ep);
return msg;
}
/*
* Create an error packet. Return its length and set *tpp to the
* newly allocated packet.
*/
int make_errpacket(struct tftphdr **tpp, int error, const char *msg)
{
struct tftphdr *tp;
int length;
if (!msg)
msg = error_msg(error);
/* Cap the error string to 512 bytes */
length = strnlen(msg, SEGSIZE-1);
tp = xmalloc(length + 5); /* 4 byte header + NUL */
/* Convert negative errno to TFTP error codes */
switch (error) {
case -ENOENT:
case -ENOTDIR:
case -EPERM:
error = ENOTFOUND;
break;
case -ENOSPC:
error = ENOSPACE;
break;
case -EEXIST:
error = EEXISTS;
break;
default:
if (error < 0 || !*msg)
error = EUNDEF;
break;
}
tp->th_opcode = htons(ERROR);
tp->th_code = htons(error);
memcpy(tp->th_msg, msg, length);
tp->th_msg[length] = 0;
*tpp = tp;
return length + 5; /* Include header and NUL */
}
tftp-hpa-7.2+20261013/common/options.h 0000664 0000000 0000000 00000001007 15263245305 0017136 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (C) 2026 H. Peter Anvin
*/
#ifndef COMMON_OPTIONS_H
#define COMMON_OPTIONS_H
#include "config.h"
struct common_options {
int ai_fam;
unsigned int portrange_from;
unsigned int portrange_to;
int blksize; /* Relative to MTU if <= 0 */
unsigned int max_windowsize;
uintmax_t rexmtval; /* Initial retransmission timeout (us) */
};
extern struct common_options xopt;
#endif /* COMMON_OPTIONS_H */
tftp-hpa-7.2+20261013/common/parsenum.c 0000664 0000000 0000000 00000004051 15263245305 0017272 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2026 H. Peter Anvin
*
* Parse a decimal number, with validation and support for optional
* unit suffixes.
*
* Returns BAD_NUM = uintmax_t maximum on any errors.
*/
#include "config.h"
#include "tftpsubs.h"
#include "common/options.h"
#include
uintmax_t parse_uint(const char *arg, uintmax_t lo, uintmax_t hi)
{
char *end;
uintmax_t parsed, shifted;
unsigned int shift;
if (!arg)
return BAD_NUM;
errno = 0;
parsed = strtoumax(arg, &end, 10);
if (errno || end == arg)
return BAD_NUM;
while (isspace((unsigned char)*end))
end++;
switch (ascii_tolower(*end)) {
case '\0':
shift = 0;
break;
case 'k':
shift = 10;
break;
case 'm':
shift = 20;
break;
case 'g':
shift = 30;
break;
case 't':
shift = 40;
break;
case 'p':
shift = 50;
break;
case 'e':
shift = 60;
break;
default:
return BAD_NUM;
}
shifted = parsed;
if (shift) {
shifted = parsed << shift;
if ((shifted >> shift) != parsed)
return BAD_NUM; /* Overflow! */
end++;
if (*end)
return BAD_NUM; /* Garbage after value */
}
if (shifted < lo || shifted > hi)
return BAD_NUM;
return shifted;
}
bool parse_blocksize_arg(const char *str, unsigned int minimum)
{
uintmax_t v;
if (ascii_strncaseeq(str, "mtu", 3)) {
switch (str[3]) {
case '\0':
xopt.blksize = 0;
return true;
case '-':
v = parse_uint(str+4, 0, INT_MAX/2);
if (v == BAD_NUM)
return false;
xopt.blksize = -v;
return true;
default:
return false;
}
} else {
v = parse_uint(str, minimum, MAX_SEGSIZE);
if (v == BAD_NUM)
return false;
xopt.blksize = v;
return true;
}
}
tftp-hpa-7.2+20261013/common/pollset.c 0000664 0000000 0000000 00000016712 15263245305 0017131 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
#include "config.h"
#include "pollset.h"
#include "clock.h"
#include "tftpsubs.h" /* For xcalloc()/xfree() */
static sigjmp_buf pollset_sigjmpbuf;
static volatile sig_atomic_t pollset_jmp;
static volatile sig_atomic_t pollset_intr;
void pollset_notify_signal(int sig)
{
(void)sig;
if (pollset_jmp) {
pollset_intr = 0;
siglongjmp(pollset_sigjmpbuf, 1);
} else {
pollset_intr = 1;
}
}
struct pollset *pollset_new(void)
{
struct pollset *ptr = xcalloc(1, sizeof(struct pollset));
#ifdef HAVE_POLL_H
/*
* On a typical implementation, struct pollfd is 8 bytes long.
* Typical malloc() datums are 32 or 64 bytes, so consuming 64
* bytes at the start is pretty reasonable, and will cover the
* vast majority of all use cases.
*/
size_t bytes;
ptr->size = 8;
bytes = ptr->size * sizeof(*ptr->fds);
ptr->fds = xmalloc(bytes);
/* Not really necessary, but out of paranoia... */
memset(ptr->fds, -1, bytes);
#else
/* Handle the remote possibility that FD_ZERO() isn't all zero */
FD_ZERO(&ptr->fdset);
#endif
return ptr;
}
void pollset_free(struct pollset **setp)
{
struct pollset *set = *setp;
*setp = NULL;
#ifdef HAVE_POLL_H
xfree(set->fds);
#endif
xfree(set);
}
#ifdef HAVE_POLL_H
/*
* Return the index in the pollset::fds array where either a file
* descriptor *is*, or where it should be inserted if it isn't already
* included.
*/
struct pollset_found {
bool found;
size_t i;
};
static struct pollset_found pollset_find(const struct pollset *set, int fd)
{
size_t l = 0; /* Lowest possible position */
size_t h = set->nfds; /* Highest possible position + 1 */
struct pollset_found found;
while (l < h) {
size_t i = (l+h) >> 1;
if (set->fds[i].fd < fd) {
l = i+1;
} else if (set->fds[i].fd == fd) {
/* Exact match */
found.found = true;
found.i = i;
return found;
} else {
h = i;
}
}
/* No exact match, l will point to the insertion index point */
found.found = false;
found.i = l;
return found;
}
struct pollset *pollset_add(struct pollset *set, int fd)
{
struct pollset_found found;
if (!set)
set = pollset_new();
if (fd < 0) /* Invalid file descriptor */
return set;
/*
* Check for duplicates, and where in a sorted list to insert the
* value.
*/
found = pollset_find(set, fd);
if (found.found)
return set; /* Already in set */
if (set->nfds >= set->size) {
size_t oldsize = set->size;
size_t newsize = set->size = oldsize << 1;
set->fds = xrealloc(set->fds, newsize * sizeof(*set->fds));
/* Not really necessary, but out of paranoia... */
memset(set->fds + oldsize, -1, (newsize-oldsize) * sizeof(*set->fds));
}
if (found.i < (size_t)set->nfds) {
memmove(&set->fds[found.i+1], &set->fds[found.i],
(set->nfds - found.i) * sizeof(*set->fds));
}
set->fds[found.i].fd = fd;
set->nfds++;
return set;
}
int pollset_next(const struct pollset *set, pollset_cursor *cursor, int *whatp)
{
int what;
pollset_cursor i = *cursor;
what = whatp ? *whatp : 0;
while (i < set->nfds) {
if (whatp) {
int whatflags = what & set->fds[i].revents;
if (whatflags) {
*whatp = whatflags;
*cursor = i+1;
return set->fds[i].fd;
}
} else {
*cursor = i+1;
return set->fds[i].fd;
}
i++;
}
*cursor = set->nfds;
return -1;
}
int pollset_poll(struct pollset *set, int what, intmax_t utimeout)
{
size_t i;
int rv;
for (i = 0; i < set->nfds; i++)
set->fds[i].events = what;
if (pollset_intr)
goto intr;
if (sigsetjmp(pollset_sigjmpbuf, 1))
goto intr;
pollset_jmp = 1;
if (pollset_intr)
goto intr;
#ifdef HAVE_PPOLL
{
struct timespec ts, *tsp = NULL;
if (utimeout >= 0)
tsp = us_to_timespec(utimeout, &ts);
rv = ppoll(set->fds, set->nfds, tsp, NULL);
}
#else
{
int timeout = -1;
if (utimeout >= 0) {
utimeout = (utimeout + MSEC_PER_USEC-1)/MSEC_PER_USEC;
timeout = (utimeout > INT_MAX) ? INT_MAX : utimeout;
}
rv = poll(set->fds, set->nfds, timeout);
}
#endif
pollset_jmp = 0;
return rv;
intr:
pollset_intr = 0;
pollset_jmp = 0;
errno = EINTR;
return -1;
}
int pollset_close(struct pollset **setp)
{
struct pollset *set = *setp;
size_t i;
int err = 0;
for (i = 0; i < set->nfds; i++)
err |= close(set->fds[i].fd);
pollset_free(setp);
return err;
}
bool pollset_has(const struct pollset *set, int fd)
{
return pollset_find(set, fd).found;
}
#else /* no poll(), using select() */
struct pollset *pollset_add(struct pollset *set, int fd)
{
if (!set)
set = pollset_new();
/* select() has a maximum supported file descriptor count */
if ((unsigned int)fd >= FD_SETSIZE)
return set;
if (fd >= set->nfds)
set->nfds = fd + 1;
FD_SET(fd, &set->fdset);
return set;
}
static int fd_what(const struct pollset *set, int fd)
{
int what = 0;
size_t i;
if (fd >= set->nfds)
return 0;
for (i = 0; i < POLLSET_FDSETS; i++)
if (FD_ISSET(fd, &set->rfdset[i]))
what |= 1 << i;
return what;
}
int pollset_next(const struct pollset *set, pollset_cursor *cursor, int *whatp)
{
int what;
pollset_cursor i = *cursor;
what = whatp ? *whatp : 0;
while (i < set->nfds) {
if (FD_ISSET(i, &set->fdset)) {
if (whatp) {
int whatflags = what & fd_what(set, i);
if (whatflags) {
*whatp = whatflags;
*cursor = i+1;
return i;
}
} else {
*cursor = i+1;
return i;
}
}
i++;
}
*cursor = set->nfds;
return -1;
}
int pollset_poll(struct pollset *set, int what, intmax_t utimeout)
{
fd_set *sets[3] = { NULL, NULL, NULL };
size_t i;
const size_t nsets = POLLSET_FDSETS < 3 ? POLLSET_FDSETS : 3;
int rv;
for (i = 0; i < nsets; i++) {
if (what & (1 << i)) {
sets[i] = &set->rfdset[i];
memcpy(&set->rfdset[i], &set->fdset, sizeof set->fdset);
} else {
FD_ZERO(&set->rfdset[i]);
}
}
if (pollset_intr)
goto intr;
if (sigsetjmp(pollset_sigjmpbuf, 1))
goto intr;
pollset_jmp = 1;
if (pollset_intr)
goto intr;
{
struct timeval tv, *tvp = NULL;
if (utimeout >= 0)
tvp = usec_to_timeval(utimeout, &tv);
rv = select(set->nfds, sets[0], sets[1], sets[2], tvp);
}
pollset_jmp = 0;
return rv;
intr:
pollset_intr = 0;
pollset_jmp = 0;
errno = EINTR;
return -1;
}
int pollset_close(struct pollset **setp)
{
struct pollset *set = *setp;
size_t i;
int err = 0;
for (i = 0; i < (size_t)set->nfds; i++)
if (FD_ISSET(i, &set->fdset))
err |= close(i);
pollset_free(setp);
return err;
}
#endif
tftp-hpa-7.2+20261013/common/pollset.h 0000664 0000000 0000000 00000003362 15263245305 0017133 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
#ifndef TFTP_POLL_H
#define TFTP_POLL_H 1
#include "config.h"
#ifdef HAVE_POLL_H
struct pollset {
nfds_t nfds;
nfds_t size;
struct pollfd *fds;
};
typedef nfds_t pollset_cursor;
#define POLLSET_IN (POLLIN | POLLHUP | POLLERR)
#define POLLSET_OUT (POLLOUT | POLLERR)
#define POLLSET_EX (POLLPRI)
bool pollset_has(const struct pollset *set, int fd);
#else
#define POLLSET_FDSETS 3 /* read, write, err */
struct pollset {
int nfds;
fd_set fdset;
fd_set rfdset[POLLSET_FDSETS]; /* No "all" set included */
};
typedef int pollset_cursor;
#define POLLSET_IN 1
#define POLLSET_OUT 2
#define POLLSET_EX 4
static inline bool pollset_has(const struct pollset *set, int fd)
{
return !!FD_ISSET(fd, &set->fdset);
}
#endif
static inline bool pollset_isempty(const struct pollset *set)
{
return set->nfds <= 0;
}
struct pollset *pollset_new(void);
struct pollset *pollset_add(struct pollset *set, int fd);
int pollset_next(const struct pollset *set, pollset_cursor *cursor, int *whatp);
int pollset_poll(struct pollset *set, int what, intmax_t utimeout);
/*
* pollset_close() is like pollset_free(), but closes file descriptors
* in the set.
*/
int pollset_close(struct pollset **setp);
void pollset_free(struct pollset **setp);
/*
* Signals that should be masked around the poll, to avoid possibly lost
* EINTR.
*/
void pollset_sigmask_add(int sig);
void pollset_sigmask_clear(void);
/*
* pollset_notify_signal() should be called at the end of a signal
* handler to force the next pollset_poll() to return EINTR if set.
* It may or may not return.
*/
void pollset_notify_signal(int sig);
#endif /* TFTP_POLLSET_H */
tftp-hpa-7.2+20261013/common/progname.c 0000664 0000000 0000000 00000000606 15263245305 0017252 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
#include "config.h"
#include "tftpsubs.h"
const char *_progname;
pid_t _progpid;
void set_progname(const char *argv0)
{
const char *p = strrchr(argv0, '/');
_progname = p ? p+1 : argv0;
_progpid = getpid();
}
void post_fork(void)
{
_progpid = getpid();
}
tftp-hpa-7.2+20261013/common/random.c 0000664 0000000 0000000 00000010144 15263245305 0016720 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause-UC
*
* Copyright (c) 2026 H. Peter Anvin
*/
#include "config.h"
#include "tftpsubs.h"
#ifndef HAVE_RANDOM
static inline long random(void)
{
return rand();
}
static inline void srandom(unsigned int seed)
{
return srand(seed);
}
#endif
static inline uint32_t mulx(uint32_t a, uint32_t b)
{
uint64_t c = (uint64_t)a * b;
return (uint32_t)(c >> 32) ^ (uint32_t)c;
}
/*
* Arbitrary prime numbers in [2^31,2^32) with decent bit balance
* 0x915d4bcd = 2438810573 = 0b10010001010111010100101111001101
* 0xa1789f93 = 2709036947 = 0b10100001011110001001111110010011
* 0xb4cb6f11 = 3033231121 = 0x10110100110010110110111100010001
*/
#define PRIME1 0x915d4bcd
#define PRIME2 0xa1789f93
#define PRIME3 0xb4cb6f11
uint32_t (*random_u32)(void);
static uint32_t random_from_tick(void)
{
#ifdef HAVE_CLOCK_GETTIME
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return mulx(ts.tv_sec, PRIME1) + mulx(ts.tv_nsec, PRIME2);
#else
return mulx(clock_us() * PRIME1, PRIME2);
#endif
}
static void seed_random(void)
{
srandom(random_from_tick() ^ mulx(getpid(), PRIME3));
}
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
struct cpuid {
uint32_t eax, ecx, edx, ebx;
};
#define X86_EFLAGS_ID (1U << 21)
#define X86_CPUID_RDRAND (1U << 30) /* In cpuid(1,0).ecx */
static inline bool have_cpuid(void)
{
#ifdef __x86_64__
return true;
#else
uint32_t x, y;
asm("pushf; "
"pushf; "
"pop %0; "
"xor %2,%0; "
"push %0; "
"popf; "
"pushf; "
"pop %1; "
"popf"
: "=r" (x), "=r" (y)
: "g" (X86_EFLAGS_ID));
return !!((x^y) & (X86_EFLAGS_ID));
#endif
}
static inline struct cpuid cpuid(uint32_t leaf, uint32_t subleaf)
{
struct cpuid res;
#if defined(__i386__) && defined(__PIC__)
/* %ebx might be a reserved register for i386 in PIC mode */
asm(".ifnc '%3','%%ebx'; xchg %%ebx,%3; .endif; "
"cpuid; "
".ifnc '%3','%%ebx'; xchg %%ebx,%3; .endif"
: "=a" (res.eax), "=c" (res.ecx), "=d" (res.edx), "=r" (res.ebx)
: "a" (leaf), "c" (subleaf));
#else
asm("cpuid"
: "=a" (res.eax), "=c" (res.ecx), "=d" (res.edx), "=b" (res.ebx)
: "a" (leaf), "c" (subleaf));
#endif
return res;
}
NOINLINE_FUNC static uint32_t x86_random_u32_tsc(void)
{
uint32_t lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return (mulx(lo, PRIME1) + mulx(hi, PRIME2)) ^ random();
}
NOINLINE_FUNC static uint32_t x86_random_u32_rdrand(void)
{
uint32_t v;
bool ok;
int cnt;
for (cnt = 0; cnt < 16; cnt++) {
#ifdef __GCC_ASM_FLAG_OUTPUTS__
asm volatile("rdrand %0" : "=r" (v), "=@ccnc" (ok) : : "cc");
#else
asm volatile("rdrand %0; setnc %1" : "=r" (v), "=q" (ok) : : "cc");
#endif
if (likely(ok))
return v;
}
/* rdrand failed despite multiple tries; assume broken */
random_u32 = x86_random_u32_tsc;
return x86_random_u32_tsc();
}
static inline void arch_random_init(void)
{
if (have_cpuid() && cpuid(0, 0).eax >= 1) {
struct cpuid leaf1 = cpuid(1, 0);
if (leaf1.ecx & X86_CPUID_RDRAND)
random_u32 = x86_random_u32_rdrand;
}
}
#else
static inline void arch_random_init(void)
{
}
#endif /* GNUC x86 */
static FILE *urandom_fh;
static uint32_t random_u32_tick(void)
{
return random_from_tick() ^ random();
}
NOINLINE_FUNC static uint32_t random_u32_urandom(void)
{
uint32_t v = PRIME3;
if (fread(&v, sizeof v, 1, urandom_fh) == 1)
return v;
/* Reading /dev/urandom failed, but might have gotten something... */
return v + random_u32_tick();
}
static void close_urandom(void)
{
fclose(urandom_fh);
}
void random_init(void)
{
seed_random();
/* Try to open /dev/urandom if it exists */
urandom_fh = fopen("/dev/urandom", "r");
if (urandom_fh) {
setvbuf(urandom_fh, NULL, _IONBF, 0); /* Disable buffering */
atexit(close_urandom);
random_u32 = random_u32_urandom;
} else {
random_u32 = random_u32_tick;
}
arch_random_init();
}
tftp-hpa-7.2+20261013/common/signal.c 0000664 0000000 0000000 00000000733 15263245305 0016720 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2024 Intel Corporation; Author: H. Peter Anvin
*/
/*
* signal.c
*
* User-friendly wrapper around sigaction().
*/
#include "config.h"
#include "tftpsubs.h"
int tftp_signal(int signum, sighandler_t handler, int flags)
{
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = flags;
return sigaction(signum, &sa, NULL);
}
tftp-hpa-7.2+20261013/common/tftp-io.c 0000664 0000000 0000000 00000036202 15263245305 0017025 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#include "config.h"
#include "tftp-io.h"
#ifdef HAVE_PTHREAD
#include
#endif
enum io_direction {
IO_READ,
IO_WRITE
};
enum slot_state {
SLOT_EMPTY,
SLOT_RESERVED,
SLOT_READY,
SLOT_WRITING
};
struct tftp_io_ops {
int (*read_packet)(struct tftp_io *, struct tftphdr *);
int (*write_packet)(struct tftp_io *, const struct tftphdr *, int);
int (*write_finish)(struct tftp_io *);
};
struct tftp_io {
FILE *file;
const struct tftp_io_ops *ops;
char *packets;
int *lengths;
enum slot_state *states;
unsigned int slots;
unsigned int window;
unsigned int blocksize;
unsigned int packetsize;
unsigned int head;
unsigned int tail;
unsigned int count;
unsigned int held;
int error;
bool eof;
bool stopped;
bool threaded;
bool newline;
int prevchar;
bool write_cr;
#ifdef HAVE_PTHREAD
pthread_t thread;
pthread_mutex_t lock;
pthread_cond_t changed;
bool lock_initialized;
bool cond_initialized;
#endif
};
static unsigned int io_next(const struct tftp_io *io, unsigned int n)
{
return n + 1 == io->slots ? 0 : n + 1;
}
static struct tftphdr *io_packet(const struct tftp_io *io, unsigned int n)
{
return (struct tftphdr *)(io->packets + (size_t)n * io->packetsize);
}
static void io_error(struct tftp_io *io, int error)
{
if (!error)
error = EIO;
if (!io->error)
io->error = error;
}
static int octet_read_packet(struct tftp_io *io, struct tftphdr *dp)
{
size_t n;
n = fread_unlocked(dp->th_data, 1, io->blocksize, io->file);
if (n < io->blocksize && ferror(io->file)) {
errno = EIO;
return -1;
}
return (int)n;
}
static int netascii_read_packet(struct tftp_io *io, struct tftphdr *dp)
{
char *p;
int c;
unsigned int i;
p = dp->th_data;
for (i = 0; i < io->blocksize; i++) {
if (io->newline) {
c = io->prevchar == '\n' ? '\n' : '\0';
io->newline = false;
} else {
c = getc_unlocked(io->file);
if (c == EOF) {
if (ferror(io->file)) {
errno = EIO;
return -1;
}
break;
}
if (c == '\n' || c == '\r') {
io->prevchar = c;
c = '\r';
io->newline = true;
}
}
*p++ = c;
}
return (int)(p - dp->th_data);
}
static int octet_write_packet(struct tftp_io *io, const struct tftphdr *dp,
int count)
{
if (fwrite_unlocked(dp->th_data, 1, count, io->file) != (size_t)count) {
errno = EIO;
return -1;
}
return count;
}
static int netascii_write_packet(struct tftp_io *io,
const struct tftphdr *dp, int count)
{
const char *p;
int c;
int ct;
p = dp->th_data;
ct = count;
while (ct--) {
c = *p++;
if (io->write_cr) {
if (c == '\n') {
c = '\n';
} else if (c == '\0') {
c = '\r';
} else if (putc_unlocked('\r', io->file) == EOF) {
errno = EIO;
return -1;
}
io->write_cr = false;
if (putc_unlocked(c, io->file) == EOF) {
errno = EIO;
return -1;
}
continue;
}
if (c == '\r') {
io->write_cr = true;
continue;
}
if (putc_unlocked(c, io->file) == EOF) {
errno = EIO;
return -1;
}
}
return count;
}
static int octet_write_finish(struct tftp_io *io)
{
errno = 0;
if (fflush_unlocked(io->file)) {
if (!errno)
errno = EIO;
return -1;
}
return 0;
}
static int netascii_write_finish(struct tftp_io *io)
{
if (io->write_cr) {
if (putc_unlocked('\r', io->file) == EOF) {
errno = EIO;
return -1;
}
io->write_cr = false;
}
errno = 0;
if (fflush_unlocked(io->file)) {
if (!errno)
errno = EIO;
return -1;
}
return 0;
}
static const struct tftp_io_ops octet_io_ops = {
octet_read_packet,
octet_write_packet,
octet_write_finish
};
static const struct tftp_io_ops netascii_io_ops = {
netascii_read_packet,
netascii_write_packet,
netascii_write_finish
};
#ifdef HAVE_PTHREAD
static void *reader_thread(void *arg)
{
struct tftp_io *io = arg;
struct tftphdr *dp;
int length;
for (;;) {
pthread_mutex_lock(&io->lock);
while (io->count == io->slots && !io->stopped)
pthread_cond_wait(&io->changed, &io->lock);
if (io->stopped) {
pthread_mutex_unlock(&io->lock);
break;
}
dp = io_packet(io, io->tail);
pthread_mutex_unlock(&io->lock);
length = io->ops->read_packet(io, dp);
pthread_mutex_lock(&io->lock);
if (length < 0) {
io_error(io, errno);
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
break;
}
io->lengths[io->tail] = length + 4;
io->tail = io_next(io, io->tail);
io->count++;
if (length != (int)io->blocksize)
io->eof = true;
pthread_cond_broadcast(&io->changed);
if (io->eof || io->stopped) {
pthread_mutex_unlock(&io->lock);
break;
}
pthread_mutex_unlock(&io->lock);
}
return NULL;
}
static void *writer_thread(void *arg)
{
struct tftp_io *io = arg;
struct tftphdr *dp;
int length;
for (;;) {
pthread_mutex_lock(&io->lock);
while (io->states[io->head] != SLOT_READY &&
!io->stopped && !io->error)
pthread_cond_wait(&io->changed, &io->lock);
if (io->stopped || io->error) {
pthread_mutex_unlock(&io->lock);
break;
}
io->states[io->head] = SLOT_WRITING;
dp = io_packet(io, io->head);
length = io->lengths[io->head];
pthread_mutex_unlock(&io->lock);
if (io->ops->write_packet(io, dp, length) != length) {
pthread_mutex_lock(&io->lock);
io_error(io, errno);
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
break;
}
pthread_mutex_lock(&io->lock);
io->states[io->head] = SLOT_EMPTY;
io->head = io_next(io, io->head);
io->count--;
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
}
return NULL;
}
#endif
static struct tftp_io *io_start(FILE *file, bool convert, unsigned int slots,
unsigned int window, unsigned int blocksize,
enum io_direction direction, bool threaded)
{
struct tftp_io *io;
#ifdef HAVE_PTHREAD
int error;
#endif
if (!slots || !blocksize || (direction == IO_READ && slots < window)) {
errno = EINVAL;
return NULL;
}
#ifndef HAVE_PTHREAD
if (threaded) {
errno = ENOTSUP;
return NULL;
}
#endif
io = xcalloc(1, sizeof(*io));
io->file = file;
io->slots = slots;
io->window = window;
io->blocksize = blocksize;
io->packetsize = ((size_t)blocksize + 5) & ~(size_t)1;
io->ops = convert ? &netascii_io_ops : &octet_io_ops;
io->threaded = threaded;
io->prevchar = -1;
io->packets = xcalloc(io->slots, io->packetsize);
io->lengths = xcalloc(io->slots, sizeof(*io->lengths));
if (direction == IO_WRITE)
io->states = xcalloc(io->slots, sizeof(*io->states));
#ifdef HAVE_PTHREAD
if (!threaded)
return io;
error = pthread_mutex_init(&io->lock, NULL);
if (!error)
io->lock_initialized = true;
if (!error)
error = pthread_cond_init(&io->changed, NULL);
if (!error)
io->cond_initialized = true;
if (!error)
error = pthread_create(&io->thread, NULL,
direction == IO_READ ? reader_thread :
writer_thread, io);
if (!error)
return io;
errno = error;
if (io->cond_initialized)
pthread_cond_destroy(&io->changed);
if (io->lock_initialized)
pthread_mutex_destroy(&io->lock);
xfree(io->states);
xfree(io->lengths);
xfree(io->packets);
xfree(io);
return NULL;
#else
return io;
#endif
}
struct tftp_io *tftp_io_reader_start(FILE *file, bool convert,
unsigned int window, unsigned int slots,
unsigned int blocksize, bool threaded)
{
return io_start(file, convert, slots, window, blocksize, IO_READ,
threaded);
}
struct tftp_io *tftp_io_writer_start(FILE *file, bool convert,
unsigned int slots, unsigned int blocksize,
bool threaded)
{
return io_start(file, convert, slots, 0, blocksize, IO_WRITE, threaded);
}
static int tftp_io_read_window(void *vctx, unsigned int *count, bool *final)
{
struct tftp_io *io = vctx;
struct tftphdr *dp;
int length;
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_mutex_lock(&io->lock);
while (io->count < io->window && !io->eof && !io->error)
pthread_cond_wait(&io->changed, &io->lock);
} else
#endif
{
while (io->count < io->window && !io->eof && !io->error) {
dp = io_packet(io, io->tail);
length = io->ops->read_packet(io, dp);
if (length < 0) {
io_error(io, errno);
break;
}
io->lengths[io->tail] = length + 4;
io->tail = io_next(io, io->tail);
io->count++;
if (length != (int)io->blocksize)
io->eof = true;
}
}
if (io->error) {
errno = io->error;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
return -1;
}
io->held = io->count < io->window ? io->count : io->window;
*count = io->held;
*final = io->eof && io->held == io->count;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
return 0;
}
static struct tftphdr *tftp_io_read_packet(void *vctx, unsigned int n)
{
struct tftp_io *io = vctx;
if (n >= io->held) {
errno = EINVAL;
return NULL;
}
return io_packet(io, (io->head + n) % io->slots);
}
static int tftp_io_read_length(void *vctx, unsigned int n)
{
struct tftp_io *io = vctx;
if (n >= io->held) {
errno = EINVAL;
return -1;
}
return io->lengths[(io->head + n) % io->slots];
}
static void tftp_io_read_release(void *vctx)
{
struct tftp_io *io = vctx;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_lock(&io->lock);
#endif
while (io->held) {
io->head = io_next(io, io->head);
io->count--;
io->held--;
}
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
}
#endif
}
static struct tftphdr *tftp_io_writer_reserve(struct tftp_io *io)
{
struct tftphdr *dp;
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_mutex_lock(&io->lock);
while (io->states[io->tail] != SLOT_EMPTY && !io->error)
pthread_cond_wait(&io->changed, &io->lock);
} else
#endif
if (io->states[io->tail] != SLOT_EMPTY && !io->error) {
errno = EIO;
return NULL;
}
if (io->error) {
errno = io->error;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
return NULL;
}
io->states[io->tail] = SLOT_RESERVED;
dp = io_packet(io, io->tail);
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
return dp;
}
static int tftp_io_write_publish(void *vctx, int length)
{
struct tftp_io *io = vctx;
if (length < 0 || length > (int)io->blocksize) {
errno = EINVAL;
return -1;
}
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_lock(&io->lock);
#endif
if (io->states[io->tail] != SLOT_RESERVED) {
errno = EIO;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
return -1;
}
io->lengths[io->tail] = length;
io->states[io->tail] = SLOT_READY;
io->tail = io_next(io, io->tail);
io->count++;
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
}
#endif
return 0;
}
static struct tftphdr *tftp_io_xfer_write_reserve(void *vctx)
{
return tftp_io_writer_reserve(vctx);
}
static int tftp_io_write_drain(void *vctx)
{
struct tftp_io *io = vctx;
struct tftphdr *dp;
int length;
int error;
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_mutex_lock(&io->lock);
while (io->count && !io->error)
pthread_cond_wait(&io->changed, &io->lock);
error = io->error;
pthread_mutex_unlock(&io->lock);
} else
#endif
{
while (io->count && !io->error) {
if (io->states[io->head] != SLOT_READY) {
io_error(io, EIO);
break;
}
io->states[io->head] = SLOT_WRITING;
dp = io_packet(io, io->head);
length = io->lengths[io->head];
if (io->ops->write_packet(io, dp, length) != length) {
io_error(io, errno);
break;
}
io->states[io->head] = SLOT_EMPTY;
io->head = io_next(io, io->head);
io->count--;
}
error = io->error;
}
if (!error && fflush_unlocked(io->file)) {
error = errno ? errno : EIO;
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_lock(&io->lock);
#endif
io_error(io, error);
#ifdef HAVE_PTHREAD
if (io->threaded)
pthread_mutex_unlock(&io->lock);
#endif
}
if (error)
errno = error;
return error ? -1 : 0;
}
static int tftp_io_write_finish(void *vctx)
{
struct tftp_io *io = vctx;
if (io->ops->write_finish(io) < 0) {
io_error(io, errno);
errno = io->error;
return -1;
}
return 0;
}
void tftp_io_stop(struct tftp_io *io)
{
if (!io)
return;
#ifdef HAVE_PTHREAD
if (io->threaded) {
pthread_mutex_lock(&io->lock);
io->stopped = true;
pthread_cond_broadcast(&io->changed);
pthread_mutex_unlock(&io->lock);
(void)pthread_join(io->thread, NULL);
pthread_cond_destroy(&io->changed);
pthread_mutex_destroy(&io->lock);
}
#endif
xfree(io->states);
xfree(io->lengths);
xfree(io->packets);
xfree(io);
}
const struct tftp_xfer_io_ops tftp_io_xfer_ops = {
tftp_io_read_window,
tftp_io_read_packet,
tftp_io_read_length,
tftp_io_read_release,
tftp_io_xfer_write_reserve,
tftp_io_write_publish,
tftp_io_write_drain,
tftp_io_write_finish
};
tftp-hpa-7.2+20261013/common/tftp-io.h 0000664 0000000 0000000 00000001040 15263245305 0017022 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#ifndef TFTP_IO_H
#define TFTP_IO_H
#include "tftp-xfer.h"
struct tftp_io;
struct tftp_io *tftp_io_reader_start(FILE *, bool, unsigned int,
unsigned int, unsigned int, bool);
struct tftp_io *tftp_io_writer_start(FILE *, bool, unsigned int,
unsigned int, bool);
void tftp_io_stop(struct tftp_io *);
extern const struct tftp_xfer_io_ops tftp_io_xfer_ops;
#endif /* TFTP_IO_H */
tftp-hpa-7.2+20261013/common/tftp-xfer.c 0000664 0000000 0000000 00000027713 15263245305 0017371 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#include "tftp-xfer.h"
static void set_result(struct tftp_xfer_result *result,
enum tftp_xfer_status status, int error,
uintmax_t bytes)
{
result->status = status;
result->error = error;
result->bytes = bytes;
}
static void finish(const struct tftp_xfer *xfer,
struct tftp_xfer_result *result,
enum tftp_xfer_status status, int error, uintmax_t bytes)
{
xfer->ops->retry_leave(xfer->context);
set_result(result, status, error, bytes);
}
static uint16_t next_block(uint16_t block, uint16_t rollover)
{
if (!++block)
block = rollover;
return block;
}
void tftp_xfer_send(const struct tftp_xfer *xfer,
struct tftp_xfer_result *result)
{
struct tftphdr * volatile dp;
struct tftphdr *ap;
sigjmp_buf retrybuf;
volatile uint16_t block = 1;
volatile uintmax_t bytes = 0;
unsigned int packet_count;
bool final;
int n;
int size;
int resend_start;
bool restarted;
uint16_t opcode;
uint16_t packet_block;
uint16_t expected_ack;
result->last_block = 0;
result->packet = NULL;
result->packet_len = 0;
if (!xfer->io_ops) {
errno = EINVAL;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno, 0);
return;
}
for (;;) {
if (xfer->io_ops->read_window(xfer->io_context, &packet_count,
&final) < 0 ||
!packet_count || packet_count > xfer->windowsize) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno, bytes);
return;
}
for (n = 0; n < (int)packet_count; n++) {
dp = xfer->io_ops->read_packet(xfer->io_context,
(unsigned int)n);
if (!dp) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno,
bytes);
return;
}
dp->th_opcode = htons((uint16_t)DATA);
dp->th_block = htons(block);
block = next_block(block, xfer->rollover);
}
restarted = !!sigsetjmp(retrybuf, 1);
xfer->ops->retry_enter(xfer->context, &retrybuf, restarted);
resend_start = 0;
resend_window:
for (n = resend_start; (unsigned int)n < packet_count; n++) {
dp = xfer->io_ops->read_packet(xfer->io_context,
(unsigned int)n);
size = xfer->io_ops->read_length(xfer->io_context,
(unsigned int)n);
if (!dp || size < 4 || size > (int)xfer->blocksize + 4) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno,
bytes);
return;
}
if (xfer->ops->send(xfer->context, dp, size) < 0) {
finish(xfer, result, TFTP_XFER_SEND_ERROR, errno,
bytes);
return;
}
}
xfer->ops->wait_begin(xfer->context);
for (;;) {
n = xfer->ops->recv(xfer->context, xfer->control,
xfer->control_size);
if (n < 0) {
finish(xfer, result, TFTP_XFER_RECV_ERROR, errno,
bytes);
return;
}
if (n < 4)
continue;
ap = xfer->control;
xfer->ops->received(xfer->context, ap, n);
opcode = ntohs(ap->th_opcode);
packet_block = ntohs(ap->th_block);
if (opcode == ERROR) {
result->packet = ap;
result->packet_len = n;
finish(xfer, result, TFTP_XFER_PEER_ERROR, 0, bytes);
return;
}
dp = xfer->io_ops->read_packet(xfer->io_context,
packet_count - 1);
if (!dp) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno,
bytes);
return;
}
expected_ack = ntohs(dp->th_block);
if (opcode == ACK && packet_block == expected_ack)
break;
if (opcode == OACK && xfer->resend_oack) {
resend_start = 0;
goto resend_window;
}
if (opcode == ACK) {
/*
* An ACK within this window cumulatively confirms its
* prefix. Retransmit only the remaining suffix.
*/
for (n = 0; (unsigned int)n + 1 < packet_count; n++) {
dp = xfer->io_ops->read_packet(xfer->io_context,
(unsigned int)n);
if (!dp) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_READ_ERROR, errno,
bytes);
return;
}
if (packet_block == ntohs(dp->th_block)) {
resend_start = n + 1;
goto resend_window;
}
}
}
}
for (n = 0; (unsigned int)n < packet_count; n++) {
bytes += xfer->io_ops->read_length(xfer->io_context,
(unsigned int)n) - 4;
}
xfer->io_ops->read_release(xfer->io_context);
if (final) {
finish(xfer, result, TFTP_XFER_OK, 0, bytes);
return;
}
}
}
void tftp_xfer_recv(const struct tftp_xfer *xfer,
struct tftphdr *input, int input_size,
struct tftphdr **initial_reply,
int initial_reply_len,
struct tftphdr **initial_packet,
int initial_packet_len,
struct tftp_xfer_result *result)
{
struct tftphdr * volatile dp;
struct tftphdr ack;
const struct tftphdr *reply;
const struct tftphdr *packet;
sigjmp_buf retrybuf;
volatile uint16_t block = 1;
volatile uint16_t last_received = 0;
volatile uint16_t last_acked = 0;
uint16_t opcode;
volatile uint16_t packet_block;
volatile uintmax_t bytes = 0;
volatile int packets_in_window = 0;
volatile bool initial_reply_pending;
volatile bool initial_packet_pending;
int reply_len;
int n;
int size;
bool final;
bool restarted;
initial_reply_pending =
initial_reply_len >= 4 && initial_reply && *initial_reply;
initial_packet_pending =
initial_packet_len >= 4 && initial_packet && *initial_packet;
ack.th_opcode = htons(ACK);
result->last_block = 0;
result->packet = NULL;
result->packet_len = 0;
if (!xfer->io_ops || !xfer->io_ops->write_finish) {
errno = EINVAL;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno, 0);
return;
}
if (!input || input_size < (int)xfer->blocksize + 4) {
errno = EINVAL;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno, 0);
return;
}
dp = xfer->io_ops->write_reserve(xfer->io_context);
if (!dp) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno, 0);
return;
}
for (;;) {
restarted = !!sigsetjmp(retrybuf, 1);
xfer->ops->retry_enter(xfer->context, &retrybuf, restarted);
if (initial_reply_pending || restarted) {
if (initial_reply_pending) {
reply = *initial_reply;
reply_len = initial_reply_len;
} else {
ack.th_block = htons(last_acked);
reply = &ack;
reply_len = 4;
}
if (xfer->ops->send(xfer->context, reply, reply_len) < 0) {
finish(xfer, result, TFTP_XFER_SEND_ERROR, errno,
bytes);
return;
}
}
if (initial_packet_pending) {
n = initial_packet_len;
initial_packet_pending = false;
packet = *initial_packet;
opcode = ntohs(packet->th_opcode);
packet_block = ntohs(packet->th_block);
} else {
xfer->ops->wait_begin(xfer->context);
for (;;) {
n = xfer->ops->recv(xfer->context, input, input_size);
if (n < 0) {
finish(xfer, result, TFTP_XFER_RECV_ERROR, errno,
bytes);
return;
}
if (n < 4)
continue;
xfer->ops->received(xfer->context, input, n);
packet = input;
opcode = ntohs(input->th_opcode);
packet_block = ntohs(input->th_block);
if (opcode == ERROR) {
result->packet = input;
result->packet_len = n;
finish(xfer, result, TFTP_XFER_PEER_ERROR, 0,
bytes);
return;
}
if (opcode != DATA)
continue;
if (packet_block == block)
break;
/*
* RFC 7440 recovery is driven by the last contiguous
* block, including when it falls within the current window.
*/
ack.th_block = htons(last_received);
(void)xfer->ops->send(xfer->context, &ack, 4);
}
}
initial_reply_pending = false;
xdeletep(initial_reply);
if (n - 4 > (int)xfer->blocksize) {
finish(xfer, result, TFTP_XFER_BAD_DATA, 0, bytes);
return;
}
size = n - 4;
if ((uintmax_t)size > xfer->max_bytes - bytes) {
finish(xfer, result, TFTP_XFER_SIZE_EXCEEDED, 0, bytes);
return;
}
memcpy(dp, packet, (size_t)n);
if (xfer->io_ops->write_publish(xfer->io_context, size) < 0) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno, bytes);
return;
}
xdeletep(initial_packet);
bytes += size;
final = size != (int)xfer->blocksize;
packets_in_window++;
last_received = packet_block;
block = next_block(block, xfer->rollover);
if (final || packets_in_window == (int)xfer->windowsize) {
last_acked = packet_block;
packets_in_window = 0;
ack.th_block = htons(last_acked);
if (xfer->io_ops->write_drain(xfer->io_context) < 0) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno,
bytes);
return;
}
if (final &&
xfer->io_ops->write_finish(xfer->io_context) < 0) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno,
bytes);
return;
}
if (xfer->ops->send(xfer->context, &ack, 4) < 0) {
finish(xfer, result, TFTP_XFER_SEND_ERROR, errno,
bytes);
return;
}
if (final) {
result->last_block = last_acked;
finish(xfer, result, TFTP_XFER_OK, 0, bytes);
return;
}
}
dp = xfer->io_ops->write_reserve(xfer->io_context);
if (!dp) {
if (!errno)
errno = EIO;
finish(xfer, result, TFTP_XFER_WRITE_ERROR, errno, bytes);
return;
}
}
}
tftp-hpa-7.2+20261013/common/tftp-xfer.h 0000664 0000000 0000000 00000010515 15263245305 0017366 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#ifndef TFTP_XFER_H
#define TFTP_XFER_H
#include "tftpsubs.h"
#define TFTP_XFER_MAX_PACKET_SIZE (MAX_SEGSIZE + 4)
enum tftp_xfer_status {
TFTP_XFER_OK,
TFTP_XFER_SEND_ERROR,
TFTP_XFER_RECV_ERROR,
TFTP_XFER_READ_ERROR,
TFTP_XFER_WRITE_ERROR,
TFTP_XFER_BAD_DATA,
TFTP_XFER_SIZE_EXCEEDED,
TFTP_XFER_PEER_ERROR
};
struct tftp_xfer_result {
enum tftp_xfer_status status;
uintmax_t bytes;
/* Caller-owned control or input packet storage. */
const struct tftphdr *packet;
int packet_len;
int error;
uint16_t last_block;
};
/*
* The transport callbacks keep packet I/O, timeout implementation, tracing,
* and error reporting local to the client or daemon. recv() is responsible
* for its own timeout mechanism. retry_enter() supplies its jump buffer to
* that mechanism, and is called again after it transfers control there.
*/
struct tftp_xfer_ops {
int (*send)(void *, const void *, int);
int (*recv)(void *, void *, int);
void (*received)(void *, const struct tftphdr *, int);
void (*retry_enter)(void *, sigjmp_buf *, bool);
void (*retry_leave)(void *);
void (*wait_begin)(void *);
};
/*
* The file I/O adapter. The transfer engine owns the protocol state, while
* the adapter can pipeline file I/O independently. A read window remains
* valid until read_release() and a write packet remains reserved until
* write_publish(). write_finish() is called after draining only the final
* receive window and before its ACK. All callbacks return -1 and set errno
* on failure, except for callbacks declared void. write_reserve() must
* provide room for a TFTP header and xfer->blocksize bytes of data.
*/
struct tftp_xfer_io_ops {
int (*read_window)(void *, unsigned int *, bool *);
struct tftphdr *(*read_packet)(void *, unsigned int);
int (*read_length)(void *, unsigned int);
void (*read_release)(void *);
struct tftphdr *(*write_reserve)(void *);
int (*write_publish)(void *, int);
int (*write_drain)(void *);
int (*write_finish)(void *);
};
struct tftp_xfer {
/* Negotiated maximum data bytes in each DATA packet. */
unsigned int blocksize;
/* Negotiated number of DATA packets acknowledged as a window. */
unsigned int windowsize;
/* Maximum total DATA bytes accepted during a receive transfer. */
uintmax_t max_bytes;
/* Block number to use after the 16-bit sequence number wraps. */
uint16_t rollover;
/* Resend a received OACK by retransmitting the current send window. */
bool resend_oack;
/* Storage used for incoming control packets during a send transfer. */
void *control;
/* Size of control, in bytes. */
int control_size;
/* Caller state passed to every transport callback. */
void *context;
/* Transport callbacks for sending, receiving, retries, and tracing. */
const struct tftp_xfer_ops *ops;
/* Caller state passed to every file I/O callback. */
void *io_context;
/* File I/O callbacks used to supply or consume DATA packets. */
const struct tftp_xfer_io_ops *io_ops;
};
/*
* Send a file after any request or OACK exchange is complete.
*/
void tftp_xfer_send(const struct tftp_xfer *, struct tftp_xfer_result *);
/*
* Receive a file after any request or OACK exchange is complete.
* input is caller-owned storage, separate from the I/O adapter, with
* a capacity of at least xfer->blocksize + 4 (+5 if MSG_TRUNC is not
* supported); received data is validated and copied to the adapter's
* reserved storage.
*
* input must not overlap initial_reply and must remain valid through any use
* of result.packet. initial_reply, when supplied, is sent before waiting
* for DATA 1 (typically OACK or ACK 0). initial_packet is DATA 1 that the
* request exchange has already received.
*
* initial_reply and initial_packet are freed after they are consumed,
* in which case their pointers are set to NULL.
*/
void tftp_xfer_recv(const struct tftp_xfer *xfer,
struct tftphdr *input, int input_size,
struct tftphdr **initial_reply,
int initial_reply_len,
struct tftphdr **initial_packet,
int initial_packet_len,
struct tftp_xfer_result *result);
#endif /* TFTP_XFER_H */
tftp-hpa-7.2+20261013/common/tftp.h 0000664 0000000 0000000 00000005372 15263245305 0016431 0 ustar 00root root 0000000 0000000 /* SPDX-License-Identifier: BSD-3-Clause-UC */
/* Copyright (c) 2026 H. Peter Anvin */
/*
* This header avoids relying on from the system.
*/
#ifndef TFTP_TFTP_H
#define TFTP_TFTP_H
#include "config.h"
#include "common/clock.h"
/* TFTP packet type */
enum tftp_opcode {
NULL_OP, /* undefined opcode */
RRQ, /* read request */
WRQ, /* write request */
DATA, /* data packet */
ACK, /* data acknowledgement */
ERROR, /* error, terminate transfer */
OACK, /* option acknowledgement */
PTYPE_CNT /* number of defined packet types */
};
/* TFTP ERROR failure code */
enum tftp_error {
EUNDEF, /* not defined/generic error */
ENOTFOUND, /* file not found */
EACCESS, /* access violation */
ENOSPACE, /* disk full or allocation exceeded */
EBADOP, /* illegal TFTP operation */
EBADID, /* unknown transfer ID */
EEXISTS, /* file already exists */
ENOUSER, /* no such user */
EOPTNEG, /* option negotiation failure */
ETYPE_CNT /* number of defined errors */
};
struct tftphdr {
uint16_t th_opcode;
union tftphdr_altfmt {
uint16_t thdr_block;
char thdr_stuff[2];
} thdr_second;
char th_data[];
};
#define th_block thdr_second.thdr_block
#define th_code th_block
#define th_stuff thdr_second.thdr_stuff
#define th_msg th_data
/* Range of possible block sizes (see RFC 1350 and RFC 2348) */
#define MIN_SEGSIZE 8 /* minimum permitted by spec */
#define SEGSIZE 512 /* blksize default (if not negotiated) */
#define MAX_SEGSIZE 65464 /* maximum permitted by spec */
/* TFTP default port */
#define TFTP_IP_PORT 69
/* Known protocol options. */
/* Keep this in sync with enum protocol_options in common/tftp.h. */
enum protocol_option_enum {
PO_BLKSIZE,
PO_BLKSIZE2,
PO_COOKIE,
PO_ROLLOVER,
PO_TIMEOUT,
PO_TSIZE,
PO_UTIMEOUT,
PO_WINDOWSIZE,
PO_NUM_OPTS
};
/* Maximum size of a TFTP request cookie */
#define TFTP_MAX_COOKIE 255
/* Maximum, default and minimum timeouts (s and us) */
#define MIN_TIMEOUT_SEC 1
#define DEF_TIMEOUT_SEC 1
#define MAX_TIMEOUT_SEC 255
#define MIN_TIMEOUT 10000UL
#define DEF_TIMEOUT (DEF_TIMEOUT_SEC * USEC_PER_SEC)
#define MAX_TIMEOUT (MAX_TIMEOUT_SEC * USEC_PER_SEC)
/* Number of attempts to send each packet */
#define TRIES 6
#define TIMEOUT_LIMIT ((1 << TRIES)-1)
#endif /* TFTP_TFTP_H */
tftp-hpa-7.2+20261013/common/tftpsubs.c 0000664 0000000 0000000 00000021013 15263245305 0017307 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*/
#include "config.h"
#include "options.h"
#include "tftpsubs.h"
#include "pollset.h"
#include "clock.h"
#define TFTP_SOCKET_BUFFER_MIN (256U * 1024U)
#define TFTP_SOCKET_BUFFER_MAX (4U * 1024U * 1024U)
#define TFTP_SOCKET_BUFFER_WINDOWS 2
/* A somewhat conservative estimate for all packet overhead */
#define TFTP_SOCKET_BUFFER_OVERHEAD 256
void tftp_set_socket_buffers(int fd, unsigned int blocksize,
unsigned int windowsize, bool is_send)
{
#if defined(SO_SNDBUF) && defined(SO_RCVBUF)
int whichbuf = is_send ? SO_SNDBUF : SO_RCVBUF;
size_t packetsize = (size_t)blocksize + TFTP_SOCKET_BUFFER_OVERHEAD;
unsigned int buffersize;
buffersize = windowsize * packetsize * TFTP_SOCKET_BUFFER_WINDOWS;
if (buffersize > TFTP_SOCKET_BUFFER_MAX)
buffersize = TFTP_SOCKET_BUFFER_MAX;
if (buffersize <= TFTP_SOCKET_BUFFER_MIN)
return;
setsockint(fd, SOL_SOCKET, whichbuf, buffersize);
#else
(void)fd;
(void)blocksize;
(void)windowsize;
(void)is_send;
#endif
}
#ifndef MSG_DONTWAIT
static int set_socket_nonblock(int fd, bool flag)
{
int socket_flags;
#if defined(HAVE_FCNTL) && (O_NONBLOCK != 0)
socket_flags = fcntl(fd, F_GETFL, 0);
if (socket_flags < 0)
return -1;
if (flag)
socket_flags |= O_NONBLOCK;
else
socket_flags &= ~O_NONBLOCK;
return fcntl(fd, F_SETFL, socket_flags);
#else
socket_flags = flag ? 1 : 0;
return ioctl(fd, FIONBIO, &socket_flags);
#endif
}
#endif
/*
* Try to get the MTU of a connected socket, adjusted to account
* for TFTP overhead.
*/
unsigned int tftp_max_blksize(int fd, const union sock_addr *sa)
{
int mtu;
if (xopt.blksize <= 0) {
int adjust = xopt.blksize;
mtu = -1;
errno = 0;
switch (sa->sa.sa_family) {
case AF_INET:
adjust -= 20 + 8 + 4;
#ifdef IP_MTU
mtu = getsockint(fd, IPPROTO_IP, IP_MTU);
#endif
break;
#ifdef HAVE_IPV6
case AF_INET6:
adjust -= 40 + 8 + 4;
#ifdef IPV6_MTU
mtu = getsockint(fd, IPPROTO_IPV6, IPV6_MTU);
#endif
break;
#endif
default: /* What is this?! */
break;
}
/* If querying the MTU failed, guess Ethernet */
if (errno || mtu < 0)
mtu = 1500;
mtu += adjust;
/* Don't allow MTU-based size to drop below SEGSIZE */
if (mtu < SEGSIZE)
mtu = SEGSIZE;
} else {
mtu = xopt.blksize; /* Absolute */
/* Don't allow dropping below MIN_SEGSIZE */
if (mtu < MIN_SEGSIZE)
mtu = MIN_SEGSIZE;
}
/* Obviously cannot be beyond MAX_SEGSIZE */
if (mtu > MAX_SEGSIZE)
mtu = MAX_SEGSIZE;
return mtu;
}
/*
* Wrappers for getsockopt() for the case where the option is an int.
*/
int getsockint(int sockfd, int level, int optname)
{
int val = -1;
socklen_t optlen = sizeof val;
if (getsockopt(sockfd, level, optname, &val, &optlen) ||
(size_t)optlen != sizeof val)
return -1;
return val;
}
/*
* Receive a packet with a synchronous timeout. The remaining timeout is
* updated after interrupted polls and discarded packets so a receive attempt
* cannot extend its deadline.
*/
int tftp_recv_time(int s, void *rbuf, int len, unsigned int flags,
struct sockaddr *from, socklen_t *fromlen,
uintmax_t *timeout_us_p)
{
uintmax_t t0, dt;
int rv, err = errno;
uintmax_t timeout_us = *timeout_us_p;
uintmax_t timeout_left;
struct pollset *set = pollset_add(NULL, s);
t0 = clock_us();
timeout_left = timeout_us;
do {
do {
rv = pollset_poll(set, POLLSET_IN, timeout_left);
err = errno;
dt = clock_us() - t0;
*timeout_us_p = timeout_left =
(dt >= timeout_us) ? 1 : (timeout_us - dt);
} while (rv == -1 && err == EINTR);
if (rv == 0) {
err = ETIMEDOUT;
rv = -1;
break;
}
#ifdef MSG_DONTWAIT
rv = recvfrom(s, rbuf, len, flags | MSG_DONTWAIT, from, fromlen);
err = errno;
#else
if (set_socket_nonblock(s, true) < 0) {
err = errno;
rv = -1;
break;
}
rv = recvfrom(s, rbuf, len, flags, from, fromlen);
err = errno;
if (set_socket_nonblock(s, false) < 0 && rv >= 0) {
err = errno;
rv = -1;
}
#endif
} while (rv < 0 && (E_WOULD_BLOCK(err) || err == EINTR));
pollset_free(&set);
if (rv < 0)
errno = err;
return rv;
}
int pick_port_bind(int sockfd, union sock_addr *myaddr)
{
if (xopt.portrange_from) {
uint16_t port, firstport;
port = firstport = xopt.portrange_from
+ random_u32() %
((uint16_t)(xopt.portrange_to - xopt.portrange_from) + 1);
do {
sa_set_port(myaddr, htons(port));
if (likely(!bind(sockfd, &myaddr->sa, SOCKLEN(myaddr))))
return 0;
/* Keep trying until a free port is found */
port++;
if (port > xopt.portrange_to)
port = xopt.portrange_from;
} while (port != firstport);
return -1; /* Failed to allocate a port */
} else {
/* Let the kernel pick. */
sa_set_port(myaddr, 0);
return bind(sockfd, &myaddr->sa, SOCKLEN(myaddr));
}
}
#ifdef HAVE_IPV6
bool is_numeric_ipv6(const char *p)
{
/* A numeric IPv6 address consist at least of 2 ':' and
* it may have sequences of hex-digits and maybe contain
* a '.' from a IPv4 mapped address and maybe is enclosed in []
* we do not check here, if it is a valid IPv6 address
* only if is something like a numeric IPv6 address or something else
*/
int colon = 0;
int dot = 0;
bool bracket = false;
char c;
if (!p)
return false;
if (*p == '[') {
bracket = true;
p++;
}
while ((c = *p++) && c != ']') {
switch (c) {
case ':':
colon++;
break;
case '.':
dot++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
break;
default:
return false; /* Invalid character */
}
}
if (colon < 2 || colon > 7)
return false;
if (dot) {
/* An IPv4-mapped address in dot-quad form will have 3 dots */
if (dot != 3)
return false;
/* The IPv4-mapped address takes the space of one colon */
if (colon > 6)
return false;
}
/* If bracketed, must be closed, and vice versa */
if (bracket ^ (c == ']'))
return false;
/* Otherwise, assume we're okay */
return true;
}
/* strip [] from numeric IPv6 addreses */
char *strip_address(char *addr)
{
char *p;
if (is_numeric_ipv6(addr) && (*addr == '[')) {
p = addr + strlen(addr);
p--;
if (*p == ']') {
*p = 0;
addr++;
}
}
return addr;
}
#endif
/*
* Get a descriptor to /dev/null. If none is available, open one.
* If the descriptor comes back as < 3, do it again (backfill closed
* standard file descriptors.)
*/
static int nullfd = -2;
static void close_nullfd(void)
{
if (nullfd >= 0)
close(nullfd);
}
int get_nullfd(void)
{
if (nullfd > -1)
return nullfd;
while (nullfd < 3) {
nullfd = open(_PATH_DEVNULL, O_RDWR);
if (nullfd < 0)
return nullfd;
}
atexit(close_nullfd);
#ifdef FD_CLOEXEC
{
int flags = fcntl(nullfd, F_GETFL, 0);
if (flags >= 0) {
flags |= FD_CLOEXEC;
fcntl(nullfd, F_SETFL, flags);
}
}
#endif
return nullfd;
}
/*
* Similar to strcasecmp() but only for ASCII, and returns true on match
*/
bool ascii_strncaseeq(const char *s1, const char *s2, size_t n)
{
unsigned char c1, cx;
while (n--) {
c1 = *s1++;
cx = c1 ^ *s2++;
if (unlikely(cx)) {
if (cx != 0x20)
return false;
if ((unsigned char)((c1 | cx) - 'a') > (unsigned char)('z' - 'a'))
return false;
}
if (!c1)
return true;
}
return true;
}
bool ascii_strcaseeq(const char *s1, const char *s2)
{
return ascii_strncaseeq(s1, s2, SIZE_MAX);
}
tftp-hpa-7.2+20261013/common/tftpsubs.h 0000664 0000000 0000000 00000017504 15263245305 0017326 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1993
* The Regents of the University of California. All rights reserved.
* Copyright (c) 2026 H. Peter Anvin
*/
#ifndef TFTPSUBS_H
#define TFTPSUBS_H
#include "config.h"
#include "common/tftp.h"
extern const char *_progname;
extern pid_t _progpid;
void set_progname(const char *); /* main() should pass argv[0] here */
void post_fork(void); /* Invoke in child after fork() */
extern const char version_string[];
void print_configuration(FILE *);
extern void (*out_of_memory)(void); /* Optional out of memory handler */
MALLOC_FUNC(1) void *xmalloc(size_t);
CALLOC_FUNC(1,2) void *xcalloc(size_t, size_t);
REALLOC_FUNC(2) void *xrealloc(void *, size_t);
NEWBUF_FUNC char *xstrdup(const char *);
MALLOC_FUNC(2) void *xmemdup(const void *, size_t);
static inline void xfree(void *ptr)
{
/* This is paranoia: free() is supposed to handle NULL already */
if (ptr)
free(ptr);
}
/*
* Allocates a buffer for the given pointer, for xnewn() with an array count.
*/
#define xnewn(ptr,n) \
do { \
void **pp = (void **)&(ptr); \
void *p = xcalloc(n, sizeof *(ptr)); \
*pp = p; \
} while (0)
#define xnew(ptr) xnewn(ptr,1)
/*
* Frees a value and sets the corresponding pointer to NULL.
* This blindly assumes all data pointers have the same representation;
* otherwise this would require using typeof().
*/
#define xdelete(_ptr) \
do { \
void **_pp = (void **)&(_ptr); \
void *_p = *_pp; \
if (_p) { \
*_pp = NULL; \
free(_p); \
} \
} while (0)
/*
* Equivalent, but it takes a pointer to a pointer which might be NULL
* itself.
*/
#define xdeletep(_ptrp) \
do { \
void **_pp = (void **)(_ptrp); \
if (_pp) { \
void *_p = *_pp; \
if (_p) { \
*_pp = NULL; \
free(_p); \
} \
} \
} while (0)
/*
* Clears a buffer based on its type
*/
#define xzeron(ptr,n) memset((ptr), 0, (n)*sizeof *(ptr))
#define xzero(var) xzeron(&(var),1)
/*
* Error checking versions of [v]asprintf()
*/
PRINTF_FUNC(2,3) int xasprintf(char **strp, const char *fmt, ...);
PRINTF_FUNC(2,0) int xvasprintf(char **strp, const char *fmt, va_list ap);
/*
* Number-parsing functions with validation and limit checking
*/
#define BAD_NUM TYPE_MAX(uintmax_t)
uintmax_t parse_uint(const char *arg, uintmax_t lo, uintmax_t hi);
#ifndef HAVE_RANDOM
static inline long random(void)
{
return rand();
}
static inline void srandom(unsigned int seed)
{
return srand(seed);
}
#endif
void random_init(void);
extern uint32_t (*random_u32)(void);
/* ... these might be made fancier at some point ... */
static inline void random_post_fork_parent(void)
{
/* Advance the PRNG at least once per client */
(void)random();
}
static inline void random_post_fork_child(void)
{
}
union sock_addr {
struct sockaddr sa;
struct sockaddr_in si;
#ifdef HAVE_IPV6
struct sockaddr_in6 s6;
#endif
};
#define SOCKLEN(sock) \
(((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
(sizeof(struct sockaddr_in)) : \
(sizeof(union sock_addr)))
#ifdef HAVE_IPV6
#define SOCKPORT(sock) \
(((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
((union sock_addr*)sock)->si.sin_port : \
((union sock_addr*)sock)->s6.sin6_port)
#else
#define SOCKPORT(sock) \
(((union sock_addr*)sock)->si.sin_port)
#endif
#ifdef HAVE_IPV6
#define SOCKADDR_P(sock) \
(((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
(void *)&((union sock_addr*)sock)->si.sin_addr : \
(void *)&((union sock_addr*)sock)->s6.sin6_addr)
#else
#define SOCKADDR_P(sock) \
((void *)&((union sock_addr*)sock)->si.sin_addr)
#endif
#ifdef HAVE_IPV6
bool is_numeric_ipv6(const char *);
char *strip_address(char *);
#else
#define is_numeric_ipv6(a) false
#define strip_address(a) (a)
#endif
static inline int sa_set_port(union sock_addr *s, uint16_t port)
{
switch (s->sa.sa_family) {
case AF_INET:
s->si.sin_port = port;
break;
#ifdef HAVE_IPV6
case AF_INET6:
s->s6.sin6_port = port;
break;
#endif
default:
return -1;
}
return 0;
}
void tftp_set_socket_buffers(int, unsigned int, unsigned int, bool);
int tftp_recv_time(int, void *, int, unsigned int, struct sockaddr *,
socklen_t *, uintmax_t *);
const char *net_family(sa_family_t);
char *net_address(const struct sockaddr *, socklen_t);
unsigned int tftp_max_blksize(int fd, const union sock_addr *sa);
bool parse_blocksize_arg(const char *str, unsigned int minimum);
/*
* Wrappers for get/setsockopt() for the case where the option is an int.
*/
int getsockint(int sockfd, int level, int optname);
static inline int setsockint(int sockfd, int level, int optname,
const int optval)
{
return setsockopt(sockfd, level, optname, &optval, sizeof(optval));
}
int pick_port_bind(int sockfd, union sock_addr *myaddr);
int get_nullfd(void);
static inline int tftp_sigmask(int how, const sigset_t *set, sigset_t *oset)
{
#ifdef HAVE_PTHREAD_SIGMASK
return pthread_sigmask(how, set, oset);
#else
int rv;
do {
rv = sigprocmask(how, set, oset) ? errno : 0;
} while (rv == EINTR);
return rv;
#endif
}
/*
* Functions similar to , but valid only for the ASCII range.
* These functions can be used when processing the protocol data, as
* opposed to arbitrary strings in order in order to avoid the overhead
* (and potential problems!) of locale-aware functions.
*/
static inline unsigned char ascii_digitval(unsigned char c)
{
return c - '0';
}
static inline bool ascii_isdigit(unsigned char c)
{
return ascii_digitval(c) <= 9;
}
static inline unsigned char ascii_tolower(unsigned char c)
{
if ((unsigned char)(c - 'A') <= (unsigned char)('Z' - 'A'))
c += 'a' - 'A';
return c;
}
bool ascii_strcaseeq(const char *s1, const char *s2);
bool ascii_strncaseeq(const char *s1, const char *s2, size_t n);
/*
* Convenience wrapper around sigaction()
*/
#ifndef HAVE_SIGHANDLER_T
typedef void (*sighandler_t)(int);
#endif
int tftp_signal(int, sighandler_t, int);
/*
* A conservative estimate of the maximum number of decimal digits
* that can represent a certain unsigned integer type
*/
#define DIGIT_SPACE(x) ((sizeof(x)*5+1) >> 1)
/*
* Packet type and error name functions, for printing messages.
* packet_type() and error_msg() return a pointer into static memory;
* errpkt_to_string() allocates a string in heap storage.
*
* If error_msg() is passed a negative value, then it is assumed to be
* -errno, and the string is passed to strerror().
*/
const char *error_msg(int err);
char *errpkt_to_string(const struct tftphdr *tp, int n);
int make_errpacket(struct tftphdr **tpp, int error, const char *msg);
extern const char * const packet_types[PTYPE_CNT];
extern const char * const errmsgs[ETYPE_CNT];
static inline const char *packet_type(uint16_t opcode)
{
if (opcode >= PTYPE_CNT)
return "unknown";
else
return packet_types[opcode];
}
#endif
tftp-hpa-7.2+20261013/common/xalloc.c 0000664 0000000 0000000 00000002350 15263245305 0016722 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* xalloc.c
*
* Simple error-checking memory allocation functions
*
*/
#include "xalloc.h"
#include "config.h"
#include "tftpsubs.h"
void (*out_of_memory)(void) = NULL;
noreturn void xalloc_out_of_memory(void)
{
if (out_of_memory)
out_of_memory();
/* If out_of_memory() returns and/or is not set */
perror(_progname);
while (1)
exit(EX_OSERR);
}
void *xmalloc(size_t size)
{
/* Use calloc() in the interest of safety */
return xcalloc(1,size);
}
void *xcalloc(size_t n, size_t size)
{
if (!n || !size)
n = size = 1; /* Avoid undefined behavior 0-byte allocation */
return check_null(calloc(n,size));
}
void *xrealloc(void *p, size_t newsize)
{
/* This is paranoia: realloc() is supposed to handle NULL */
if (!p)
return xmalloc(newsize);
if (newsize == 0)
newsize = 1; /* Avoid undefined behavior 0-byte allocation */
return check_null(realloc(p, newsize));
}
char *xstrdup(const char *s)
{
return check_null(strdup(s));
}
void *xmemdup(const void *p, size_t n)
{
char *q = xmalloc(n);
return memcpy(q, p, n);
}
tftp-hpa-7.2+20261013/common/xalloc.h 0000664 0000000 0000000 00000001121 15263245305 0016722 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* xalloc.h
*
* Simple error-checking allocation functions - internal header
*
*/
#ifndef TFTP_XALLOC_H
#define TFTP_XALLOC_H
#include "config.h"
#include "tftpsubs.h"
extern void (*out_of_memory)(void);
noreturn void xalloc_out_of_memory(void);
/* This function is used to check for memory allocation failure (only) */
static inline void *check_null(void *p)
{
if (!p) {
xalloc_out_of_memory();
abort();
}
return p;
}
#endif /* TFTP_XALLOC_H */
tftp-hpa-7.2+20261013/common/xasprintf.c 0000664 0000000 0000000 00000003412 15263245305 0017456 0 ustar 00root root 0000000 0000000 /*
* xvasprintf(), xasprintf()
*
* Error-checking versions of [v]asprintf()
*/
#include "xalloc.h"
#ifdef HAVE_VASPRINTF
int xvasprintf(char **strp, const char *fmt, va_list ap)
{
int len;
len = vasprintf(strp, fmt, ap);
check_null(*strp);
return len;
}
int xasprintf(char **strp, const char *fmt, ...)
{
va_list ap;
int len;
va_start(ap, fmt);
len = vasprintf(strp, fmt, ap);
va_end(ap);
check_null(*strp);
return len;
}
#else
int xvasprintf(char **strp, const char *fmt, va_list ap)
{
size_t buf_size;
int len;
va_list ap2;
char *str;
va_copy(ap2, ap);
len = vsnprintf(NULL, 0, fmt, ap2);
va_end(ap2);
str = NULL;
if (len >= 0) {
/* Properly working vsnprintf() */
buf_size = len + 1;
} else {
/* Old, broken vsnprintf() */
buf_size = BUFSIZ; /* As good as any guess? */
}
for (;;) {
str = xrealloc(str, buf_size);
va_copy(ap2, ap);
len = vsnprintf(str, buf_size, fmt, ap2);
va_end(ap2);
if (likely((unsigned int)len < buf_size))
break; /* Good! */
if (buf_size >= INT_MAX) {
xfree(str);
xalloc_out_of_memory(); /* WHAT THE HELL... */
abort();
}
buf_size <<= 1;
if (buf_size > INT_MAX)
buf_size = INT_MAX;
}
/* Give a little bit of a slack before bothering with realloc() */
if (unlikely(buf_size > (size_t)len + 4*sizeof(void *)))
str = xrealloc(str, (size_t)len + 1);
*strp = str;
return len;
}
int xasprintf(char **strp, const char *fmt, ...)
{
va_list ap;
int len;
va_start(ap, fmt);
len = xvasprintf(strp, fmt, ap);
va_end(ap);
return len;
}
#endif
tftp-hpa-7.2+20261013/config.h 0000664 0000000 0000000 00000022460 15263245305 0015426 0 ustar 00root root 0000000 0000000 /* -*- c -*- ------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2001-2025 H. Peter Anvin - All Rights Reserved
* Copyright (C) 2026 H. Peter Anvin
*
* ----------------------------------------------------------------------- */
/*
* config.h
*
* Sets up a common baseline environment, based on "autoconf" findings...
*/
#ifndef CONFIG_H
#define CONFIG_H 1
/* Feature enables for specific environments */
#ifdef __APPLE__
#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1070
#define __APPLE_USE_RFC_3542 1
#endif
#endif
/* Must be included before we include any system headers! */
#include "config/config.h" /* autogenerated configuration header */
/* Standard includes */
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_SYS_TYPES_H
#include
#endif
#ifdef HAVE_SYS_STAT_H
#include
#endif
#ifdef HAVE_STRINGS_H
#include
#endif
#ifdef HAVE_UNISTD_H
#include
#endif
#ifdef HAVE_SYS_TIME_H
#include
#endif
#ifdef HAVE_GRP_H
#include
#endif
#ifdef HAVE_FCNTL_H
#include
#endif
#if !defined(HAVE_POLL) && !defined(HAVE_PPOLL)
#undef HAVE_POLL_H
#endif
#ifdef HAVE_POLL_H
#include
#elif defined(HAVE_SYS_SELECT_H)
#include
#endif
#ifdef HAVE_SYS_IOCTL_H
#include
#endif
#ifdef HAVE_SYS_SOCKET_H
#include
#else
#ifdef HAVE_WINSOCK2_H
#include
#else
#ifdef HAVE_WINSOCK_H
#include
#endif
#endif
#endif
#ifdef HAVE_NETDB_H
#include
#endif
#ifdef HAVE_WCHAR_H
#include
#endif
#ifdef HAVE_WCTYPE_H
#include
#endif
#ifdef HAVE_LOCALE_H
#include
#endif
#ifdef HAVE_GETOPT_LONG
#include
#else
#include "lib/getopt.h"
#endif
#ifdef HAVE_PATHS_H
#include
#endif
#ifndef _PATH_DEVNULL
#if defined(_WIN32) && !defined(__CYGWIN__)
#define _PATH_DEVNULL "\\\\.\\NUL"
#else
#define _PATH_DEVNULL "/dev/null"
#endif
#endif
/* Test for EAGAIN/EWOULDBLOCK */
#ifdef EAGAIN
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
#define E_WOULD_BLOCK(x) ((x) == EAGAIN || (x) == EWOULDBLOCK)
#else
#define E_WOULD_BLOCK(x) ((x) == EAGAIN)
#endif
#else
#define E_WOULD_BLOCK(x) ((x) == EWOULDBLOCK)
#endif
/* Some broken systems care about text versus binary, but
real Unix systems don't... */
#if !HAVE_DECL_O_TEXT
#define O_TEXT 0
#endif
#if !HAVE_DECL_O_BINARY
#define O_BINARY 0
#endif
#ifndef HAVE_DECL_O_NONBLOCK
# ifdef HAVE_DECL_O_NDELAY
# define O_NONBLOCK O_NDELAY
# else
# define O_NONBLOCK 0
# endif
#endif
/* A lot of this is old BSD code. Some newer systems don't approve. */
/* socklen_t */
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
/* sa_family_t */
#ifndef HAVE_SA_FAMILY_T
/* This isn't safe to use in a structure; for that, need more smarts */
typedef unsigned int sa_family_t;
#endif
/* sysexits.h */
#ifdef HAVE_SYSEXITS_H
#include
#else
#define EX_USAGE 64 /* command line usage error */
#define EX_DATAERR 65 /* data format error */
#define EX_NOINPUT 66 /* cannot open input */
#define EX_NOUSER 67 /* addressee unknown */
#define EX_NOHOST 68 /* host name unknown */
#define EX_UNAVAILABLE 69 /* service unavailable */
#define EX_SOFTWARE 70 /* internal software error */
#define EX_OSERR 71 /* system error (e.g., can't fork) */
#define EX_OSFILE 72 /* critical OS file missing */
#define EX_CANTCREAT 73 /* can't create (user) output file */
#define EX_IOERR 74 /* input/output error */
#define EX_TEMPFAIL 75 /* temp failure; user is invited to retry */
#define EX_PROTOCOL 76 /* remote error in protocol */
#define EX_NOPERM 77 /* permission denied */
#define EX_CONFIG 78 /* configuration error */
#endif
/* If we don't have sigsetjmp() et all, setjmp() will have to do */
#ifndef HAVE_SIGSETJMP
#define sigsetjmp(x,y) setjmp(x)
#define siglongjmp(x,y) longjmp(x,y)
#define sigjmp_buf jmp_buf
#endif
#ifndef HAVE_STPCPY
char *stpcpy(char *dst, const char *src); /* In lib/stpcpy.c */
#endif
#ifndef HAVE_MEMPCPY
static inline void *mempcpy(void *dst, const void *src, size_t n)
{
return memcpy(dst, src, n) + n;
}
#endif
/* Various attributes */
#ifndef UNUSED
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
#endif
#ifndef likely
#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#else
#define likely(x) (!!(x))
#endif
#endif
#ifndef unlikely
#ifdef __GNUC__
#define unlikely(x) __builtin_expect(!!(x), 0)
#else
#define unlikely(x) (!!(x))
#endif
#endif
#ifndef PRINTF_FUNC
#ifdef __GNUC__
#define PRINTF_FUNC(fmt,lst) __attribute__((format(printf,fmt,lst)))
#else
#define PRINTF_FUNC(fmt,lst)
#endif
#endif
#ifndef CONST_FUNC
#ifdef __GNUC__
#define CONST_FUNC __attribute__((const))
#else
#define CONST_FUNC
#endif
#endif
#ifndef PURE_FUNC
#ifdef __GNUC__
#define PURE_FUNC __attribute__((pure))
#else
#define PURE_FUNC
#endif
#endif
/* For a malloc()-like function which never returns NULL */
#ifndef MALLOC_FUNC
#ifdef __GNUC__
#define MALLOC_FUNC(x) __attribute__((malloc,returns_nonnull,alloc_size(x)))
#else
#define MALLOC_FUNC(x)
#endif
#endif
/* For a calloc()-like function which never returns NULL */
#ifndef CALLOC_FUNC
#ifdef __GNUC__
#define CALLOC_FUNC(x,y) __attribute__((malloc,returns_nonnull,alloc_size(x,y)))
#else
#define CALLOC_FUNC(x,y)
#endif
#endif
/* For a realloc() function which never returns null */
#ifndef REALLOC_FUNC
#ifdef __GNUC__
#define REALLOC_FUNC(x) __attribute__((returns_nonnull,alloc_size(x)))
#else
#define REALLOC_FUNC(x)
#endif
#endif
/* A function which returns a pointer to a newly allocated buffer, never NULL */
#ifndef NEWBUF_FUNC
#ifdef __GNUC__
#define NEWBUF_FUNC __attribute__((malloc,returns_nonnull))
#else
#define NEWBUF_FUNC
#endif
#endif
/* Inhibit inlining */
#ifndef NOINLINE_FUNC
#ifdef __GNUC__
#define NOINLINE_FUNC __attribute__((noinline))
#else
#define NOINLINE_FUNC
#endif
#endif
/* The max and min values of an integer type (assumes 2's complement) */
#define IS_SIGNED(t) ((t)(-1) < (t)0)
#define TYPE_MKMASK(t,x) ((t)(x) + ((t)(x) - 1))
#define TYPE_MAX(t) TYPE_MKMASK(t, (t)1 << (sizeof(t)*CHAR_BIT-1-IS_SIGNED(t)))
#define TYPE_MIN(t) ((t)~TYPE_MAX(t))
/* If OFF_T_MAX isn't defined */
#ifndef OFF_T_MAX
#define OFF_T_MAX TYPE_MAX(off_t)
#endif
/* netinet/in.h, and possible missing pieces */
#include
/* arpa/inet.h, and possible missing pieces */
#ifdef HAVE_ARPA_INET_H
#include
#endif
#include "common/tftp.h"
/* Prototypes for libxtra functions */
#ifndef HAVE_DAEMON
int daemon(int, int);
#endif
#ifndef HAVE_GETADDRINFO
#ifndef HAVE_STRUCT_ADDRINFO_AI_ADDR
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};
#endif
int getaddrinfo(const char *, const char *, const struct addrinfo *,
struct addrinfo **);
void freeaddrinfo(struct addrinfo *);
const char *gai_strerror(int);
#ifndef EAI_NONAME
#define EAI_NONAME -2 /* NAME or SERVICE is unknown. */
#endif
#ifndef EAI_ADDRFAMILY
#define EAI_ADDRFAMILY -9 /* Address family for NAME not supported. */
#endif
#ifndef EAI_MEMORY
#define EAI_MEMORY -10 /* Memory allocation failure. */
#endif
#ifndef EAI_SYSTEM
#define EAI_SYSTEM -11 /* System error returned in `errno'. */
#endif
#endif
#ifndef AI_CANONNAME
#define AI_CANONNAME 0
#endif
#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG 0
#endif
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 46
#endif
#ifndef HAVE_INET_NTOP
const char *inet_ntop(int, const void *, char *, socklen_t);
#endif
/* If unlocked stdio is unavailable, use normal stdio */
#ifndef HAVE_FREAD_UNLOCKED
# define fread_unlocked(p,s,n,f) fread(p,s,n,f)
#endif
#ifndef HAVE_FWRITE_UNLOCKED
# define fwrite_unlocked(p,s,n,f) fwrite(p,s,n,f)
#endif
#ifndef HAVE_GETC_UNLOCKED
# define getc_unlocked(f) getc(f)
#endif
#ifndef HAVE_PUTC_UNLOCKED
# define putc_unlocked(c,f) putc(c,f)
#endif
#ifndef HAVE_FERROR_UNLOCKED
# define ferror_unlocked(f) ferror(f)
#endif
#ifndef HAVE_FEOF_UNLOCKED
# define feof_unlocked(f) feof(f)
#endif
#ifndef HAVE_FILENO_UNLOCKED
# define fileno_unlocked(f) fileno(f)
#endif
#ifndef HAVE_FFLUSH_UNLOCKED
# define fflush_unlocked(f) fflush(f)
#endif
/* strnlen(): an unoptimized version is small enough to inline */
#ifndef HAVE_STRNLEN
static inline size_t strnlen(const char *str, size_t n)
{
size_t len = 0;
while (len < n) {
if (!str[len])
break;
len++;
}
return len;
}
#endif
/* HAVE_IPV6 as a boolean */
#ifdef HAVE_IPV6
# define WITH_IPV6 1
#else
# define WITH_IPV6 0
#endif
/* Handy macros */
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
#define ARRAY_END(x) (&(x)[ARRAY_SIZE(x)])
#define ARRAY_FOREACH(var,array) \
for ((var) = (array); (var) < ARRAY_END(array); (var)++)
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#endif
tftp-hpa-7.2+20261013/config/ 0000775 0000000 0000000 00000000000 15263245305 0015251 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/config/MCONFIG.in 0000664 0000000 0000000 00000002407 15263245305 0016666 0 ustar 00root root 0000000 0000000 ## -*- makefile -*- ------------------------------------------------------
##
## SPDX-License-Identifier: BSD-3-Clause
##
## Copyright 2001-2007 H. Peter Anvin - All Rights Reserved
##
## -----------------------------------------------------------------------
##
## MCONFIG.in
##
## Basic Makefile definitions
##
# Source and object root
SRCROOT = @SRCROOT@
OBJROOT = @OBJROOT@
# Prefixes
prefix = @prefix@
exec_prefix = @exec_prefix@
# Directory for user binaries
BINDIR = @bindir@
# Man page tree
MANDIR = @mandir@
# System binaries
SBINDIR = @sbindir@
# Data root directory
datarootdir = @datarootdir@
# Binary suffixes
O = @OBJEXT@
X = @EXEEXT@
# Install into alternate root area, e.g. for package generation
INSTALLROOT =
# Link
LN_S = @LN_S@
# Install program
INSTALL = @INSTALL@
INSTALL_PROGRAM = @INSTALL_PROGRAM@
INSTALL_DATA = @INSTALL_DATA@
# Compiler and compiler flags
CC = @CC@
CFLAGS = @CFLAGS@ -I..
# Link flags
LDFLAGS = @LDFLAGS@
# Libraries (client and server)
TFTP_LIBS = ../common/libcommon.a @TFTP_LIBS@
TFTPD_LIBS = ../common/libcommon.a @TFTPD_LIBS@
LIBS = @LIBS@
# Additional library we need to build
LIBOBJS = @LIBOBJS@
# ar and ranlib (for making libraries)
AR = @AR@ cq
RANLIB = @RANLIB@
tftp-hpa-7.2+20261013/configure.ac 0000664 0000000 0000000 00000025401 15263245305 0016274 0 ustar 00root root 0000000 0000000 dnl SPDX-License-Identifier: BSD-3-Clause
dnl
dnl Copyright (c) 2008 Karsten Keil
dnl Copyright (c) 2011-2026 Intel Corporation; Author: H. Peter Anvin
dnl Copyright (C) 1999-2008, 2026 H. Peter Anvin
dnl
dnl Process this file with autoconf 2.71 or later to produce
dnl a configure script.
AC_PREREQ([2.71])
AC_INIT
AC_CONFIG_SRCDIR([MRULES])
AC_PREFIX_DEFAULT([/usr])
AC_CONFIG_AUX_DIR([autoconf/helpers])
AC_CONFIG_MACRO_DIRS([autoconf/m4])
dnl This prevents us from running Wine and thinking we are not
dnl cross-compiling when in fact we are; running Wine here is at
dnl the best very slow and doesn't buy us a single thing at all.
PA_CROSS_COMPILE
dnl Enable any available C extensions
PA_PROG_CC
AC_USE_SYSTEM_EXTENSIONS
dnl C99 is the minimum supported C language and library version.
PA_C_C99_CHECK
dnl Options for debugging and profiling
PA_OPTION_DEBUG
PA_OPTION_PROFILING
dnl Force gcc and gcc-compatible compilers treat signed integers
dnl as 2's complement
PA_ADD_CFLAGS([-fwrapv])
dnl Force gcc and gcc-compatible compilers to not try to optimize
dnl around type punning, which is very common in this code.
PA_ADD_CFLAGS(-fno-strict-aliasing)
dnl Force clang to behave in a predictable manner, in order to make bugs
dnl possible to track down. gcc appears to have this behavior by default.
PA_ADD_CFLAGS([-ftrivial-auto-var-init=zero])
dnl Some environments abuse __STRICT_ANSI__ to disable some
dnl function declarations
PA_ADD_CFLAGS([-U__STRICT_ANSI__])
dnl Don't put things in common if we can avoid it. We don't want to
dnl assume all compilers support common, and this will help find those
dnl problems. This also works around an OSX linker problem.
PA_ADD_CFLAGS([-fno-common])
dnl Tests which may trigger warnings on some compilers
AC_C_CONST
dnl Check now to declare noreturn functions
PA_C_NORETURN
dnl Checks for header files.
AC_CHECK_INCLUDES_DEFAULT
dnl See if we need extra libraries
XTRA=false
AC_SEARCH_LIBS([strerror],[cposix])
AC_CHECK_HEADERS_ONCE(grp.h)
AC_CHECK_HEADERS_ONCE(libgen.h)
AC_CHECK_HEADERS_ONCE(locale.h)
AC_CHECK_HEADERS_ONCE(paths.h)
AC_CHECK_HEADERS_ONCE(poll.h)
AC_CHECK_HEADERS_ONCE(setjmp.h)
AC_CHECK_HEADERS_ONCE(strings.h)
AC_CHECK_HEADERS_ONCE(sysexits.h)
AC_CHECK_HEADERS_ONCE(unistd.h)
AC_CHECK_HEADERS_ONCE(sys/filio.h)
AC_CHECK_HEADERS_ONCE(sys/ioctl.h)
AC_CHECK_HEADERS_ONCE(sys/select.h)
AC_CHECK_HEADERS_ONCE(sys/stat.h)
AC_CHECK_HEADERS_ONCE(sys/time.h)
dnl This is needed on some versions of FreeBSD...
AC_CHECK_HEADERS_ONCE(machine/param.h)
dnl Windows...
PA_ADD_HEADERS(windows.h)
PA_ADD_HEADERS(winsock2.h)
AS_IF([test "x$ac_cv_header_winsock2_h" != xyes],
[PA_ADD_HEADERS(winsock.h)])
PA_ADD_HEADERS(fcntl.h)
PA_ADD_HEADERS(sys/types.h)
PA_ADD_HEADERS(arpa/inet.h)
PA_ADD_HEADERS(sys/socket.h)
PA_ADD_HEADERS(sys/file.h)
PA_ADD_HEADERS(netinet/in.h)
PA_ADD_HEADERS(sys/uio.h)
PA_ADD_HEADERS(netdb.h)
AC_TYPE_PID_T
AC_TYPE_MODE_T
AC_TYPE_SIZE_T
AC_CHECK_TYPES(socklen_t)
AC_CHECK_TYPES(sa_family_t)
AC_TYPE_OFF_T
AC_CHECK_DECLS(OFF_T_MAX)
AC_SEARCH_LIBS(socket, [socket ws2_32 wsock32], ,
[AC_MSG_ERROR(socket library not found)])
PA_ARG_DISABLED([poll],
[use select() instead of poll(): for debugging only], [],
[
AC_CHECK_FUNCS(poll)
AC_CHECK_FUNCS(ppoll)
])
AC_CHECK_FUNCS(fcntl)
AC_CHECK_FUNCS(flock)
AC_CHECK_FUNCS(setsid)
AC_CHECK_FUNCS(recvmsg)
AC_CHECK_FUNCS(ftruncate)
AC_CHECK_FUNCS(openat2)
AC_CHECK_FUNCS(setresuid)
AC_CHECK_FUNCS(setreuid)
AC_CHECK_FUNCS(setresgid)
AC_CHECK_FUNCS(setregid)
AC_CHECK_FUNCS(initgroups)
AC_CHECK_FUNCS(setgroups)
AC_CHECK_TYPES(sighandler_t)
AC_CHECK_TYPES([sigset_t], [],
[AC_MSG_ERROR(sigset_t not found, please send a bug report)])
dnl Solaris 8 has [u]intmax_t but not strtoumax(). How utterly braindamaged.
AC_CHECK_FUNCS(strtoumax)
AC_CHECK_FUNCS(strtoull)
AC_CHECK_FUNCS(random)
AC_CHECK_FUNCS(fread_unlocked)
AC_CHECK_FUNCS(fwrite_unlocked)
AC_CHECK_FUNCS(getc_unlocked)
AC_CHECK_FUNCS(putc_unlocked)
AC_CHECK_FUNCS(ferror_unlocked)
AC_CHECK_FUNCS(feof_unlocked)
AC_CHECK_FUNCS(fileno_unlocked)
AC_CHECK_FUNCS(fflush_unlocked)
AC_CHECK_TYPES(struct timespec)
AC_SEARCH_LIBS(clock_gettime, [rt])
AC_CHECK_FUNCS(clock_gettime)
AC_CHECK_MEMBERS(struct msghdr.msg_control)
AC_CHECK_MEMBERS(struct in_pktinfo.ipi_addr)
AC_CHECK_MEMBERS(struct addrinfo.ai_addr)
AC_CHECK_DECLS([O_NONBLOCK, O_NDELAY, O_BINARY, O_TEXT])
AC_CHECK_DECLS([F_SETLK])
AC_CHECK_DECLS([LOCK_SH, LOCK_EX])
PA_ADD_HEADERS(wctype.h)
PA_ADD_HEADERS(wchar.h)
AC_CHECK_FUNCS(mbrtowc)
AC_CHECK_FUNCS(towlower)
PA_SIGSETJMP
PA_ARG_DISABLED([threads],
[disable threading support: for debugging only], [],
[PA_PTHREAD])
AC_CHECK_FUNCS(pthread_sigmask)
dnl
dnl Get common paths
dnl
SRCROOT=`cd $srcdir && pwd`
OBJROOT=`pwd`
PA_SEARCH_LIBS_AND_ADD(getopt_long, getopt, getopt_long)
PA_SEARCH_LIBS_AND_ADD(getaddrinfo, [nsl resolv])
AS_IF([$pa_add_getaddrinfo],
[AC_SEARCH_LIBS(gethostbyname, [nsl resolv],
[AC_SEARCH_LIBS(herror, [nsl resolv], ,
[AC_MSG_ERROR(herror not found)])],
[AC_MSG_ERROR(gethostbyname not found)])],
[AC_SEARCH_LIBS(freeaddrinfo, [nsl resolv], ,
[AC_MSG_ERROR(getaddrinfo but not freeaddrinfo found)])
AC_SEARCH_LIBS(gai_strerror, [nsl resolv], ,
[AC_MSG_ERROR(getaddrinfo but not gai_strerror found)])])
PA_SEARCH_LIBS_AND_ADD(inet_ntop, [nsl resolv])
AS_IF([$pa_add_inet_ntop],
[AC_SEARCH_LIBS(inet_ntoa, [nsl resolv], ,
[AC_MSG_ERROR(inet_ntoa not found)])])
AC_SEARCH_LIBS(inet_aton, [nsl resolv], ,[AC_MSG_ERROR(inet_aton not found)])
PA_SEARCH_LIBS_AND_ADD(daemon)
AC_SEARCH_LIBS(dup2, , ,[AC_MSG_ERROR(dup2 not found; the bundled ersatz dup2() implementation has been removed as obsolete)])
PA_SEARCH_LIBS_AND_ADD(stpcpy, , stpcpy)
AC_CHECK_FUNCS(mempcpy)
AC_CHECK_FUNCS(strnlen)
AC_CHECK_FUNCS(vasprintf)
AS_IF([$XTRA], [XTRALIBS="$OBJROOT/lib/libxtra.a $XTRALIBS"])
dnl
dnl These libraries apply to the server only
dnl
common_libs="$LIBS"
AC_ARG_VAR([TFTPD_MAX_WINDOWSIZE],
[maximum RFC 7440 windowsize accepted by tftpd (default: 256)])
AS_IF([test -z "$TFTPD_MAX_WINDOWSIZE"], [TFTPD_MAX_WINDOWSIZE=256])
AS_CASE([$TFTPD_MAX_WINDOWSIZE],
[*[!0-9]*|''], [AC_MSG_ERROR([TFTPD_MAX_WINDOWSIZE must be a positive integer])])
AS_IF([test "$TFTPD_MAX_WINDOWSIZE" -lt 1 || test "$TFTPD_MAX_WINDOWSIZE" -gt 32768],
[AC_MSG_ERROR([TFTPD_MAX_WINDOWSIZE must be in the range 1-32768])])
AC_DEFINE_UNQUOTED([MAX_WINDOWSIZE], [$TFTPD_MAX_WINDOWSIZE],
[maximum RFC 7440 windowsize accepted by tftpd])
AC_ARG_VAR([TFTPD_MAX_WINDOWBYTES],
[maximum bytes in an RFC 7440 tftpd window; 0 is unlimited (default: 4194304)])
AS_IF([test -z "$TFTPD_MAX_WINDOWBYTES"], [TFTPD_MAX_WINDOWBYTES=4194304])
AS_CASE([$TFTPD_MAX_WINDOWBYTES],
[*[!0-9]*|''], [AC_MSG_ERROR([TFTPD_MAX_WINDOWBYTES must be a nonnegative integer])])
AC_DEFINE_UNQUOTED([MAX_WINDOWBYTES], [$TFTPD_MAX_WINDOWBYTES],
[maximum bytes in an RFC 7440 tftpd window; zero is unlimited])
AC_CHECK_HEADERS_ONCE([regex.h])
PA_ARG_DISABLED([remap],
[disable regex-based filename remapping], [],
[AS_IF([test x"$ac_cv_header_regex_h" = xyes],
[AC_SEARCH_LIBS(regcomp, [regex rx],
[AC_DEFINE([WITH_REGEX], 1,
[Define if we are compiling with regex filename remapping.])])])])
AC_CHECK_HEADERS_ONCE([sys/capability.h])
AS_IF([test x"$ac_cv_header_sys_capability_h" = xyes],
[AC_SEARCH_LIBS(cap_set_proc, [cap])
AC_CHECK_FUNCS(cap_set_proc)])
TFTPD_LIBS="$LIBS $XTRALIBS"
LIBS="$common_libs"
dnl
dnl These libraries apply to the client only
dnl
AH_TEMPLATE([WITH_READLINE],
[Define if we are compiling with readline/editline command-line editing.])
PA_ARG_DISABLED([readline],
[disable the use of readline command-line editing], [],
[
AC_CHECK_HEADER([readline/readline.h],
[
dnl readline may need libtermcap or somesuch...
AC_SEARCH_LIBS(tputs, [termcap terminfo])
AC_SEARCH_LIBS(readline, [readline history],
[AC_DEFINE(WITH_READLINE)])
AC_CHECK_HEADERS(readline/history.h)
],
[AC_CHECK_HEADER([editline/readline.h],
[
dnl editline may need libtermcap or somesuch...
AC_SEARCH_LIBS(tputs, [termcap terminfo])
AC_SEARCH_LIBS(readline, [edit],
[AC_DEFINE(WITH_READLINE)
AC_DEFINE(HAVE_EDITLINE_READLINE_H, 1,
[Define if readline comes from editline/readline.h.])])
])])
],:)
TFTP_LIBS="$LIBS $XTRALIBS"
LIBS="$common_libs"
dnl
dnl Check for IPV6 and disable-ipv6
dnl
AC_CHECK_MEMBERS(struct sockaddr_in6.sin6_addr)
AC_MSG_CHECKING([for IPv6 support])
PA_ARG_DISABLED([ipv6],
[disable support for IPv6],
[AC_MSG_RESULT(disabled)],
[AS_IF([test x"$ac_cv_member_struct_sockaddr_in6_sin6_addr$ac_cv_member_struct_addrinfo_ai_addr" = xyesyes],
[AC_MSG_RESULT(yes)
AC_DEFINE(HAVE_IPV6, 1, [define if IPv6 support is enabled])
AC_CHECK_MEMBERS(struct in6_pktinfo.ipi6_addr)],
[AC_MSG_RESULT(no)
AC_MSG_WARN([*** we do not have required IPv6 structs - IPv6 will be disabled])])])
AC_SUBST(SRCROOT)
AC_SUBST(OBJROOT)
AC_SUBST(TFTP_LIBS)
AC_SUBST(TFTPD_LIBS)
AC_PROG_LN_S
AC_PROG_RANLIB
dnl
dnl Make sure the install program has an absolute path if it
dnl has a path at all. autoconf doesn't do this "in order
dnl to not pollute the cache." Sigh.
dnl Note: the $ needs to be double-quoted for reasons unknown.
dnl
AC_PROG_INSTALL
[if echo "$INSTALL" | grep '^[^/].*/' > /dev/null 2>&1; then
INSTALL='\${SRCROOT}'/"$INSTALL"
fi]
dnl Support for function garbage collection, LTO, and sanitizers
PA_OPTION_LTO
PA_OPTION_GC
PA_OPTION_SANITIZER
dnl Turn on compiler warnings
dnl LLVM doesn't error out on invalid -W options unless this option is
dnl specified first. Enable this so this script can actually discover
dnl which -W options are possible for this compiler.
PA_ADD_CFLAGS([-Werror=unknown-warning-option])
PA_ARG_ENABLED([werror],
[compile with -Werror to error out on any warning],
[PA_ADD_CFLAGS([-Werror])])
PA_ADD_CFLAGS(-W)
PA_ADD_CFLAGS(-Wall)
PA_ADD_CFLAGS(-Wpedantic)
PA_ADD_CFLAGS(-Wbad-function-cast)
PA_ADD_CFLAGS(-Wc99-c11-compat)
PA_ADD_CFLAGS(-Wc11-c23-compat,,,[PA_ADD_CFLAGS([-Wc11-c2x-compat])])
PA_ADD_CFLAGS(-Wc23-c2y-compat)
PA_ADD_CFLAGS(-Wcast-equal)
PA_ADD_CFLAGS(-Wflex-array-member-not-at-end)
PA_ADD_CFLAGS(-Wframe-larger-than=768)
PA_ADD_CFLAGS(-Wheader-guard)
PA_ADD_CFLAGS(-Winline)
PA_ADD_CFLAGS(-Wjump-misses-init)
PA_ADD_CFLAGS(-Wlogical-op)
PA_ADD_CFLAGS(-Wmissing-declarations)
PA_ADD_CFLAGS(-Wmissing-prototypes)
PA_ADD_CFLAGS(-Wnested-externs)
PA_ADD_CFLAGS(-Wpedantic-ms-format,-Wno-pedantic-ms-format)
PA_ADD_CFLAGS(-Wpointer-arith)
PA_ADD_CFLAGS(-Wshadow)
PA_ADD_CFLAGS(-Wstack-usage=16384)
PA_ADD_CFLAGS(-Wstrict-prototypes)
PA_ADD_CFLAGS(-Wtrigraphs)
PA_ADD_CFLAGS(-Wtrivial-auto-var-init)
PA_ADD_CFLAGS(-Wundef)
PA_ADD_CFLAGS(-Wvla)
PA_ADD_CFLAGS(-Wwrite-strings)
dnl
dnl Test compiler features. On some compilers, this can be affected
dnl by -Werror options, so run this *after* those options are added.
dnl
PA_C_TYPEOF
PA_DEPEND
AC_CONFIG_HEADERS([config/config.h])
AC_CONFIG_FILES([config/MCONFIG])
AC_OUTPUT
tftp-hpa-7.2+20261013/lib/ 0000775 0000000 0000000 00000000000 15263245305 0014552 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/lib/Makefile 0000664 0000000 0000000 00000000642 15263245305 0016214 0 ustar 00root root 0000000 0000000 # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2001-2005 H. Peter Anvin
# Copyright (c) 2024 Intel Corporation; Author: H. Peter Anvin
#
# Extra functions which may not be available everywhere
#
SRCROOT = ..
-include ../config/MCONFIG
include ../MRULES
ifeq ($(LIBOBJS),)
all:
else
all: libxtra.a
endif
install:
libxtra.a: $(LIBOBJS)
-rm -f libxtra.a
$(AR) libxtra.a $(LIBOBJS)
$(RANLIB) libxtra.a
tftp-hpa-7.2+20261013/lib/daemon.c 0000664 0000000 0000000 00000001446 15263245305 0016166 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2007-2008 H. Peter Anvin
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
/*
* daemon.c - "daemonize" a process
*/
#include "config.h"
int daemon(int nochdir, int noclose)
{
int nullfd;
pid_t f;
if (!nochdir) {
if (chdir("/"))
return -1;
}
if (!noclose) {
if ((nullfd = open(_PATH_DEVNULL, O_RDWR)) < 0)
return -1;
if (dup2(nullfd, 0) < 0 ||
dup2(nullfd, 1) < 0 || dup2(nullfd, 2) < 0) {
close(nullfd);
return -1;
}
close(nullfd);
}
f = fork();
if (f < 0)
return -1;
else if (f > 0)
_exit(0);
#ifdef HAVE_SETSID
return setsid();
#else
return 0;
#endif
}
tftp-hpa-7.2+20261013/lib/getaddrinfo.c 0000664 0000000 0000000 00000006540 15263245305 0017211 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2008 Karsten Keil
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
/*
* getaddrinfo.c
*
* Simple version of getaddrinfo()
*
*/
#include "config.h"
extern int errno;
extern int h_errno;
void freeaddrinfo(struct addrinfo *res)
{
if (!res)
return;
if (res->ai_next)
freeaddrinfo(res->ai_next);
if (res->ai_addr)
free(res->ai_addr);
if (res->ai_canonname)
free(res->ai_canonname);
free(res);
}
int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints,
struct addrinfo **res)
{
const struct hostent *host;
struct sockaddr *sa;
int size = 0;
if ((!node) || (!res)) {
errno = EINVAL;
return EAI_SYSTEM;
}
*res = NULL;
/* we do not support service in this version */
if (service) {
errno = EINVAL;
return EAI_SYSTEM;
}
host = gethostbyname(node);
if (!host)
return EAI_NONAME;
if (hints) {
if (hints->ai_family != AF_UNSPEC) {
if (hints->ai_family != host->h_addrtype)
return EAI_ADDRFAMILY;
}
}
*res = malloc(sizeof(struct addrinfo));
if (!*res) {
return EAI_MEMORY;
}
memset(*res, 0, sizeof(struct addrinfo));
(*res)->ai_family = host->h_addrtype;
if (host->h_length) {
if (host->h_addrtype == AF_INET)
size = sizeof(struct sockaddr_in);
#ifdef HAVE_IPV6
else if (host->h_addrtype == AF_INET6)
size = sizeof(struct sockaddr_in6);
#endif
else {
free(*res);
*res = NULL;
return EAI_ADDRFAMILY;
}
sa = malloc(size);
if (!sa) {
free(*res);
*res = NULL;
return EAI_MEMORY;
}
memset(sa, 0, size);
(*res)->ai_addr = sa;
(*res)->ai_addrlen = size;
sa->sa_family = host->h_addrtype;
if (host->h_addrtype == AF_INET) {
if ((size_t)host->h_length > sizeof(((struct sockaddr_in *)sa)->sin_addr)) {
free(sa);
free(*res);
*res = NULL;
return EAI_SYSTEM;
}
memcpy(&((struct sockaddr_in *)sa)->sin_addr, host->h_addr, host->h_length);
}
#ifdef HAVE_IPV6
else {
if ((size_t)host->h_length > sizeof(((struct sockaddr_in6 *)sa)->sin6_addr)) {
free(sa);
free(*res);
*res = NULL;
return EAI_SYSTEM;
}
memcpy(&((struct sockaddr_in6 *)sa)->sin6_addr, host->h_addr, host->h_length);
}
#endif
}
if (host->h_name)
(*res)->ai_canonname = strdup(host->h_name);
/* we only handle the first address entry and do not build a list now */
return 0;
}
const char *gai_strerror(int errcode)
{
const char *s = NULL;
switch(errcode) {
case 0:
s = "no error";
break;
case EAI_MEMORY:
s = "no memory";
break;
case EAI_SYSTEM:
s = strerror(errno);
break;
case EAI_NONAME:
s = hstrerror(h_errno);
break;
case EAI_ADDRFAMILY:
s = "address does not match address family";
break;
default:
s = "unknown error code";
break;
}
return s;
}
tftp-hpa-7.2+20261013/lib/getopt.h 0000664 0000000 0000000 00000000732 15263245305 0016227 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2008 H. Peter Anvin
*/
#ifndef LIB_GETOPT_H
#define LIB_GETOPT_H
extern char *optarg;
extern int optind, opterr, optopt;
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
enum {
no_argument = 0,
required_argument = 1,
optional_argument = 2,
};
int getopt_long(int, char *const *, const char *,
const struct option *, int *);
#endif /* LIB_GETOPT_H */
tftp-hpa-7.2+20261013/lib/getopt_long.c 0000664 0000000 0000000 00000006516 15263245305 0017247 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2008 H. Peter Anvin
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
/*
* getopt_long.c
*
* getopt_long(), or at least a common subset thereof:
*
* - Option reordering is not supported
* - -W foo is not supported
* - First optstring character "-" not supported.
*/
#include "config.h"
char *optarg;
int optind, opterr, optopt;
static struct getopt_private_state {
const char *optptr;
const char *last_optstring;
char *const *last_argv;
} pvt;
static inline const char *option_matches(const char *arg_str,
const char *opt_name)
{
while (*arg_str != '\0' && *arg_str != '=') {
if (*arg_str++ != *opt_name++)
return NULL;
}
if (*opt_name)
return NULL;
return arg_str;
}
int getopt_long(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longindex)
{
const char *carg;
const char *osptr;
int opt;
/* getopt() relies on a number of different global state
variables, which can make this really confusing if there is
more than one use of getopt() in the same program. This
attempts to detect that situation by detecting if the
"optstring" or "argv" argument have changed since last time
we were called; if so, reinitialize the query state. */
if (optstring != pvt.last_optstring || argv != pvt.last_argv ||
optind < 1 || optind > argc) {
/* optind doesn't match the current query */
pvt.last_optstring = optstring;
pvt.last_argv = argv;
optind = 1;
pvt.optptr = NULL;
}
carg = argv[optind];
/* First, eliminate all non-option cases */
if (!carg || carg[0] != '-' || !carg[1])
return -1;
if (carg[1] == '-') {
const struct option *lo;
const char *opt_end = NULL;
optind++;
/* Either it's a long option, or it's -- */
if (!carg[2]) {
/* It's -- */
return -1;
}
for (lo = longopts; lo->name; lo++) {
if ((opt_end = option_matches(carg+2, lo->name)))
break;
}
if (!opt_end)
return '?';
if (longindex)
*longindex = lo-longopts;
if (*opt_end == '=') {
if (lo->has_arg)
optarg = (char *)opt_end+1;
else
return '?';
} else if (lo->has_arg == 1) {
if (!(optarg = argv[optind]))
return '?';
optind++;
}
if (lo->flag) {
*lo->flag = lo->val;
return 0;
} else {
return lo->val;
}
}
if (!pvt.optptr ||
(uintptr_t) (pvt.optptr - carg) > (uintptr_t) strlen(carg)) {
/* Someone frobbed optind, change to new opt. */
pvt.optptr = carg + 1;
}
opt = *pvt.optptr++;
if (opt != ':' && (osptr = strchr(optstring, opt))) {
if (osptr[1] == ':') {
if (*pvt.optptr) {
/* Argument-taking option with attached
argument */
optarg = (char *)pvt.optptr;
optind++;
} else {
/* Argument-taking option with non-attached
argument */
if (argv[optind + 1]) {
optarg = (char *)argv[optind+1];
optind += 2;
} else {
/* Missing argument */
optind++;
return (optstring[0] == ':')
? ':' : '?';
}
}
return opt;
} else {
/* Non-argument-taking option */
/* pvt.optptr will remember the exact position to
resume at */
if (!*pvt.optptr)
optind++;
return opt;
}
} else {
/* Unknown option */
optopt = opt;
if (!*pvt.optptr)
optind++;
return '?';
}
}
tftp-hpa-7.2+20261013/lib/inet_ntop.c 0000664 0000000 0000000 00000002233 15263245305 0016715 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2008 Karsten Keil
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
/*
* inet_ntop.c
*
* Simple version of inet_ntop()
*
*/
#include "config.h"
const char *inet_ntop(int af, const void *src,
char *dst, socklen_t cnt)
{
char *p;
switch(af) {
case AF_INET:
p = inet_ntoa(*((const struct in_addr *)src));
if (p) {
if (cnt <= strlen(p)) {
errno = ENOSPC;
dst = NULL;
} else
strcpy(dst, p);
} else
dst = NULL;
break;
#ifdef HAVE_IPV6
case AF_INET6:
if (cnt < 40) {
errno = ENOSPC;
dst = NULL;
} else {
const struct in6_addr *a = src;
int i;
p = (char *)dst;
/* we do not compress :0: to :: */
for (i = 0; i < 8; i++)
p += sprintf(p, "%x:", ntohs(a->s6_addr16[i]));
p--;
*p = 0;
}
break;
#endif
default:
errno = EAFNOSUPPORT;
dst = NULL;
}
return dst;
}
tftp-hpa-7.2+20261013/lib/stpcpy.c 0000664 0000000 0000000 00000000376 15263245305 0016246 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* stpcpy()
*/
#include "config.h"
char *stpcpy(char *dst, const char *src)
{
size_t len = strlen(src);
memcpy(dst, src, len+1);
return dst+len;
}
tftp-hpa-7.2+20261013/release.sh 0000775 0000000 0000000 00000002314 15263245305 0015763 0 ustar 00root root 0000000 0000000 #!/bin/sh -xe
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2001-2008 H. Peter Anvin
#
# Script for generating a release
#
PACKAGE=tftp-hpa
if [ -z "$1" ]; then
echo "Usage: $0 release-id" 1>&2
exit 1
fi
release="$1"
releasetag=$PACKAGE-$release
releasedir=$PACKAGE-$release
GIT_DIR=`cd "${GIT_DIR-.git}" && pwd`
export GIT_DIR
if [ `git diff --cached | wc -l` -ne 0 ]; then
echo "$0: index not clean" 1>&2
exit 1
fi
if [ x"$release" = x'test' ]; then
release=`cat version`
releasetag=HEAD
releasedir=$PACKAGE-$release
else
echo $release > version
if [ `git diff version | wc -l` -ne 0 ]; then
git add version
git commit -m "Update version for release $release" version
else
git checkout version
fi
rm -f "$GIT_DIR"/refs/tags/$releasetag
git tag -a -m "$releasetag" -f "$releasetag"
fi
here=`pwd`
tmpdir=/var/tmp/release.$$
rm -rf $tmpdir
mkdir -p $tmpdir
cd $tmpdir
mkdir -p $releasedir
git archive --format=tar $releasetag | tar -xf - -C $releasedir
cd $releasedir
make release
rm -f release.sh
cd ..
tar cvvf $releasedir.tar $releasedir
gpg -ab $releasedir.tar
xz -9ek $releasedir.tar
gzip -9 $releasedir.tar
mv -f $releasedir.tar.* $here/..
cd ..
rm -rf $tmpdir
tftp-hpa-7.2+20261013/systemd/ 0000775 0000000 0000000 00000000000 15263245305 0015474 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/systemd/tftp.service 0000664 0000000 0000000 00000002526 15263245305 0020040 0 ustar 00root root 0000000 0000000 [Unit]
Description=tftpd-hpa TFTP Server
Documentation=man:in.tftpd
Requires=tftp.socket
After=network-online.target
[Service]
# --------------------------------------------------------------------------
# Location of tftp files
Environment=TFTPD_HOME=%S/tftpboot
# --------------------------------------------------------------------------
# For a readonly server enable/tweak this
Environment=TFTPD_ACCESS_OPTS="--permissive --read-only"
# --------------------------------------------------------------------------
# For a read/write server enable/tweak this
# Environment=TFTPD_ACCESS_OPTS="--permissive --create --umask 022 --max-upload 1048576"
# ReadWritePaths=%S/tftpboot
# --------------------------------------------------------------------------
# Network tweakables
Environment=TFTPD_NET_OPTS="--blocksize mtu"
# --------------------------------------------------------------------------
User=tftp
ExecStart=/usr/sbin/in.tftpd $TFTPD_NET_OPTS $TFTPD_ACCESS_OPTS --systemd --jail ${TFTPD_HOME}
ProtectHome=yes
ProtectSystem=strict
ProtectHostname=yes
ProtectClock=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
PrivateDevices=yes
PrivateTmp=yes
NoNewPrivileges=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
Also=tftp.socket
tftp-hpa-7.2+20261013/systemd/tftp.socket 0000664 0000000 0000000 00000000174 15263245305 0017665 0 ustar 00root root 0000000 0000000 [Unit]
Description=tftpd-hpa TFTP Server Socket
[Socket]
FreeBind=yes
ListenDatagram=69
[Install]
WantedBy=sockets.target
tftp-hpa-7.2+20261013/systemd/tftp.sysusers 0000664 0000000 0000000 00000000030 15263245305 0020264 0 ustar 00root root 0000000 0000000 u! tftp - "tftp daemon"
tftp-hpa-7.2+20261013/tests/ 0000775 0000000 0000000 00000000000 15263245305 0015146 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/tests/README.md 0000664 0000000 0000000 00000007665 15263245305 0016443 0 ustar 00root root 0000000 0000000 # TFTP Test Suite
This directory contains test scripts for the TFTP client and server implementation.
## test-tftp.sh
A comprehensive shell script that tests bidirectional file transfer between a TFTP client and an ephemeral TFTP server.
### Features
- Starts an ephemeral TFTP server on localhost with a nonstandard port (default: 6969)
- Creates multiple test files of varying sizes and types:
- Small text file
- Medium binary file (10 KB random data)
- Multiline text file
- Large ASCII file (100 lines of numbers)
- Tests **download** operations (client receives files from server)
- Tests **upload** operations (client sends files to server)
- Verifies data integrity by comparing original and transferred files
- Automatically terminates the server after tests complete
- Cleans up all temporary files
### Requirements
- `tftpd` - TFTP server daemon (system or built from this repository)
- `tftp` - TFTP client (system or built from this repository)
- Standard POSIX utilities: `bash`, `diff`, `dd`, `mktemp`, `seq`
### Usage
#### Using binaries from the current tree (default)
```bash
./test-tftp.sh
```
#### Using custom tftpd and tftp binaries
```bash
./test-tftp.sh $objtree/tftpd/tftpd $objtree/tftp/tftp
```
#### Using custom port (default: 6969)
```bash
./test-tftp.sh '' '' 6970
```
### Test Operations
The script performs the following sequence:
1. **Initialization**
- Verifies binaries exist and are executable
- Creates temporary directories for test files and server storage
- Starts tftpd on localhost:PORT
2. **Download Tests** (Client → Receive)
- `small.txt` - Basic text file transfer
- `multiline.txt` - Multi-line text file
- `numbers.txt` - Sequential numbered lines
- `medium.bin` - Binary data transfer (10 KB)
3. **Upload Tests** (Client → Send)
- Same files as download tests
- Server receives and stores files
- Integrity verified by diff
4. **Cleanup**
- Terminates tftpd server
- Removes temporary files and directories
### Output
The script provides colored output for easy reading:
- **[INFO]** - Information messages (yellow)
- **[PASS]** - Successful test results (green)
- **[FAIL]** - Test failures (red)
Example:
```
[INFO] ================================
[INFO] TFTP Client-Server Test Suite
[INFO] ================================
[PASS] Found tftpd at: /usr/sbin/tftpd
[PASS] Found tftp at: /usr/bin/tftp
[INFO] Starting tftpd on 127.0.0.1:6969...
[PASS] tftpd started with PID 12345
[INFO] Running download tests...
[PASS] Download test passed: small.txt
[PASS] Download test passed: multiline.txt
[PASS] All tests passed!
```
### Exit Codes
- `0` - All tests passed
- `1` - One or more tests failed, or setup error
### Notes
- The test server runs with limited privileges (user: nobody)
- Uses ephemeral ports and temporary directories—safe to run multiple instances
- No files are permanently created; all cleanup occurs automatically
- TFTP uses UDP (port 69 by default, or specified PORT)—ensure no firewall blocks the port
### Troubleshooting
#### "tftpd not found"
Build the tftpd from source:
```bash
cd ../
make
./tests/test-tftp.sh ./tftpd/tftpd ./tftp/tftp
```
Or specify the system tftpd:
```bash
./test-tftp.sh /usr/sbin/tftpd /usr/bin/tftp
```
#### Port already in use
Specify a different port:
```bash
./test-tftp.sh /usr/sbin/tftpd /usr/bin/tftp 6971
```
#### Permission denied errors
The script requires:
- Write access to create temporary directories
- Execute permission on tftp and tftpd binaries
- Ability to bind to localhost
#### Transfer timeouts
- Verify firewall doesn't block the UDP port
- Check that the server is actually running: `ps aux | grep tftpd`
- Try with a different port number
## Contributing
To add more tests:
1. Create test files in `create_test_files()` function
2. Add corresponding test functions (e.g., `test_download "myfile"`)
3. Call test functions from `main()`
4. Track pass/fail counts with `((tests_passed++))` / `((tests_failed++))`
tftp-hpa-7.2+20261013/tests/csvlog.pl 0000775 0000000 0000000 00000001565 15263245305 0017012 0 ustar 00root root 0000000 0000000 #!/usr/bin/perl
#
# Create a CSV file out of the timings of a set of test-tftp.sh logs
#
use strict;
my $delta = 0;
if ($ARGV[0] eq '--delta') {
$delta = 1;
shift(@ARGV);
}
my @times = ();
my $nf = 0;
my $nt = 0;
foreach my $f (@ARGV) {
open(my $fh, '<', $f) or die "$0: $f: $!\n";
my $it = 0;
while (defined(my $l = <$fh>)) {
next if ($l !~ /\btime = ([0-9.]+)/);
my $t = $1 + 0.0;
if (!defined($times[$it])) {
$times[$it] = [(0.0) x $nf];
}
push(@{$times[$it]}, $t);
$it++;
}
close($fh);
if ($it > $nt) {
$nt = $it;
} else {
while ($it < $nt) {
push(@{$times[$it]}, 0.0);
}
}
}
if ($delta) {
foreach my $tl (@times) {
my $base = shift(@$tl);
if (!$base) {
$tl = [(0.0) x ($nf - 1)];
} else {
$tl = [map { $_/$base - 1.0 } @$tl];
}
}
}
foreach my $tl (@times) {
print join(',', @$tl), "\n";
}
tftp-hpa-7.2+20261013/tests/test-tftp.sh 0000775 0000000 0000000 00000024626 15263245305 0017451 0 ustar 00root root 0000000 0000000 #!/bin/bash
#
# TFTP Client-Server Test Script
# Tests bidirectional file transfer with an ephemeral TFTP server
#
# Usage: ./test-tftp.sh [-q|-qq|-qqq]
#
# Configuration
SCRIPT_DIR="$(realpath "$(dirname "${BASH_SOURCE[0]}")")"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
TFTPD="${TFTPD:-${REPO_ROOT}/tftpd/tftpd}"
TFTP="${TFTP:-${REPO_ROOT}/tftp/tftp}"
PORT="${PORT:-6969}"
PORTRANGE="${PORTRANGE:-60969:60999}"
LOCALHOSTS="${LOCALHOSTS:-127.0.0.1 ::1}"
ANYADDR="${ANYADDR:-0}"
TSIZE="${TSIZE-1}"
TESTROOT=$(mktemp -d)
SERVER_DIR="$TESTROOT"
FILES_DIR="$TESTROOT/files"
DL_DIR="$TESTROOT/download"
UL_DIR="$TESTROOT/upload"
PCAP="${PCAP-1}"
PCAP_LOG="${PCAP_LOG-$SCRIPT_DIR/test-tftp.pcap.gz}"
TFTPD_LOG="${TFTPD_LOG-$SCRIPT_DIR/tftpd.log}"
TFTP_TEST_WINSIZES="${TFTP_TEST_WINSIZES:-1 4 64 256}"
TFTP_TEST_BLKSIZES="${TFTP_TEST_BLKSIZES:-mtu mtu-16 512 1468 9001 65464 199}"
VERBOSE="${VERBOSE:-0}"
QUIET="${QUIET:-0}"
trap 'exit 127' INT TERM
trap 'cleanup' EXIT
# Output verbosity level
for arg; do
case "$arg" in
-q) QUIET=$((QUIET+1)) ;;
-qq) QUIET=$((QUIET+2)) ;;
-qqq) QUIET=$((QUIET+3)) ;;
*) echo "Unknown option: $arg" 1>&2; exit 64 ;;
esac
done
# Color output helpers
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
time=$(type -P time)
export TIME="${YELLOW}[TIME]${NC} real %e user %U sys %s\\n"
print_info() {
[ $QUIET -lt 1 ] && echo -e "${YELLOW}[INFO]${NC} $*"
}
print_success() {
[ $QUIET -lt 2 ] && echo -e "${GREEN}[PASS]${NC} $*"
}
print_error() {
[ $QUIET -lt 3 ] && echo -e "${RED}[FAIL]${NC} $*"
}
# Print the difference between two fractional timestamps
difftime() {
echo "$2 - $1" | bc
}
# Cleanup function
cleanup() {
print_info "Cleaning up..."
# Kill tftpd if still running
if [ -n "$TFTPD_PID" ] && kill -0 "$TFTPD_PID" 2>/dev/null; then
print_info "Terminating tftpd (PID $TFTPD_PID)..."
kill "$TFTPD_PID" 2>/dev/null
sleep 1
kill -9 "$TFTPD_PID" 2>/dev/null
fi
# Kill tshark if still running
if [ -n "$TSHARK_PID" ] && kill -0 "$TSHARK_PID" 2>/dev/null; then
print_info "Terminating tshark (PID $TSHARK_PID)..."
kill "$TSHARK_PID" 2>/dev/null
sleep 1
kill -9 "$TSHARK_PID" 2>/dev/null
fi
# Remove temporary directories
rm -rf "$TESTROOT"
}
# Check if binaries exist and are executable
check_binaries() {
print_info "Checking for TFTP binaries..."
if [ ! -x "$TFTPD" ]; then
print_error "tftpd not found or not executable at: $TFTPD"
echo "Usage: $0 [tftpd_path] [tftp_path]"
echo "Example: $0 ./tftpd/tftpd /usr/bin/tftp"
exit 1
fi
if [ ! -x "$TFTP" ]; then
print_error "tftp not found or not executable at: $TFTP"
exit 1
fi
print_success "Found tftpd at: $TFTPD"
print_success "Found tftp at: $TFTP"
}
# Start the TFTP server
start_server() {
print_info "Starting tftpd..."
# Start tftpd in the background, listening on localhost
# Run in standalone mode, serve from SERVER_DIR
local -a TFTPD_CMD=()
if [ -n "$STRACE_LOG" ]; then
TFTPD_CMD+=(strace -o "$STRACE_LOG" -f)
fi
TFTPD_CMD+=("$TFTPD" --verbosity $VERBOSE --stderr -L
-p --port-range $PORTRANGE)
if [ $ANYADDR -ne 0 ]; then
if [ $PORT -ne 69 ]; then
TFTPD_CMD+=(-a :$PORT)
fi
else
local addrs=$(echo "$LOCALHOSTS" | \
sed -E -e 's/([^[:space:]]*:[^[:space:]]*)/[\1]/g' \
-e "s/([^[:space:]]+)/-a \\1:$PORT/g")
TFTPD_CMD+=($addrs)
fi
TFTPD_CMD+=(-c --jail "$SERVER_DIR")
print_info "${TFTPD_CMD[*]}"
if [ -n "$TFTPD_LOG" ]; then
"${TFTPD_CMD[@]}" >"$TFTPD_LOG" 2>&1 &
else
"${TFTPD_CMD[@]}" &
fi
TFTPD_PID=$!
# Wait for server to start
sleep 1
# Check if server started successfully
if ! kill -0 "$TFTPD_PID" 2>/dev/null; then
print_error "tftpd failed to start"
return 1
fi
print_success "tftpd started with PID $TFTPD_PID"
me=$(whoami)
# If the user has tshark, dump a packet trace if enabled
rm -f "$PCAP_LOG"
if [ 0"$PCAP" -ne 0 ]; then
local dumphosts=$(echo "$LOCALHOSTS" | \
sed -E -e 's/([^[:space:]]*:[^[:space:]]*)/[\1]/g' \
-e "s/([^[:space:]]+)/or host \\1/g" \
-e 's/^or //')
tshark -q -Q -i lo -n -w "$PCAP_LOG" \
-f "udp port $PORT or portrange ${PORTRANGE/:/-}" \
1>&2 2>/dev/null &
TSHARK_PID=$!
if kill -0 "$TSHARK_PID" 2>/dev/null; then
print_info "dumping packets to: $PCAP_LOG"
else
unset TSHARK_PID
fi
fi
}
declare -a testfiles
# Create test files
create_test_files() {
print_info "Creating test files..."
mkdir -p "$FILES_DIR" "$UL_DIR" "$DL_DIR"
# Small text file
echo "This is a small test file for TFTP." > "$FILES_DIR/small.txt"
# Medium binary-like file
dd if=/dev/urandom of="$FILES_DIR/medium.bin" bs=1024 count=10 2>/dev/null
# Exactly one four-block window; exercises the terminating empty block
dd if=/dev/urandom of="$FILES_DIR/window-boundary.bin" bs=512 count=4 2>/dev/null
# Text file with multiple lines
printf "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n" > "$FILES_DIR/multiline.txt"
# CR NUL pairs cross a 512-byte packet and a four-packet window.
{
head -c 511 /dev/zero | tr '\000' A
printf '\r'
head -c 1534 /dev/zero | tr '\000' B
printf '\rtrailing\r'
} > "$FILES_DIR/netascii-boundary.txt"
# Sparse ASCII file
seq 1 100 > "$FILES_DIR/numbers.txt"
# Large file (> 65536 blocks)
dd if=/dev/urandom of="$FILES_DIR/large.bin" bs=512 count=67890 2>/dev/null
chmod a-w "$FILES_DIR"/*.txt "$FILES_DIR"/*.bin
print_success "Created test files in $FILES_DIR"
}
# Test file download (client receives)
test_download() {
local filename="$1"
local -a tftp_options=(--verbosity $VERBOSE
-B $BLKSIZE -W $WINSIZE "${@:2}")
local logfile="$TESTROOT/tftp.log"
mkdir -p "$DL_DIR"
rm -f "$DL_DIR/$filename"
local mode
case "$filename" in
*.txt) mode=netascii ;;
*) mode=octet ;;
esac
if [ 0"$TSIZE" -eq 0 ]; then
tftp_options+=(-T)
fi
print_info "Testing download: $filename"
# Download using tftp
local download_file="$DL_DIR/$filename"
# Use non-interactive tftp with get command
local -a TFTP_CMD=("$TFTP" "${tftp_options[@]}" "-m" $mode
"$LOCALHOST" "$PORT"
-c get files/"$filename" "$download_file")
print_info "${TFTP_CMD[*]}"
rm -f "$logfile"
local start=$(date -u +%s.%N)
"${TFTP_CMD[@]}"
status=$?
local end=$(date -u +%s.%N)
print_info time = $(difftime $start $end)
if [ $status -ne 0 ]; then
print_error "TFTP exited with status $status"
if [ $status -gt 127 ]; then
# Exit immediately on signal
return $status
fi
elif [ ! -f "$download_file" ]; then
print_error "Failed to download $filename"
elif ! cmp -s "$FILES_DIR/$filename" "$DL_DIR/$filename"; then
print_error "Downloaded file differs from original: $filename"
else
print_success "Download test passed: $filename"
tests_passed=$((tests_passed + 1))
fi
tests_total=$((tests_total + 1))
return 0
}
# Test file upload (client sends)
test_upload() {
local filename="$1"
local -a tftp_options=(--verbosity $VERBOSE
-B $BLKSIZE -W $WINSIZE "${@:2}")
local logfile="$TESTROOT/tftp.log"
mkdir -p "$UL_DIR"
rm -f "$UL_DIR/$filename"
local mode
case "$filename" in
*.txt) mode=netascii ;;
*) mode=octet ;;
esac
if [ 0"$TSIZE" -eq 0 ]; then
tftp_options+=(-T)
fi
print_info "Testing upload: $filename"
# Upload using tftp
local upload_file="$UL_DIR/$filename"
# The server will write it to SERVER_DIR
local -a TFTP_CMD=("$TFTP" "${tftp_options[@]}" "-m" "$mode"
"$LOCALHOST" "$PORT"
-c put "$FILES_DIR/$filename" upload/"$filename")
print_info "${TFTP_CMD[*]}"
rm -f "$logfile"
local start=$(date -u +%s.%N)
"${TFTP_CMD[@]}"
status=$?
local end=$(date -u +%s.%N)
print_info time = $(difftime $start $end)
if [ $status -ne 0 ]; then
print_error "TFTP exited with status $status"
if [ $status -gt 127 ]; then
# Exit immediately on signal
return $status
fi
elif [ ! -f "$upload_file" ]; then
print_error "Failed to upload $filename"
elif ! cmp -s "$FILES_DIR/$filename" "$UL_DIR/$filename"; then
print_error "Uploaded file differs from original: $filename"
else
print_success "Upload test passed: $filename"
tests_passed=$((tests_passed + 1))
fi
tests_total=$((tests_total + 1))
return 0
}
# Main test execution
main() {
tests_passed=0
tests_total=0
umask 077
print_info "================================"
print_info "TFTP Client-Server Test Suite"
print_info "================================"
print_info "Test directory: $TEST_DIR"
print_info "Server directory: $SERVER_DIR"
print_info "Server addresses: $LOCALHOSTS"
print_info "Server port: $PORT"
print_info ""
local start_tests=$(date -u +%s.%N)
check_binaries
create_test_files
start_server
# Give server a moment to start
sleep 2
local -a testfiles=(small.txt multiline.txt netascii-boundary.txt
numbers.txt medium.bin window-boundary.bin large.bin)
# The largest supported client window exercises the threaded packet ring.
for BLKSIZE in $TFTP_TEST_BLKSIZES; do
for WINSIZE in $TFTP_TEST_WINSIZES; do
for LOCALHOST in $LOCALHOSTS; do
print_info "---------------------"
print_info "Block size: $BLKSIZE"
print_info "Window size: $WINSIZE"
print_info "IP address: $LOCALHOST"
print_info "---------------------"
print_info "Running download tests..."
for testfile in "${testfiles[@]}"; do
test_download $testfile || return $?
done
print_info "Running upload tests..."
for testfile in "${testfiles[@]}"; do
test_upload $testfile || return $?
done
done
done
done
local end_tests=$(date -u +%s.%N)
tests_failed=$((tests_total - tests_passed))
print_info ""
print_info "================================"
print_info "Test Results Summary"
print_info "================================"
print_info "Time elapsed: "$(difftime $start_tests $end_tests)
print_success "Tests passed: $tests_passed"
if [ $tests_failed -gt 0 ]; then
print_error "Tests failed: $tests_failed"
return 1
else
print_success "All tests passed!"
return 0
fi
}
# Run main function
main
exit $?
tftp-hpa-7.2+20261013/tftp/ 0000775 0000000 0000000 00000000000 15263245305 0014761 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/tftp/Makefile 0000664 0000000 0000000 00000001316 15263245305 0016422 0 ustar 00root root 0000000 0000000 # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 1999-2006 H. Peter Anvin
# Copyright (c) 2024-2025 Intel Corporation; Author: H. Peter Anvin
SRCROOT = ..
VERSION = $(shell cat ../version)
-include ../config/MCONFIG
include ../MRULES
OBJS = tftp.$(O) main.$(O) version.$(O)
all: tftp$(X) tftp.1
tftp$(X): $(OBJS) $(filter %.a,$(TFTP_LIBS))
$(CC) $(CFLAGS) $(LDFLAGS) -o tftp$(X) $(OBJS) $(TFTP_LIBS)
tftp.1: tftp.1.in ../version
sed -e 's/@@VERSION@@/$(VERSION)/g' < tftp.1.in > tftp.1
install: all
mkdir -p $(INSTALLROOT)$(BINDIR) $(INSTALLROOT)$(MANDIR)/man1
$(INSTALL_PROGRAM) tftp$(X) $(INSTALLROOT)$(BINDIR)
$(INSTALL_DATA) tftp.1 $(INSTALLROOT)$(MANDIR)/man1
clean:
rm -f tftp tftp.1
tftp-hpa-7.2+20261013/tftp/extern.h 0000664 0000000 0000000 00000001156 15263245305 0016442 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1993
* The Regents of the University of California.
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
#ifndef TFTP_EXTERN_H
#define TFTP_EXTERN_H
#include "config.h"
#include "common/tftpsubs.h"
struct server_info {
union sock_addr addr;
socklen_t addrlen;
bool connected;
char *host;
char *canonname;
char *addr_str;
};
extern struct server_info serv;
extern sigjmp_buf toplevel;
int tftp_recvfile(int, const char *, const char *);
int tftp_sendfile(int, const char *, const char *);
#endif
tftp-hpa-7.2+20261013/tftp/main.c 0000664 0000000 0000000 00000120731 15263245305 0016055 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
* Copyright (C) 2026 H. Peter Anvin
*/
#include "common/tftpsubs.h"
#include "common/clock.h"
#include "options.h"
/* Many bug fixes are from Jim Guyton */
/*
* TFTP User Program -- Command Interface.
*/
#include
#include
#ifdef WITH_READLINE
#ifdef HAVE_EDITLINE_READLINE_H
#include
#else
#include
#ifdef HAVE_READLINE_HISTORY_H
#include
#endif
#endif
#endif
#include "extern.h"
#define TRIES 6 /* Number of attempts to send each packet */
#define TIMEOUT_LIMIT ((1 << TRIES)-1)
#define LBUFLEN 200 /* size of input buffer */
/* In theory up to 65535 is supported, but limit it for safety */
#define TFTP_MAX_WINDOWSIZE 32768
struct modes {
const char *m_name;
const char *m_mode;
int m_openflags;
};
static const struct modes modes[] = {
{"netascii", "netascii", O_TEXT},
{"ascii", "netascii", O_TEXT},
{"octet", "octet", O_BINARY},
{"binary", "octet", O_BINARY},
{"image", "octet", O_BINARY},
{0, 0, 0}
};
#define MODE_OCTET (&modes[2])
#define MODE_NETASCII (&modes[0])
#define MODE_DEFAULT MODE_OCTET
struct tftp_options copt = {
.mode = MODE_DEFAULT,
.tsize = true,
.maxtimeout = DEF_TIMEOUT * TIMEOUT_LIMIT,
};
struct common_options xopt = {
#ifdef HAVE_IPV6
.ai_fam = AF_UNSPEC,
#else
.ai_fam = AF_INET,
#endif
.max_windowsize = 64,
.blksize = 0, /* Use MTU */
.rexmtval = DEF_TIMEOUT,
};
struct server_info serv;
union sock_addr servaddr;
bool connected; /* servaddr set */
#ifdef WITH_READLINE
static char *line = NULL;
#else
static char line[LBUFLEN];
#endif
static int margc;
#define MARGVSIZE 20
static char *margv[MARGVSIZE];
static const char *const prompt = "tftp> ";
sigjmp_buf toplevel;
static void intr(int);
static void help_init(void);
static int print_cmd_help(const char *);
static int get(int, char **);
static int getfiles(int, char **, const char *);
static int help(int, char **);
static int mget(int, char **);
static int modecmd(int, char **);
static int mput(int, char **);
static int put(int, char **);
static int putfiles(int, char **, bool);
static int quit(int, char **);
static int setascii(int, char **);
static int setbinary(int, char **);
static int setblocksize(int, char **);
static int setpeer(int, char **);
static int parse_rexmtval(const char *str, FILE *errf);
static int setrexmt(int, char **);
static int set_transfer_host(char *, const char *);
static int parse_timeout(const char *str, FILE *errf);
static int settimeout(int, char **);
static int settrace(int, char **);
static int set_verbosity(const char *, bool);
static int setverbose(int, char **);
static int status(int, char **);
static int setliteral(int, char **);
static int setwindowsize(int, char **);
static int settsize(int, char **);
static int setoptions(int, char **);
static void command(void);
static void getusage(const char *);
static int makeargv(char *, char **);
static void putusage(const char *);
static int settftpmode(const struct modes *mode, bool printmsg);
struct cmd {
const char *name;
int (*handler) (int, char **);
const char *shorthelp;
const char *longhelp;
};
static const struct cmd cmdtab[] = {
{
"c[onnect]", setpeer,
"connect to remote tftp server",
" connect host [port]\n"
" Set the host, and optionally port, for transfers. TFTP does not\n"
" maintain connections between transfers, so this command merely\n"
" remembers the host to use. A remote host can instead be specified\n"
" as part of an [m]get or [m]put command.\n"
},
{
"m[ode]", modecmd,
"set file transfer mode",
" mode {netascii|octet}\n"
" Specify the transfer mode. netascii converts line endings and\n"
" octet transfers binary data without conversion. The default is\n"
" netascii.\n"
},
{
"p[ut]", put,
"send (upload) file or files",
" put [local-file] [host:]remote-file\n"
" Upload a file to a remote file or directory. If 'local-file'\n"
" is not specified, it is assumed to be the same as 'remote-file'\n"
" with any directory portion removed. If 'remote-file' is\n"
" to be considered a directory, it needs to end in '/'.\n"
" put local-file local-file... [host:]remote-directory\n"
" Upload two or more files to a directory on the remote host.\n"
" See also the 'mput' command.\n"
"\n"
" The remote host is assumed to use '/' as its directory separator.\n"
" The remote name may be of the form host:filename to specify\n"
" the remote host to connect to, as if the 'connect' command had\n"
" been used to specify this host.\n"
" Enable literal mode to prevent special treatment of ':' in filenames.\n"
},
{
"mp[ut]", mput,
"send (upload) multiple files",
" mput local-file... [host:]remote-directory\n"
" Upload one or more files to a directory on the remote host.\n"
"\n"
" The remote host is assumed to use '/' as its directory separator.\n"
" The remote name may be of the form host:filename to specify\n"
" the remote host to connect to, as if the 'connect' command had\n"
" been used to specify this host.\n"
" Enable literal mode to prevent special treatment of ':' in filenames.\n"
},
{
"g[et]", get,
"receive (download) file or files",
" get [host:]remote-file [local-file]\n"
" Download a file from a remote file or directory. If 'local-file'\n"
" is not specified, it is assumed to be the same as 'remote-file'\n"
" with any directory portion removed.\n"
" get [host:]remote-file [host:]remote-file [host:]remote-file...\n"
" Download three or more files into the current directory on the\n"
" local system. See also the 'mget' command.\n"
"\n"
" The remote host is assumed to use '/' as its directory separator.\n"
" The remote name may be of the form host:filename to specify\n"
" the remote host to connect to, as if the 'connect' command had\n"
" been used to specify this host.\n"
" Enable literal mode to prevent special treatment of ':' in filenames.\n"
},
{
"mg[et]", mget,
"receive (download) multiple files",
" mget [host:]remote-file... local-directory\n"
" Download one or more files from from a remote directory into\n"
" a specified directory on the local system.\n"
"\n"
" The remote host is assumed to use '/' as its directory separator.\n"
" The remote name may be of the form host:filename to specify\n"
" the remote host to connect to, as if the 'connect' command had\n"
" been used to specify this host.\n"
" Enable literal mode to prevent special treatment of ':' in filenames.\n"
},
{
"q[uit]", quit,
"exit tftp",
" quit\n"
" Exit tftp. End-of-file also exits.\n"
},
{
"v[erbose]", setverbose,
"toggle or set message verbosity",
" verbose [level]\n"
" Toggle verbose mode or set the verbosity level.\n"
},
{
"tr[ace]", settrace,
"toggle packet tracing",
" trace\n"
" Toggle packet tracing, a debugging feature.\n"
},
{
"l[iteral]", setliteral,
"toggle literal mode, ignore ':' in file name",
" literal\n"
" Toggle literal mode. When enabled, this mode prevents special\n"
" treatment of ':' in filenames.\n"
},
{
"st[atus]", status,
"show current status",
" status\n"
" Show current status.\n"
},
{
"b[inary]", setbinary,
"set mode to octet",
" binary\n"
" Set the transfer mode to octet (shorthand for \"mode octet\".)\n"
},
{
"a[scii]", setascii,
"set mode to netascii",
" ascii\n"
" Set the transfer mode to netascii (shorthand for \"mode netascii\".)\n"
},
{
"bl[ocksize]", setblocksize,
"set the requested transfer block size",
" blocksize size\n"
" Request the RFC 2348 blksize option with 'size' bytes per data\n"
" block. Valid values are 8 through 65464.\n"
},
{
"r[exmt]", setrexmt,
"set per-packet transmission timeout",
" rexmt packet-timeout\n"
" Set the initial per-packet retransmission timeout in seconds. Each\n"
" subsequent retry doubles this interval.\n"
},
{
"ti[meout]", settimeout,
"set total retransmission timeout",
" timeout total-timeout\n"
" Set the maximum retransmission interval in seconds.\n"
},
{
"tsi[ze]", settsize,
"toggle sending tsize option",
" tsize\n"
" Toggle the sending of the TFTP tsize (transfer size) option.\n"
" The default is to send the tsize option.\n"
},
{
"win[dowsize]", setwindowsize,
"set the requested transfer window size",
" windowsize size\n"
" Request the RFC 7440 windowsize option with 'size' data\n"
" blocks per window. Valid values are 1 through 32768.\n"
},
{
"opt[ions]", setoptions,
"toggle TFTP options support",
" options\n"
" Toggle the sending of TFTP options. When set to off, no\n"
" TFTP options of any kind are sent. This disables the\n"
" block size, window size, and transfer size functions.\n"
},
{
"?", help,
"print help information",
" help [command ...]\n"
" ? [command ...]\n"
" Print help information. With command names, display detailed help\n"
" for each command.\n"
},
{
"h[elp]", help,
"print help information",
" help [command ...]\n"
" ? [command ...]\n"
" Print help information. With command names, display detailed help\n"
" for each command.\n"
}
};
static const char *getcmd(const char *, const struct cmd **cmdp);
static char *tail(char *);
static void usage(int errcode)
{
fprintf(errcode ? stderr : stdout,
"Usage: %s [options] [host [port]] [-c command...]\n"
" Options:\n"
" -V, --version print version number and exit\n"
" -h, --help print this help text and exit\n"
" --help=command print the help text for \"command\" and exit\n"
#ifdef HAVE_IPV6
" -4. --ipv4 only use IPv4, no IPv6\n"
" -6. --ipv6 only use IPv6, no IPv4\n"
#endif
" -v, --verbose increase logging verbosity\n"
" --verbosity level set logging verbosity level\n"
" -l, --literal disable host:path syntax\n"
" -m, --mode mode set the transfer mode (netascii, octet)\n"
" -a, --ascii alias for --mode netascii\n"
" --netascii alias for --mode netascii\n"
" --text alias for --mode netascii\n"
" -b, --binary alias for --mode octet\n"
" --octet alias for --mode octet\n"
" -R, --port-range min:max use emhermeral ports in the given range\n"
" -B, --blocksize size set the requested transfer block size\n"
" -W, --windowsize size set the requested transfer window size\n"
" -T, --no-tsize disable sending the tsize TFTP option\n"
" -N, --no-options disable sending any TFTP options\n"
" -U, --unsafe allow multihomed server address changes\n"
" -c, --command command execute \"command\", then exit (must be last)\n"
" -c, --command help get a list of available commands\n"
, _progname);
exit(errcode);
}
enum long_only_options {
OPT_VERBOSITY = 256
};
static const struct option long_options[] = {
{ "ipv4", no_argument, NULL, '4' },
{ "ipv6", no_argument, NULL, '6' },
{ "verbose", no_argument, NULL, 'v' },
{ "verbosity", required_argument, NULL, OPT_VERBOSITY },
{ "version", no_argument, NULL, 'V' },
{ "literal", no_argument, NULL, 'l' },
{ "mode", required_argument, NULL, 'm' },
{ "command", no_argument, NULL, 'c' },
{ "port-range", required_argument, NULL, 'R' },
{ "blocksize", required_argument, NULL, 'B' },
{ "windowsize", required_argument, NULL, 'W' },
{ "ascii", no_argument, NULL, 'a' },
{ "text", no_argument, NULL, 'a' },
{ "netascii", no_argument, NULL, 'a' },
{ "binary", no_argument, NULL, 'b' },
{ "octet", no_argument, NULL, 'b' },
{ "no-tsize", no_argument, NULL, 'T' },
{ "help", optional_argument, NULL, 'h' },
{ "no-options", no_argument, NULL, 'N' },
{ "unsafe", no_argument, NULL, 'U' },
{ NULL, 0, NULL, 0 }
};
static const char short_options[] = "+46vVlm:cR:B:W:w:abThNU";
int main(int argc, char *argv[])
{
int optc, ret;
static int pargc, peerargc;
static char **pargv;
char *peerargv[3];
uintmax_t v;
set_progname(argv[0]);
random_init();
help_init();
copt.mode = MODE_DEFAULT;
peerargv[0] = argv[0];
peerargc = 1;
while (!copt.iscmd) {
optc = getopt_long(argc, argv, short_options, long_options,
NULL);
if (optc == -1) {
if (optind == argc)
break;
if (peerargc >= 3)
usage(EX_USAGE);
peerargv[peerargc++] = argv[optind++];
continue;
}
switch (optc) {
case '4':
xopt.ai_fam = AF_INET;
break;
case '6':
#ifdef HAVE_IPV6
xopt.ai_fam = AF_INET6;
#else
fprintf(stderr, "%s: this version compiled without IPv6 support\n",
_progname);
exit(EX_UNAVAILABLE);
#endif
break;
case 'v':
copt.verbose++;
break;
case OPT_VERBOSITY:
set_verbosity(optarg, true);
break;
case 'V':
/* Print version and configuration to stdout and exit */
print_configuration(stdout);
exit(0);
case 'b':
settftpmode(MODE_OCTET, false);
break;
case 'a':
settftpmode(MODE_NETASCII, false);
break;
case 'l':
copt.literal = true;
break;
case 'm':
{
const struct modes *p;
for (p = modes; p->m_name; p++) {
if (!strcmp(optarg, p->m_name))
break;
}
if (settftpmode(p, false)) {
fprintf(stderr, "%s: invalid mode: %s\n", argv[0], optarg);
exit(EX_USAGE);
}
break;
}
case 'c':
copt.iscmd = true;
break;
case 'R':
if (sscanf(optarg, "%u:%u", &xopt.portrange_from,
&xopt.portrange_to) != 2 ||
!xopt.portrange_from ||
xopt.portrange_from > xopt.portrange_to ||
xopt.portrange_to > 65535) {
fprintf(stderr, "Bad port range: %s\n", optarg);
exit(EX_USAGE);
}
break;
case 'B':
if (!parse_blocksize_arg(optarg, MIN_SEGSIZE)) {
fprintf(stderr, "Bad block size argument: %s\n", optarg);
exit(EX_USAGE);
}
break;
case 'W':
case 'w':
v = parse_uint(optarg, 1, TFTP_MAX_WINDOWSIZE);
if (v == BAD_NUM) {
fprintf(stderr, "Bad window size: %s (valid range is 1-%u)\n",
optarg, TFTP_MAX_WINDOWSIZE);
exit(EX_USAGE);
} else {
xopt.max_windowsize = v;
}
break;
case 'T':
copt.tsize = false;
break;
case 'N':
copt.no_options = true;
break;
case 'U':
copt.unsafe = true;
break;
case 'h':
if (optarg && *optarg)
exit(print_cmd_help(optarg));
else
usage(0);
break;
default:
usage(EX_USAGE);
break;
}
}
pargv = argv + optind;
pargc = argc - optind;
/* Allow SIGINT in non-interactive mode to terminate the program */
if (!copt.iscmd)
tftp_signal(SIGINT, intr, 0);
if (peerargc > 1) {
/* Set peer */
if (sigsetjmp(toplevel, 1) != 0)
exit(EX_NOHOST);
(void)setpeer(peerargc, peerargv);
}
if (copt.iscmd) {
/* -c specified; execute command and exit */
const struct cmd *c;
const char *errtype;
static char *splitbuf = NULL;
if (pargc == 1) {
/* Only one string, see if it should be split */
splitbuf = xstrdup(pargv[0]);
pargc = makeargv(splitbuf, pargv = margv);
}
if (!pargc || !pargv[0] || !*pargv[0]) {
fprintf(stderr, "%s: missing command after -c\n", _progname);
exit(EX_USAGE);
}
errtype = getcmd(pargv[0], &c);
if (errtype) {
fprintf(stderr, "%s: %s command: %s (did you mean %s?)\n",
_progname, errtype, pargv[0], c->name);
exit(EX_USAGE);
}
ret = sigsetjmp(toplevel, 1);
if (!ret) {
ret = (*c->handler) (pargc, pargv);
xfree(splitbuf);
}
exit(ret);
}
#ifdef WITH_READLINE
#ifdef HAVE_READLINE_HISTORY_H
using_history();
#endif
#endif
if (sigsetjmp(toplevel, 1) != 0)
(void)putchar('\n');
command();
return 0; /* Never reached */
}
/* Called when a command is incomplete; modifies
the global variable "line" */
static bool getmoreargs(const char *partial, const char *mprompt)
{
if (copt.iscmd)
return false;
#ifdef WITH_READLINE
char *eline;
int len, elen;
len = strlen(partial);
eline = readline(mprompt);
if (!eline)
exit(0); /* EOF */
elen = strlen(eline);
if (line) {
free(line);
line = NULL;
}
line = xmalloc(len + elen + 1);
strcpy(line, partial);
strcpy(line + len, eline);
free(eline);
#ifdef HAVE_READLINE_HISTORY_H
add_history(line);
#endif
#else
int len = strlen(partial);
strcpy(line, partial);
fputs(mprompt, stdout);
if (fgets(line + len, LBUFLEN - len, stdin) == 0)
if (feof(stdin))
exit(0); /* EOF */
#endif
return true;
}
static int setpeer(int argc, char *argv[])
{
if (argc < 2) {
if (!getmoreargs("connect ", "(to) "))
return EX_USAGE;
margc = makeargv(line, margv);
argc = margc;
argv = margv;
}
if ((argc < 2) || (argc > 3)) {
printf("usage: %s host-name [port]\n", argv[0]);
return EX_USAGE;
}
return set_transfer_host(argv[1], argc == 3 ? argv[2] : NULL);
}
static int modecmd(int argc, char *argv[])
{
const struct modes *p;
const char *sep;
if (argc < 2) {
printf("Using %s mode to transfer files.\n", copt.mode->m_mode);
return 0;
}
if (argc == 2) {
for (p = modes; p->m_name; p++)
if (strcmp(argv[1], p->m_name) == 0)
break;
if (!settftpmode(p, true))
return 0;
printf("%s: unknown mode\n", argv[1]);
/* drop through and print usage message */
}
printf("usage: %s [", argv[0]);
sep = " ";
for (p = modes; p->m_name; p++) {
printf("%s%s", sep, p->m_name);
if (*sep == ' ')
sep = " | ";
}
printf(" ]\n");
return EX_USAGE;
}
static int setbinary(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
return settftpmode(MODE_OCTET, true);
}
static int setascii(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
return settftpmode(MODE_NETASCII, true);
}
static int settftpmode(const struct modes *newmode, bool printmsg)
{
if (!newmode)
return EX_USAGE;
copt.mode = newmode;
if (printmsg && copt.verbose)
printf("Mode set to %s\n", newmode->m_name);
return 0;
}
/*
* Simple wrapper around getaddrinfo().
*/
static int
set_sock_addr(char **hostp, const char *port,
union sock_addr *s, socklen_t *slen)
{
char *host = *hostp;
struct addrinfo *addrResult;
struct addrinfo hints;
int err;
memset(&hints, 0, sizeof(hints));
hints.ai_family = s->sa.sa_family;
hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
#ifdef AI_IDN
hints.ai_flags |= AI_IDN;
#endif
#ifdef AI_CANONIDN
hints.ai_flags |= AI_CANONIDN;
#endif
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
err = getaddrinfo(strip_address(host), port, &hints, &addrResult);
if (err)
return err;
if (addrResult == NULL)
return EAI_NONAME;
memcpy(s, addrResult->ai_addr, addrResult->ai_addrlen);
*slen = addrResult->ai_addrlen;
if (addrResult->ai_canonname)
*hostp = xstrdup(addrResult->ai_canonname);
else
*hostp = xstrdup(host);
freeaddrinfo(addrResult);
return 0;
}
static int set_transfer_host(char *host, const char *port)
{
int err;
if (!port || !*port)
port = "tftp";
xzero(serv.addr);
serv.addr.sa.sa_family = xopt.ai_fam;
xdelete(serv.host);
xdelete(serv.canonname);
xdelete(serv.addr_str);
serv.canonname = serv.host = xstrdup(host);
err = set_sock_addr(&serv.canonname, port, &serv.addr, &serv.addrlen);
if (err) {
serv.connected = false;
if (err == EAI_SERVICE) {
fprintf(stderr, "%s: bad port/service: %s\n",
_progname, port);
return EX_USAGE;
} else {
fprintf(stderr, "%s: %s: %s\n",
_progname, serv.host, gai_strerror(err));
return EX_NOHOST;
}
}
serv.connected = true;
serv.addr_str = net_address(&serv.addr.sa, serv.addrlen);
if (copt.verbose) {
printf("Connected to %s ", serv.host);
if (strcmp(serv.host, serv.canonname))
printf("(%s) ", serv.canonname);
printf("%s\n", serv.addr_str);
}
return 0;
}
/*
* Is this a directory (ending in /)?
*/
static bool is_directory(const char *filename)
{
const char *ep = strchr(filename, 0);
return ep > filename && ep[-1] == '/';
}
/*
* Send file(s).
*/
static int putfiles(int argc, char *argv[], bool target_is_directory)
{
int fd;
int n, err, result;
char *cp;
char *targ;
if (argc < 2) {
if (!getmoreargs("send ", "(file) "))
return EX_USAGE;
margc = makeargv(line, margv);
argc = margc;
argv = margv;
}
if (argc < 2) {
putusage(argv[0]);
return EX_USAGE;
}
targ = argv[argc - 1];
if (!copt.literal && strchr(argv[argc - 1], ':')) {
for (n = 1; n < argc - 1; n++)
if (strchr(argv[n], ':')) {
putusage(argv[0]);
return EX_USAGE;
}
cp = argv[argc - 1];
targ = strchr(cp, ':');
*targ++ = 0;
err = set_transfer_host(cp, NULL);
if (err)
return EX_NOHOST;
}
if (!serv.connected) {
fprintf(stderr, "%s: %s: no server host specified\n", _progname, targ);
return EX_USAGE;
}
if (!target_is_directory &&
(argc < 3 || (argc == 3 && !is_directory(targ)))) {
cp = argc == 2 ? tail(targ) : argv[1];
fd = open(cp, O_RDONLY | copt.mode->m_openflags);
if (fd < 0) {
fprintf(stderr, "%s: %s: %s\n",
_progname, targ, strerror(errno));
return EX_NOINPUT;
}
if (copt.verbose)
printf("putting %s to %s:%s [%s]\n",
cp, serv.host, targ, copt.mode->m_mode);
return tftp_sendfile(fd, targ, copt.mode->m_mode);
}
/* this assumes the target is a directory */
/* on a remote unix system. hmmmm. */
err = 0;
for (n = 1; n < argc - 1; n++) {
const char *base = tail(argv[n]);
char *remotepath = xmalloc(strlen(targ) + 1 + strlen(base) + 1);
sprintf(remotepath, "%s/%s", targ, base);
fd = open(argv[n], O_RDONLY | copt.mode->m_openflags);
if (fd < 0) {
fprintf(stderr, "%s: %s: %s", _progname, argv[n], strerror(errno));
free(remotepath);
if (!err)
err = EX_OSERR;
continue;
}
if (copt.verbose)
printf("putting %s to %s:%s [%s]\n",
argv[n], serv.host, remotepath, copt.mode->m_mode);
result = tftp_sendfile(fd, remotepath, copt.mode->m_mode);
if (!err)
err = result;
free(remotepath);
}
return err;
}
static int put(int argc, char *argv[])
{
return putfiles(argc, argv, false);
}
static int mput(int argc, char *argv[])
{
if (argc < 3) {
putusage(argv[0]);
return EX_USAGE;
}
return putfiles(argc, argv, true);
}
static void putusage(const char *s)
{
printf("usage: %s file ... host:target, or\n", s);
printf(" %s file ... target (when already connected)\n", s);
}
/*
* Receive file(s).
*/
static int getfiles(int argc, char *argv[], const char *local_directory)
{
int fd;
int n, err, result;
char *cp;
char *src;
if (argc < 2) {
if (!getmoreargs("get ", "(files) "))
return EX_USAGE;
margc = makeargv(line, margv);
argc = margc;
argv = margv;
}
if (argc < 2 + !!local_directory) {
getusage(argv[0]);
return EX_USAGE;
}
if (!serv.connected) {
for (n = 1; n < argc - !!local_directory; n++)
if (copt.literal || strchr(argv[n], ':') == 0) {
getusage(argv[0]);
return EX_USAGE;
}
}
err = 0;
for (n = 1; n < argc - !!local_directory; n++) {
src = strchr(argv[n], ':');
if (copt.literal || src == NULL)
src = argv[n];
else {
int resolve_error;
*src++ = 0;
resolve_error = set_transfer_host(argv[n], NULL);
if (resolve_error) {
printf("Warning: %s\n", gai_strerror(resolve_error));
printf("%s: unknown host\n", argv[n]);
if (!err)
err = EX_NOHOST;
continue;
}
}
if (!local_directory &&
(argc < 3 || (argc == 3 && !is_directory(argv[2])))) {
cp = argc == 3 ? argv[2] : tail(src);
fd = open(cp, O_WRONLY | O_CREAT | O_TRUNC | copt.mode->m_openflags,
0666);
if (fd < 0) {
fprintf(stderr, "%s: %s: %s\n", _progname, cp, strerror(errno));
return EX_OSERR;
}
if (copt.verbose)
printf("getting from %s:%s to %s [%s]\n",
serv.host, src, cp, copt.mode->m_mode);
err = tftp_recvfile(fd, src, copt.mode->m_mode);
break;
}
if (local_directory) {
const char *base = tail(src);
cp = xmalloc(strlen(local_directory) + 1 + strlen(base) + 1);
sprintf(cp, "%s/%s", local_directory, base);
} else {
cp = tail(src); /* new .. jdg */
}
fd = open(cp, O_WRONLY | O_CREAT | O_TRUNC | copt.mode->m_openflags,
0666);
if (fd < 0) {
fprintf(stderr, "%s: %s: %s\n", _progname, cp, strerror(errno));
if (!err)
err = EX_OSERR;
if (local_directory)
free(cp);
continue;
}
if (copt.verbose)
printf("getting from %s:%s to %s [%s]\n",
serv.host, src, cp, copt.mode->m_mode);
result = tftp_recvfile(fd, src, copt.mode->m_mode);
if (!err)
err = result;
if (local_directory)
free(cp);
}
return err;
}
static int get(int argc, char *argv[])
{
return getfiles(argc, argv, NULL);
}
static int mget(int argc, char *argv[])
{
if (argc < 3) {
getusage(argv[0]);
return EX_USAGE;
}
return getfiles(argc, argv, argv[argc - 1]);
}
static void getusage(const char *s)
{
printf("usage: %s host:file host:file ... file, or\n", s);
printf(" %s file file ... file if connected\n", s);
}
static int parse_rexmtval(const char *str, FILE *errf)
{
const double mini = (double)MIN_TIMEOUT/USEC_PER_SEC;
const double maxi = (double)MAX_TIMEOUT/USEC_PER_SEC;
double t;
char *ep;
errno = 0;
t = strtod(str, &ep);
/* Careful here: keep in mind unordered values! */
if (!errno && ep != str && !*ep && t >= mini && t <= maxi) {
xopt.rexmtval = t * USEC_PER_SEC;
copt.maxtimeout = xopt.rexmtval * TIMEOUT_LIMIT;
} else {
fprintf(errf, "Bad value (range %g-%g): %s\n", mini, maxi, str);
return EX_USAGE;
}
return 0;
}
static int setrexmt(int argc, char *argv[])
{
if (argc < 2) {
if (!getmoreargs("rexmt-timeout ", "(value) "))
return EX_USAGE;
argc = margc = makeargv(line, margv);
argv = margv;
}
if (argc != 2) {
printf("usage: %s value\n", argv[0]);
return EX_USAGE;
}
return parse_rexmtval(argv[1], stdout);
}
static int parse_timeout(const char *str, FILE *errf)
{
const double mini = (double)xopt.rexmtval/USEC_PER_SEC;
const double maxi = (double)MAX_TIMEOUT*TIMEOUT_LIMIT/USEC_PER_SEC;
double t;
char *ep;
errno = 0;
t = strtod(str, &ep);
/* Careful here: keep in mind unordered values! */
if (!errno && ep != str && !*ep && t >= mini && t <= maxi) {
copt.maxtimeout = t * USEC_PER_SEC + 1.0;
} else {
fprintf(errf, "Bad value (range %g-%g): %s\n", mini, maxi, str);
return EX_USAGE;
}
return 0;
}
static int settimeout(int argc, char *argv[])
{
if (argc < 2) {
if (!getmoreargs("maximum-timeout ", "(value) "))
return EX_USAGE;
argc = margc = makeargv(line, margv);
argv = margv;
}
if (argc != 2) {
printf("usage: %s value\n", argv[0]);
return EX_USAGE;
}
return parse_timeout(argv[1], stdout);
}
static int setblocksize(int argc, char *argv[])
{
if (argc < 2) {
if (!getmoreargs("blocksize ", "(size) "))
return EX_USAGE;
argc = margc = makeargv(line, margv);
argv = margv;
}
if (argc != 2) {
printf("usage: %s {size|mtu[-slack]}\n", argv[0]);
return EX_USAGE;
}
if (!parse_blocksize_arg(argv[1], MIN_SEGSIZE)) {
printf("%s: bad block size (valid range is %d-%d)\n",
argv[1], MIN_SEGSIZE, MAX_SEGSIZE);
return EX_USAGE;
}
return 0;
}
static int setwindowsize(int argc, char *argv[])
{
uintmax_t v;
if (argc < 2) {
if (!getmoreargs("windowsize ", "(size) "))
return EX_USAGE;
argc = margc = makeargv(line, margv);
argv = margv;
}
if (argc != 2) {
printf("usage: %s size\n", argv[0]);
return EX_USAGE;
}
v = parse_uint(argv[1], 1, TFTP_MAX_WINDOWSIZE);
if (v == BAD_NUM) {
printf("%s: bad window size (valid range is 1-%u)\n",
argv[1], TFTP_MAX_WINDOWSIZE);
return EX_USAGE;
}
xopt.max_windowsize = v;
return 0;
}
static int setliteral(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
copt.literal = !copt.literal;
printf("Literal mode %s.\n", copt.literal ? "on" : "off");
return 0;
}
static int settsize(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
copt.tsize = !copt.tsize;
printf("tsize option %s%s.\n",
copt.tsize ? "on" : "off",
copt.no_options ? " (options disabled)" : "");
return 0;
}
static int setoptions(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
copt.no_options = !copt.no_options;
printf("TFTP options %s.\n", copt.no_options ? "disabled" : "enabled");
return 0;
}
static int status(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
if (serv.connected) {
printf("Connected to: %s ", serv.host);
if (strcmp(serv.host, serv.canonname))
printf("(%s) ", serv.canonname);
printf("%s\n", serv.addr_str);
} else {
printf("Not connected\n");
}
printf("Mode: %s, verbose: %s, tracing: %s, literal: %s\n",
copt.mode->m_mode,
copt.verbose ? "on" : "off", copt.trace ? "on" : "off",
copt.literal ? "on" : "off");
printf("Retransmit interval: %g s, total timeout: %g s\n",
(double)xopt.rexmtval / USEC_PER_SEC,
(double)copt.maxtimeout / USEC_PER_SEC);
printf("TFTP options: %s\n", copt.no_options ? "disabled" : "enabled");
if (!copt.no_options) {
printf("Blocksize: ");
if (xopt.blksize <= 0)
printf("mtu");
if (xopt.blksize != 0)
printf("%d", xopt.blksize);
printf(", windowsize: %u, tsize: %s\n",
xopt.max_windowsize ? xopt.max_windowsize : 1,
copt.tsize ? "on" : "off");
}
return 0;
}
static void intr(int sig)
{
int err;
alarm(0);
tftp_signal(SIGALRM, SIG_DFL, 0);
if (sig == SIGALRM)
err = EX_TEMPFAIL;
else
err = sig + 128;
siglongjmp(toplevel, err);
}
static char *tail(char *filename)
{
char *s;
while (*filename) {
s = strrchr(filename, '/');
if (s == NULL)
break;
if (s[1])
return (s + 1);
*s = '\0';
}
return (filename);
}
/*
* Command parser.
*/
static void command(void)
{
const struct cmd *c;
const char *errtype;
for (;;) {
#ifdef WITH_READLINE
if (line) {
free(line);
line = NULL;
}
line = readline(prompt);
if (!line)
exit(0); /* EOF */
#else
fputs(prompt, stdout);
if (fgets(line, LBUFLEN, stdin) == 0) {
if (feof(stdin)) {
exit(0);
} else {
continue;
}
}
#endif
if ((line[0] == 0) || (line[0] == '\n'))
continue;
#ifdef WITH_READLINE
#ifdef HAVE_READLINE_HISTORY_H
add_history(line);
#endif
#endif
margc = makeargv(line, margv);
if (margc == 0)
continue;
errtype = getcmd(margv[0], &c);
if (errtype) {
printf("Error: %s command: %s (did you mean %s?)\n",
errtype, margv[0], c->name);
continue;
}
(void)(*c->handler) (margc, margv);
}
}
static const char *getcmd(const char *name, const struct cmd **cmdp)
{
const char *p, *q;
const struct cmd *cmd;
const struct cmd *best = &cmdtab[0];
int best_metric = -1;
for (cmd = cmdtab; cmd < ARRAY_END(cmdtab); cmd++) {
bool ok = false;
bool stop = false;
int metric = 0;
for (p = name, q = cmd->name; !stop; q++) {
unsigned char pc = *p;
unsigned char qc = *q;
switch (qc) {
case '\0':
case ']':
/* Exact match if end of input, otherwise fail */
ok = !pc;
stop = true;
break;
case '[':
ok = true; /* Valid prefix, so far at least */
/* Do not advance p here */
break;
default:
if (!pc) {
/* ok if and only if it is a valid prefix */
stop = true;
} else if (tolower(pc) != qc) {
/* Character mismatch */
ok = false;
stop = true;
} else {
metric++;
p++;
}
break;
}
}
if (ok) {
*cmdp = cmd;
return NULL;
} else if (metric > best_metric) {
best = cmd;
best_metric = metric;
}
}
/* Failure, but suggest the best match */
*cmdp = best;
return "unknown";
}
/*
* Slice a string up into argc/argv. Silently discards any words beyond
* MARGVSIZE - 1 (leaving room for the NULL terminator) rather than
* overflowing the fixed-size margv[] array.
*
* The string is modified in-place!
*
* XXX: handle quotes and escapes!
*/
static int makeargv(char *str, char **argp)
{
char *cp;
char ** const argpend = &argp[MARGVSIZE - 1];
int argc = 0;
margc = 0;
for (cp = str; *cp;) {
while (isspace(*cp))
cp++;
if (*cp == '\0')
break;
if (argp >= argpend)
break;
*argp++ = cp;
argc++;
while (*cp != '\0' && !isspace(*cp))
cp++;
if (*cp == '\0')
break;
*cp++ = '\0';
}
*argp++ = 0;
return argc;
}
static int quit(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
exit(0);
}
/*
* Help command.
*/
static int helpindent = 0;
static void help_init(void)
{
const struct cmd *c;
for (c = cmdtab; c < ARRAY_END(cmdtab); c++) {
int len = strlen(c->name);
if (len > helpindent)
helpindent = len;
}
}
static int print_cmd_help(const char *cmd)
{
const struct cmd *c;
const char *errtype;
errtype = getcmd(cmd, &c);
if (errtype) {
printf("help: %s command %s (did you mean %s?)\n",
errtype, cmd, c->name);
return EX_USAGE;
} else {
printf("%-*s %s\n%s",
helpindent, c->name, c->shorthelp, c->longhelp);
return 0;
}
}
static int help(int argc, char *argv[])
{
int err = 0;
if (argc == 1) {
const struct cmd *c;
printf("%s command list\n"
"Commands may be abbreviated as indicated by [...]\n",
version_string);
for (c = cmdtab; c < ARRAY_END(cmdtab); c++)
printf(" %-*s %s\n", helpindent, c->name, c->shorthelp);
} else {
int i;
for (i = 1; i < argc; i++) {
if (i > 1)
putchar('\n'); /* Blank line between help texts */
err |= print_cmd_help(argv[i]);
}
}
return err;
}
static int settrace(int argc, char *argv[])
{
(void)argc;
(void)argv; /* Quiet unused warning */
copt.trace = !copt.trace;
printf("Packet tracing %s.\n", copt.trace ? "on" : "off");
return 0;
}
static int set_verbosity(const char *to, bool startup)
{
const char *name;
if (to) {
char *ep;
long v = strtol(to, &ep, 0);
if (*to && !*ep && v == (int)v) {
copt.verbose = v;
} else {
if (startup) {
fprintf(stderr, "%s: invalid verbosity level: %s\n",
_progname, to);
exit(EX_USAGE);
} else {
printf("Invalid verbosity level: %s\n", to);
return EX_USAGE;
}
}
} else {
copt.verbose = !copt.verbose;
}
switch (copt.verbose) {
case 0:
name = "off";
break;
case 1:
name = "on";
break;
default:
name = (copt.verbose < 0) ? "quiet" : "high";
break;
}
if (!startup)
printf("Verbosity set to level %d (%s).\n", copt.verbose, name);
return 0;
}
static int setverbose(int argc, char *argv[])
{
(void)argc;
return set_verbosity(argv[1], false);
}
tftp-hpa-7.2+20261013/tftp/options.h 0000664 0000000 0000000 00000001156 15263245305 0016630 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (C) 2026 H. Peter Anvin
*/
#ifndef TFTP_OPTIONS_H
#define TFTP_OPTIONS_H
#include "common/options.h"
struct modes;
/*
* Client configuration selected at startup or by an interactive command.
* Connection and transfer state deliberately remain outside this structure.
*/
struct tftp_options {
const struct modes *mode;
uintmax_t maxtimeout;
int verbose;
bool trace;
bool literal;
bool tsize;
bool iscmd;
bool no_options;
bool unsafe;
};
extern struct tftp_options copt;
#endif /* TFTP_OPTIONS_H */
tftp-hpa-7.2+20261013/tftp/tftp.1.in 0000664 0000000 0000000 00000022473 15263245305 0016435 0 ustar 00root root 0000000 0000000 .\" -*- nroff -*- --------------------------------------------------------- *
.\"
.\" SPDX-License-Identifier: BSD-4-Clause-UC
.\"
.\" Copyright (c) 1990, 1993, 1994
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Copyright 2001-2026 H. Peter Anvin - All Rights Reserved
.\"
.\"----------------------------------------------------------------------- */
.TH TFTP 1 "20 September 2026" "tftp-hpa @@VERSION@@" "User's Manual"
.SH "NAME"
.B tftp
\- Trivial File Transfer Protocol (TFTP) client
.SH "SYNOPSIS"
.B tftp
[ \fIoptions...\fP ]
[\fIhost\fP [\fIport\fP]]
[\fB\-c\fP \fIcommand\fP]
.SH "DESCRIPTION"
.B tftp
is a client for the Trivial file Transfer Protocol, which can be
used to transfer files to and from remote machines, including some
very minimalistic, usually embedded, systems. The remote
.I host
may be specified on the command line, in which case
.B tftp
uses
.I host
as the default host for future transfers (see the
.B connect
command below.)
.SH "OPTIONS"
.TP
.B \-4, \-\-ipv4
Connect with IPv4 only, even if IPv6 support was compiled in.
.TP
.B \-6, \-\-ipv6
Connect with IPv6 only, if compiled in.
.TP
\fB\-c\fP, \fB\-\-command\fP \fIcommand\fP
Execute \fIcommand\fP as if it had been entered on the
.B tftp
prompt.
Must be specified last on the command line.
.TP
\fB\-l\fP, \fB\-\-literal\fP
Default to literal mode. Used to avoid special processing of \[lq]:\[rq] in a
file name.
.TP
\fB\-m\fP, \fB\-\-mode\fP \fImode\fP
Set the default transfer mode to \fImode\fP. \fImode\fP can be either
.B netascii
(convert line endings) or
.B octet
(direct binary transfer without any conversions.)
.IP
This is usually used with \-c.
.TP
\fB\-a\fP, \fB\-\-ascii\fP, \fB\-\-netascii\fP, \fB\-\-text\fP
Equivalent to
.RB \\[lq] "\-\-mode netascii" \\[rq].
.TP
\fB\-b\fP, \fB\-\-binary\fP, \fB\-\-octet\fP
Equivalent to
.RB \\[lq] "\-\-mode octet" \\[rq].
.TP
\fB\-B\fP, \fB\-\-blocksize\fP \fImax-block-size\fP
Specifies the maximum permitted block size. The permitted range for
this parameter is from 512 to 65464, or it can be specified as
.RB \\[lq] mtu \\[rq],
or \[lq]\fBmtu-\fP\fIslack\fP\[rq].
When
.B mtu
is specified,
.B tftp
will try to query the maximum transmission unit (MTU) from the kernel
and size the maximum block size accordingly. If
.I slack
is specified, the MTU value will be adjusted downward by
.I slack
bytes.
.B tftp
does not request the option if the block size is set to 512.
.IP
The default is
.BR mtu .
.TP
\fB\-W\fP, \fB\-w\fP, \fB\-\-windowsize\fP \fIwindow-size\fP
Request the RFC 7440 \fBwindowsize\fP option. This permits up to
\fIwindow-size\fP data blocks to be sent before an acknowledgment is
required. Valid values are 1 through 32768.
.B tftp
does not request the option if the window size is set to 1.
.IP
The default is 64.
.TP
\fB\-T\fP, \fB\-\-no-tsize\fP
Disable the sending of the RFC 2349 \fBtsize\fP (transfer size) option. The
default is to send the option.
.TP
\fB\-N\fP, \fB\-\-no-options\fP
Do not request any TFTP options, for maximum compatibility with old
servers. This is equivalent to
.br
.RB \\[lq] "--blocksize 512 --windowsize 1 --no-tsize" \\[rq].
.TP
\fB\-U\fP, \fB\-\-unsafe\fP
Allow a TFTP response to come from a different address than the server
address to which the request was sent.
.IP
Some old TFTP servers have been known to return a response from a
network address other than the one to which the request was originally
sent. This increases the (already considerable) risk of connection
hijacking, and is therefore disallowed by default.
.TP
\fB\-R\fP, \fB\-\-port-range\fP \fImin-port:max-port\fP
Force the originating (local) port number to be in the specified range of port
numbers.
.TP
\fB\-v\fP, \fB\-\-verbose\fP
Default to verbose mode. If repeated, further increase the verbosity
level. At level 2 or higher, do not round byte counts in statistics or
use suffixes.
.TP
\fB\-\-verbosity\fP [\fIlevel\fP]
Set the verbosity level to
.IR level .
.TP
\fB\-V\fP, \fB\-\-version\fP
Print the version number and configuration to standard output, then
exit gracefully.
.TP
\fB\-h\fP, \fB\-\-help\fP [\fIcommand\fP]
If \fIcommand\fP is specified, print help text for \fIcommand\fP and
exit. Otherwise print a command line options summary and exit.
.IP
Use \fB\-c help\fP to get a list of commands available with \fB\-c\fP.
.SH "COMMANDS"
Once
.B tftp
is running, it issues the prompt
\fBtftp>\fP
and recognizes the following commands:
.TP
\fB?\fP \fIcommand-name...\fP
.TP
\fBhelp\fP \fIcommand-name...\fP
Print help information
.TP
.B ascii
Shorthand for
.RB \\[lq] "mode ascii" \\[rq].
.TP
.B binary
Shorthand for
.BR "mode binary" .
.TP
\fBconnect\fP \fIhost [port]\fP
Set the
.I host
(and optionally
.IR port )
for transfers. Note that the TFTP protocol, unlike the FTP protocol,
does not maintain connections between transfers; thus, the
.B connect
command does not actually create a connection, but merely remembers
what host is to be used for transfers. You do not have to use the
.B connect
command; the remote host can be specified as part of the
.B get
or
.B put
commands.
.TP
\fBget\fP \fIfile\fP
.sp -.6l
.TP
\fBget\fP \fIremotefile localfile\fP
.sp -.6l
.TP
\fBget\fP \fIfile1 file2 file3...\fP
Get a file or set of files from the specified sources. A remote
filename can be in one of two forms: a plain filename on the remote
host, if the host has already been specified, or a string of the form
.I host:filename
to specify both a host and filename at the same time. If the latter
form is used, the last hostname specified becomes the default for
future transfers. Enable
.B literal
mode to prevent special treatment of the ':' character (e.g. if the
desired filename is
.RB \\[lq] "C:\\edir\\efile" \\[rq]).
.TP
\fBmget\fP \fIfile1 file2 ... local-directory\fP
Get one or more files from the specified remote sources into
\fIlocal-directory\fP. Each remote filename can be a plain filename
on the configured remote host, or a string of the form
.I host:filename
to specify both a host and filename at the same time. If the latter
form is used, the last hostname specified becomes the default for
future transfers. Enable
.B literal
mode to prevent special treatment of the
.RB \\[lq] : \\[rq]
character (e.g. if the desired filename is
.RB \\[lq] "C:\\edir\\efile" \\[rq]).
.TP
.B literal
Toggle literal mode. When set, this mode prevents special treatment of ':' in filenames.
.TP
\fBmode\fP \fItransfer-mode\fP
Specify the mode for transfers;
.I transfer-mode
may be one of
.B netascii
(or
.BR ascii )
or
.B octet
(or
.BR binary .)
The default is
.BR octet .
.TP
\fBblocksize\fP \fIblock-size\fP
Set the requested block size to \fIblock-size\fP. See the
.B \-\-blocksize
command-line option.
.TP
\fBput\fP \fIfile\fP
.sp -.6l
.TP
\fBput\fP \fIlocalfile remotefile\fP
.sp -.6l
.TP
\fBput\fP \fIfile1 file2 file3... remote-directory\fP
Put a file or set of files to the specified remote file or directory.
The destination can be in one of two forms: a filename on the remote
host, if the host has already been specified, or a string of the form
.I host:filename
to specify both a host and filename at the same time. If the latter
form is used, the hostname specified becomes the default for future
transfers. If the remote-directory form is used, the remote host is
assumed to be a UNIX system or another system using
.B /
as directory separator. Enable
.B literal
mode to prevent special treatment of the ':' character (e.g. C:\\dir\\file).
.TP
\fBmput\fP \fIfile1 file2 ... remote-directory\fP
Put one or more files to \fIremote-directory\fP. The destination can
be a directory on the configured remote host, or a string of the form
.I host:directory
to specify both a host and directory at the same time. If the latter
form is used, the hostname specified becomes the default for future
transfers. The remote host is assumed to use
.B /
as directory separator. Enable
.B literal
mode to prevent special treatment of the ':' character (e.g. C:\\dir\\file).
.TP
.B quit
Exit
.BR tftp .
End-of-file will also exit.
.TP
\fBrexmt\fP \fIretransmission-timeout\fP
Set the initial per-packet retransmission timeout, in seconds. Each
subsequent retry doubles this interval.
.TP
.B status
Show current status.
.TP
\fBtimeout\fP \fItotal-transmission-timeout\fP
Set the maximum retransmission interval, in seconds.
.TP
\fBwindowsize\fP \fIwindow-size\fP
Request the RFC 7440 \fBwindowsize\fP option with \fIwindow-size\fP
data blocks per window. Valid values are 1 through 32768.
.TP
\fBtsize\fP
Toggle sending the RFC 2349 \fBtsize\fP (transfer size) option. The
default is on, unless the \fB\-\-no-tsize\fP command line option was
given.
.TP
\fBoptions\fP
Toggle the sending of TFTP options entirely. The default is enabled,
unless the \fB\-\-no-options\fP command line option was given. If
disabled, TFTP options are never sent; if enabled, TFTP options
.I may
be sent.
.TP
.B trace
Toggle packet tracing (a debugging feature.)
.TP
.B verbose
Toggle verbose mode.
.SH "NOTES"
The TFTP protocol provides no provisions for authentication or
security. Therefore, the remote server will probably implement some
kinds of access restriction or firewalling. These access restrictions
are likely to be site- and server-specific.
.SH "AUTHOR"
This version of
.B tftp
is maintained by H. Peter Anvin . It was derived from,
but has substantially diverged from, an OpenBSD source base, with
added patches by Markus Gutschke and Gero Kulhman.
.SH "SEE ALSO"
.BR tftpd (8).
tftp-hpa-7.2+20261013/tftp/tftp.c 0000664 0000000 0000000 00000063515 15263245305 0016114 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
* Copyright (C) 2026 H. Peter Anvin
*/
#include "common/tftpsubs.h"
#include "common/tftp-io.h"
#include "common/tftp-xfer.h"
#include "common/clock.h"
#include "options.h"
/*
* TFTP User Program -- Protocol Machines
*/
#include "extern.h"
struct peer {
union sock_addr addr; /* will be modified with transfer ID */
socklen_t addrlen;
union sock_addr myaddr; /* local address */
int sock; /* socket file descriptor */
bool connected; /* connected to a transfer ID */
};
static struct peer peer = { .sock = -1 };
static uintmax_t timeout;
static sigjmp_buf timeoutbuf;
static sigjmp_buf *active_timeoutbuf = &timeoutbuf;
struct optreq {
unsigned int options; /* Bitmap of options present */
unsigned int window;
unsigned int blksize;
off_t tsize;
};
/* Initialize a struct optreq with the default (no-option) values */
static inline struct optreq *optreq_init(struct optreq *optreq)
{
optreq->options = 0;
optreq->tsize = -1;
optreq->window = 1;
optreq->blksize = SEGSIZE;
return optreq;
}
static int nak(const char *, int, const char *);
static int makerequest(struct tftphdr **, struct optreq *,
int, const char *, const char *);
static bool
parse_oack(struct optreq *optack, const struct optreq *optreq,
const struct tftphdr *tp, int length);
static void printstats(const char *, uintmax_t);
static void startclock(void);
static void stopclock(void);
static void timer(int);
static void tpacket(const char *, const struct tftphdr *, int);
struct client_xfer_context {
union sock_addr from;
uintmax_t timeout;
};
static bool address_match(const union sock_addr *a, const union sock_addr *b)
{
if (a->sa.sa_family != b->sa.sa_family)
return false;
switch (a->sa.sa_family) {
case AF_INET:
return a->si.sin_addr.s_addr == b->si.sin_addr.s_addr;
#ifdef HAVE_IPV6
case AF_INET6:
return !!IN6_ARE_ADDR_EQUAL(&a->s6.sin6_addr, &b->s6.sin6_addr);
#endif
default:
return false; /* Not supported */
}
}
static int client_recv_time(void *packet, int length, union sock_addr *from,
uintmax_t *timeout_us_p)
{
socklen_t fromlen = sizeof(*from);
int n;
do {
n = tftp_recv_time(peer.sock, packet, length, 0, &from->sa, &fromlen,
timeout_us_p);
if (n < 0) {
if (errno == ETIMEDOUT)
timer(0); /* Should not return */
return n;
}
} while (n < 2 ||
!(address_match(&peer.addr, from) ||
(!peer.connected && copt.unsafe)));
if (!peer.connected) {
peer.addr = *from;
peer.addrlen = fromlen;
if (!connect(peer.sock, &from->sa, fromlen))
peer.connected = true;
}
return n;
}
static int client_xfer_send(void *vctx, const void *packet, int length)
{
(void)vctx;
if (copt.trace)
tpacket("sent", packet, length);
return sendto(peer.sock, packet, length, 0, &peer.addr.sa,
peer.addrlen) == length ? 0 : -1;
}
static int client_xfer_recv(void *vctx, void *packet, int length)
{
struct client_xfer_context *ctx = vctx;
return client_recv_time(packet, length, &ctx->from, &ctx->timeout);
}
static void client_xfer_received(void *vctx, const struct tftphdr *packet,
int length)
{
(void)vctx;
if (copt.trace)
tpacket("received", packet, length);
}
static void client_xfer_retry_enter(void *vctx, sigjmp_buf *retrybuf,
bool restarted)
{
(void)vctx;
active_timeoutbuf = retrybuf;
if (!restarted)
timeout = xopt.rexmtval;
}
static void client_xfer_retry_leave(void *vctx)
{
(void)vctx;
active_timeoutbuf = &timeoutbuf;
}
static void client_xfer_wait_begin(void *vctx)
{
struct client_xfer_context *ctx = vctx;
ctx->timeout = timeout;
}
static const struct tftp_xfer_ops client_xfer_ops = {
client_xfer_send,
client_xfer_recv,
client_xfer_received,
client_xfer_retry_enter,
client_xfer_retry_leave,
client_xfer_wait_begin
};
/*
* Printing error messages
*/
static void print_server_error(const char *file,
const struct tftphdr *packet, int packet_len)
{
char *error_str = errpkt_to_string(packet, packet_len);
fprintf(stderr, "%s: %s: server error: %s\n",
_progname, file, error_str);
xfree(error_str);
}
static void print_os_error(const char *file, const char *what, int err)
{
fprintf(stderr, "%s: %s: %s%s%s%s\n",
_progname, file,
what ? what : "",
what ? " error" : "error",
err ? ": " : "",
err ? strerror(err) : "");
}
static void print_proto_error(const char *file, const char *what)
{
fprintf(stderr, "%s: %s: server sent an invalid %s\n",
_progname, file, what);
}
/*
* The maximum possible size of an OACK packet plus at least one extra
* byte: the options we try to negotiate, plus their values; if the
* OACK packet is larger than this it is faulty.
*
* This is also used to size the buffer for the options part of a
* request packet.
*
* This is quite aggressively conservative since the numeric range of
* these options is way less than the total size of an uintmax_t, but
* the extra amount of memory is trivial and not worth worrying about.
*/
#define OPT_SPACE(x) (sizeof(x) + DIGIT_SPACE(uintmax_t) + 1)
#define TFTP_OPTION_SPACE \
(OPT_SPACE("blksize") + OPT_SPACE("windowsize") + OPT_SPACE("tsize"))
/*
* The maximum size of a reply packet (ACK, ERROR, OACK or
* default-sized DATA), that we care about. If an ERROR packet is
* unreasonably long, just truncate it.
*/
#define TFTP_REPLY_MAX_PACKET_SIZE MAX(TFTP_OPTION_SPACE+2, SEGSIZE+4)
static int open_socket(const char *name);
static inline void close_socket(void)
{
if (peer.sock >= 0) {
close(peer.sock);
peer.sock = -1;
}
}
static int open_socket(const char *name)
{
if (!serv.connected) {
fprintf(stderr, "%s: %s%sno server host selected\n",
_progname, name ? name : "", name ? ": " : "");
return EX_USAGE;
}
close_socket();
/*
* Since the return port ("transfer ID") is unknown, the socket
* cannot be connected at this point; set the peer.addr port
* to 0 to reflect that.
*/
peer.addr = serv.addr;
peer.addrlen = serv.addrlen;
peer.connected = false;
xzero(peer.myaddr);
peer.myaddr.sa.sa_family = peer.addr.sa.sa_family;
peer.sock = socket(peer.myaddr.sa.sa_family, SOCK_DGRAM, 0);
if (peer.sock < 0) {
print_os_error(name, "socket", errno);
return EX_OSERR;
}
if (pick_port_bind(peer.sock, &peer.myaddr)) {
print_os_error(name, "bind", errno);
close_socket();
return EX_OSERR;
}
return 0;
}
/*
* Send the requested file.
*/
int tftp_sendfile(int fd, const char *name, const char *mode)
{
struct tftphdr * volatile response;
struct tftphdr *req;
union sock_addr from;
FILE * volatile file = NULL;
struct tftp_io * volatile io = NULL;
struct client_xfer_context context;
struct tftp_xfer xfer;
struct tftp_xfer_result result;
int n, size;
volatile int err = 0;
bool convert = !strcmp(mode, "netascii");
struct optreq optreq, optack;
uint16_t ap_opcode, ap_block;
uintmax_t r_timeout;
volatile uintmax_t amount = 0;
struct stat st;
optreq_init(&optreq);
optreq_init(&optack);
err = open_socket(name);
if (err)
goto abort;
if (!convert && !fstat(fd, &st) && S_ISREG(st.st_mode))
optreq.tsize = st.st_size;
response = xmalloc(TFTP_REPLY_MAX_PACKET_SIZE);
startclock();
file = fdopen(fd, convert ? "rt" : "rb");
if (!file) {
print_os_error(name, "fdopen", errno);
close(fd);
err = EX_OSERR;
goto abort;
}
tftp_signal(SIGALRM, timer, 0);
size = makerequest(&req, &optreq, WRQ, name, mode);
if (size < 0) {
print_os_error(name, "request", errno);
err = EX_OSERR;
goto abort;
}
/* A peer which ignores options answers a WRQ with ACK 0. */
for (;;) {
timeout = xopt.rexmtval;
(void)sigsetjmp(timeoutbuf, 1);
if (copt.trace)
tpacket("sent", req, size);
if (sendto(peer.sock, req, size, 0, &peer.addr.sa, peer.addrlen)
!= size) {
print_os_error(name, "send", errno);
err = EX_OSERR;
goto abort;
}
r_timeout = timeout;
wait_for_reply:
n = client_recv_time(response, TFTP_REPLY_MAX_PACKET_SIZE,
&from, &r_timeout);
if (n < 0) {
print_os_error(name, "receive", errno);
err = EX_OSERR;
goto abort;
}
if (n < 2)
goto wait_for_reply;
if (copt.trace)
tpacket("received", response, n);
ap_opcode = ntohs(response->th_opcode);
if (ap_opcode == ERROR) {
print_server_error(name, response, n);
err = EX_PROTOCOL;
goto abort;
}
if (ap_opcode == OACK) {
if (!parse_oack(&optack, &optreq, response, n)) {
print_proto_error(name, "option response");
nak(name, EOPTNEG, "Invalid option response");
err = EX_PROTOCOL;
goto abort;
}
break;
}
if (n >= 4) {
ap_block = ntohs(response->th_block);
if (ap_opcode == ACK && ap_block == 0) {
/* Traditional server ignored options. */
break;
}
}
goto wait_for_reply;
}
xfree(req);
tftp_set_socket_buffers(peer.sock, optack.blksize, optack.window, true);
io = tftp_io_reader_start(file, convert, optack.window,
optack.window, optack.blksize, false);
if (!io) {
nak(name, -errno, NULL);
err = EX_OSERR;
goto abort;
}
xzero(xfer);
xfer.blocksize = optack.blksize;
xfer.windowsize = optack.window;
xfer.max_bytes = UINTMAX_MAX;
xfer.resend_oack = optack.window; /* THIS CAN'T BE RIGHT CHECK AGAIN */
xfer.control = response;
xfer.control_size = TFTP_REPLY_MAX_PACKET_SIZE;
xfer.context = &context;
xfer.ops = &client_xfer_ops;
xfer.io_context = io;
xfer.io_ops = &tftp_io_xfer_ops;
tftp_xfer_send(&xfer, &result);
amount = result.bytes;
tftp_io_stop(io);
io = NULL;
switch (result.status) {
case TFTP_XFER_READ_ERROR:
print_os_error(name, "file read", result.error);
nak(name, -result.error, NULL);
err = EX_OSERR;
break;
case TFTP_XFER_SEND_ERROR:
print_os_error(name, "send", result.error);
err = EX_OSERR;
break;
case TFTP_XFER_RECV_ERROR:
print_os_error(name, "receive", result.error);
err = EX_OSERR;
break;
case TFTP_XFER_PEER_ERROR:
{
print_server_error(name, result.packet, result.packet_len);
err = EX_PROTOCOL;
break;
}
default:
break;
}
abort:
tftp_io_stop(io);
if (file)
fclose(file);
xfree(response);
stopclock();
if (amount > 0)
printstats("Sent", amount);
close_socket();
return err;
}
/*
* Receive a file.
*/
int tftp_recvfile(int fd, const char *name, const char *mode)
{
union sock_addr from;
FILE * volatile file = NULL;
struct tftp_io * volatile io = NULL;
struct client_xfer_context context;
struct tftp_xfer xfer;
struct tftp_xfer_result result;
struct tftphdr *req = NULL;
struct tftphdr *ack = NULL;
struct tftphdr * volatile datapkt = NULL;
struct tftphdr *initial_packet = NULL;
struct tftphdr *initial_reply = NULL;
volatile int initial_reply_len = 0;
volatile int initial_packet_len = -1;
int n, size;
volatile int err = 0;
bool convert = !strcmp(mode, "netascii");
struct optreq optreq, optack;
uint16_t opcode;
unsigned long r_timeout;
volatile uintmax_t amount = 0;
optreq_init(&optreq);
optreq.tsize = 0;
optreq_init(&optack);
err = open_socket(name);
if (err)
goto abort;
startclock();
file = fdopen(fd, convert ? "wt" : "wb");
if (!file) {
print_os_error(name, "fdopen", errno);
close(fd);
err = EX_OSERR;
goto abort;
}
initial_packet = xmalloc(TFTP_REPLY_MAX_PACKET_SIZE);
size = makerequest(&req, &optreq, RRQ, name, mode);
if (size < 0) {
print_os_error(name, "request", errno);
err = EX_OSERR;
goto abort;
}
tftp_signal(SIGALRM, timer, 0);
/* RFC 7440 peers answer with OACK; legacy peers start with DATA 1. */
for (;;) {
timeout = xopt.rexmtval;
(void)sigsetjmp(timeoutbuf, 1);
if (copt.trace)
tpacket("sent", req, size);
if (sendto(peer.sock, req, size, 0, &peer.addr.sa, peer.addrlen) != size) {
print_os_error(name, "send", errno);
err = EX_OSERR;
goto abort;
}
r_timeout = timeout;
wait_for_reply:
n = client_recv_time(initial_packet, TFTP_REPLY_MAX_PACKET_SIZE,
&from, &r_timeout);
if (n < 0) {
print_os_error(name, "receive", errno);
err = EX_OSERR;
goto abort;
}
initial_packet_len = n;
if (n < 2)
goto wait_for_reply;
opcode = ntohs(initial_packet->th_opcode);
if (copt.trace)
tpacket("received", initial_packet, n);
if (opcode == ERROR) {
print_server_error(name, initial_packet, n);
err = EX_PROTOCOL;
goto abort;
}
if (opcode == OACK) {
if (!parse_oack(&optack, &optreq, initial_packet, n)) {
print_proto_error(name, "option response");
nak(name, EOPTNEG, "Invalid option response");
err = EX_PROTOCOL;
goto abort;
}
initial_reply = initial_packet; /* Reuse buffer */
initial_packet = NULL;
initial_packet_len = 0;
initial_reply->th_opcode = htons(ACK);
initial_reply->th_block = 0;
initial_reply_len = 4;
} else if (opcode == DATA && n >= 4 &&
ntohs(initial_packet->th_block) == 1) {
/* Peer ignored/rejected requested options. */
break;
} else {
goto wait_for_reply;
}
break;
}
xdelete(req);
tftp_set_socket_buffers(peer.sock, optack.blksize, optack.window, false);
io = tftp_io_writer_start(file, convert, optack.window, optack.blksize,
false);
if (!io) {
nak(name, -errno, NULL);
err = EX_OSERR;
goto abort;
}
/* +5 to allow overrun detection when MSG_TRUNC is not supported */
datapkt = xmalloc(optack.blksize + 5);
xzero(xfer);
xfer.blocksize = optack.blksize;
xfer.windowsize = optack.window;
xfer.max_bytes = UINTMAX_MAX;
xfer.context = &context;
xfer.ops = &client_xfer_ops;
xfer.io_context = io;
xfer.io_ops = &tftp_io_xfer_ops;
tftp_xfer_recv(&xfer, datapkt, optack.blksize + 5,
&initial_reply, initial_reply_len,
&initial_packet, initial_packet_len,
&result);
amount = result.bytes;
tftp_io_stop(io);
io = NULL;
switch (result.status) {
case TFTP_XFER_BAD_DATA:
print_proto_error(name, "data packet");
nak(name, EBADOP, "Data packet too large");
err = EX_PROTOCOL;
break;
case TFTP_XFER_WRITE_ERROR:
print_os_error(name, "file write", result.error);
nak(name, -result.error, NULL);
err = EX_OSERR;
break;
case TFTP_XFER_SEND_ERROR:
print_os_error(name, "send", result.error);
err = EX_OSERR;
break;
case TFTP_XFER_RECV_ERROR:
print_os_error(name, "receive", result.error);
err = EX_OSERR;
break;
case TFTP_XFER_PEER_ERROR:
print_server_error(name, result.packet, result.packet_len);
err = EX_PROTOCOL;
break;
default:
break;
}
if (optack.tsize >= 0 && amount != (uintmax_t)optack.tsize) {
fprintf(stderr, "%s: %s: warning: expected %"PRIuMAX" bytes "
"received %"PRIuMAX"\n",
_progname, name, (uintmax_t)optack.tsize, amount);
}
abort:
tftp_io_stop(io);
xdelete(datapkt);
xdelete(initial_packet);
xdelete(ack);
xdelete(req);
if (file)
fclose(file);
stopclock();
if (amount > 0)
printstats("Received", amount);
close_socket();
return err;
}
static int
makerequest(struct tftphdr **pkt, struct optreq *optreq,
int request, const char *name, const char *mode)
{
struct tftphdr *tp;
char *cp;
char optionbuf[TFTP_OPTION_SPACE];
size_t namelen, modelen, optionlen;
size_t pktsize;
namelen = strlen(name) + 1;
modelen = strlen(mode) + 1;
cp = optionbuf;
if (copt.no_options) {
/* Reset all options */
optreq_init(optreq);
} else {
/* Set default or configured options */
optreq->options = 0;
optreq->blksize = tftp_max_blksize(peer.sock, &peer.addr);
optreq->window = xopt.max_windowsize;
if (optreq->blksize != SEGSIZE) {
optreq->options |= 1 << PO_BLKSIZE;
cp = mempcpy(cp, "blksize", sizeof "blksize");
cp += snprintf(cp, sizeof optionbuf - (cp - optionbuf),
"%u", optreq->blksize) + 1;
}
if (optreq->window > 1) {
optreq->options |= 1 << PO_WINDOWSIZE;
cp = mempcpy(cp, "windowsize", sizeof "windowsize");
cp += snprintf(cp, sizeof optionbuf - (cp - optionbuf),
"%u", optreq->window) + 1;
} else {
optreq->window = 1;
}
if (optreq->tsize >= 0) {
optreq->options |= 1 << PO_TSIZE;
cp = mempcpy(cp, "tsize", sizeof "tsize");
cp += snprintf(cp, sizeof optionbuf - (cp - optionbuf),
"%"PRIuMAX, (uintmax_t)optreq->tsize) + 1;
}
}
optionlen = cp - optionbuf;
/*
* The request is encoded into tp as: opcode(2) name NUL mode NUL.
* tpsize is the total size of the buffer tp points to; reject
* anything that would not fit rather than overflowing it. Compare
* with subtraction on the tpsize side only, so there is no risk of
* namelen/modelen (both attacker/user-controlled) underflowing an
* unsigned computation.
*/
if (namelen + modelen + optionlen > MAX_SEGSIZE) {
errno = ENAMETOOLONG;
return -1;
}
pktsize = namelen + modelen + optionlen + 2;
*pkt = tp = xmalloc(pktsize);
tp->th_opcode = htons(request);
cp = (char *)&(tp->th_stuff);
cp = mempcpy(cp, name, namelen);
cp = mempcpy(cp, mode, modelen);
memcpy(cp, optionbuf, optionlen);
return pktsize;
}
/*
* RFC 2347 requires an OACK to contain only requested options. The
* client accepts only options it requested, and rejects malformed,
* duplicate, or unexpected option pairs.
*/
static bool
parse_oack(struct optreq *optack, const struct optreq *optreq,
const struct tftphdr *tp, int length)
{
const char *cp, *end, *nul;
char *value_end;
uintmax_t value;
optreq_init(optack);
if (length <= 2 || ntohs(tp->th_opcode) != OACK)
return false;
cp = (const char *)&tp->th_stuff;
end = (const char *)tp + length;
while (cp < end) {
/* Bitmask of repeated or non-requested options */
const unsigned int badopts = optack->options | ~optreq->options;
const char *option = cp;
nul = memchr(cp, '\0', (size_t)(end - cp));
if (!nul || nul == cp)
return false;
cp = nul + 1;
if (cp >= end)
return false;
nul = memchr(cp, '\0', (size_t)(end - cp));
if (!nul || nul == cp)
return false;
errno = 0;
value = strtoumax(cp, &value_end, 10);
if (errno || value_end != nul)
return false;
if (ascii_strcaseeq(option, "blksize")) {
if ((badopts & (1 << PO_BLKSIZE)) ||
value < MIN_SEGSIZE || value > optreq->blksize)
return false;
optack->blksize = value;
optack->options |= 1 << PO_BLKSIZE;
} else if (ascii_strcaseeq(option, "windowsize")) {
if ((badopts & (1 << PO_WINDOWSIZE)) ||
value < 1 || value > optreq->window)
return false;
optack->window = value;
optack->options |= 1 << PO_WINDOWSIZE;
} else if (ascii_strcaseeq(option, "tsize")) {
if (badopts & (1 << PO_TSIZE))
return false;
optack->tsize = value;
optack->options = 1 << PO_TSIZE;
} else {
/* Server sent us a unknown, unrequested option response... */
return false;
}
cp = nul + 1;
}
/*
* This allows a null OACK packet, which is technically wrong, but
* there really isn't any reason to disallow it, either.
*/
return true;
}
/*
* Send a nak packet (error message).
*
* Error code passed in is one of the standard TFTP codes, or a
* negative errno value.
*/
static int nak(const char *name, int error, const char *msg)
{
struct tftphdr *tp;
int length;
int err = 0;
length = make_errpacket(&tp, error, msg);
if (copt.trace)
tpacket("sent", tp, length);
if (sendto(peer.sock, tp, length, 0,
&peer.addr.sa, peer.addrlen) != length) {
err = errno;
if (name)
print_os_error(name, "send", err);
}
xfree(tp);
return err;
}
static void tpacket(const char *s, const struct tftphdr *tp, int n)
{
uint16_t op = ntohs(tp->th_opcode);
const char *on;
const char *pfx = "";
printf("%s %s (%u): ", s, packet_type(op), op);
switch (op) {
case RRQ:
case WRQ:
{
int fl, ml;
const char *file, *mode;
n -= 2; /* Skip header */
file = tp->th_stuff;
fl = n > 0 ? strnlen(file, n) : 0;
n -= fl + 1;
mode = file + fl + 1;
ml = n > 0 ? strnlen(mode, n) : 0;
n -= ml + 1;
on = mode + ml + 1;
printf("file \"%*s\", mode %*s", fl, file, ml, mode);
pfx = ", ";
goto print_options;
}
break;
case DATA:
printf("block %u, %d bytes\n", ntohs(tp->th_block), n - 4);
break;
case ACK:
printf("block %u\n", ntohs(tp->th_block));
break;
case ERROR:
printf("code %u, \"%*s\"\n", ntohs(tp->th_code), n-2, tp->th_msg);
break;
case OACK:
n -= 2; /* Skip header */
on = tp->th_stuff;
goto print_options;
print_options:
while (n > 0) {
const char *ov;
int nl, vl;
nl = strnlen(on, n);
n -= nl + 1;
ov = on + nl + 1;
vl = n > 0 ? strnlen(ov, n) : 0;
n -= vl + 1;
on = ov + vl + 1;
printf("%s%*s %*s", pfx, nl, on, vl, ov);
pfx = ", ";
}
putchar('\n');
break;
default:
if (n > 2)
printf("%+d bytes\n", n-2);
break;
}
}
static uintmax_t tstart, tstop;
static inline void startclock(void)
{
tstart = clock_us();
}
static inline void stopclock(void)
{
tstop = clock_us();
}
#define PWS_BINARY 1
#define PWS_EXACT 2
static bool print_with_suffix(double val, unsigned int flags)
{
static const char *const dsuffixes[] = {
"", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q", NULL
};
static const char *const bsuffixes[] = {
"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi", "Ri", "Qi", NULL
};
const char *const *suffix = flags & PWS_BINARY ? bsuffixes : dsuffixes;
double divisor = (flags & PWS_BINARY) ? 1024.0 : 1000.0;
int decimals;
bool with_suffix = false;
if (copt.verbose < 2) {
while (val >= divisor && suffix[1]) {
suffix++;
val /= divisor;
flags &= ~PWS_EXACT; /* Not exact once divided down */
with_suffix = true;
}
}
decimals = 0;
if (!(flags & PWS_EXACT)) {
if (val < 9.995)
decimals = 2;
else if (val < 99.95)
decimals = 1;
}
printf("%0.*f %s", decimals, val, *suffix);
return with_suffix;
}
static void printstats(const char *direction, uintmax_t amount)
{
if (copt.verbose) {
double delta = (tstop - tstart) * 1.0e-6;
bool with_suffix;
fputs(direction, stdout);
putchar(' ');
if (copt.verbose > 1 || amount < 9999) {
printf("%" PRIuMAX " bytes", amount);
} else {
with_suffix = print_with_suffix(amount, PWS_EXACT);
putchar('B');
if (with_suffix) {
fputs(" (", stdout);
print_with_suffix(amount, PWS_EXACT|PWS_BINARY);
fputs("B)", stdout);
}
}
printf(" in %.3f s [", delta);
print_with_suffix((amount << 3)/delta, 0);
fputs("bit/s]\n", stdout);
}
}
static void timer(int sig)
{
int save_errno = errno;
(void)sig; /* Shut up unused warning */
timeout <<= 1;
if (timeout > copt.maxtimeout) {
errno = save_errno;
siglongjmp(toplevel, EX_TEMPFAIL);
}
errno = save_errno;
siglongjmp(*active_timeoutbuf, 1);
}
tftp-hpa-7.2+20261013/tftp/version.c 0000664 0000000 0000000 00000000702 15263245305 0016611 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#include "common/tftpsubs.h"
#include "version.h"
#ifdef WITH_READLINE
#define WITH_READLINE_STR "yes"
#else
#define WITH_READLINE_STR "no"
#endif
const char version_string[] = VERSION;
void print_configuration(FILE *f)
{
fprintf(f, "%s\n"
"Readline: %s\n",
version_string,
WITH_READLINE_STR);
}
tftp-hpa-7.2+20261013/tftpd/ 0000775 0000000 0000000 00000000000 15263245305 0015125 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/tftpd/Makefile 0000664 0000000 0000000 00000001643 15263245305 0016571 0 ustar 00root root 0000000 0000000 # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 1999-2006 H. Peter Anvin
# Copyright (c) 2024-2026 Intel Corporation; Author: H. Peter Anvin
SRCROOT = ..
VERSION = $(shell cat ../version)
-include ../config/MCONFIG
include ../MRULES
OBJS = tftpd.$(O) recvfrom.$(O) misc.$(O) path.$(O) listen.$(O) \
strlist.$(O) remap.$(O) cap.$(O) logging.$(O) version.$(O)
all: tftpd$(X) tftpd.8
tftpd$(X): $(OBJS) $(filter %.a,$(TFTPD_LIBS))
$(CC) $(CFLAGS) $(LDFLAGS) -o tftpd$(X) $(OBJS) $(TFTPD_LIBS)
tftpd.8: tftpd.8.in ../version
sed -e 's/@@VERSION@@/$(VERSION)/g' < tftpd.8.in > tftpd.8
install: all
mkdir -p $(INSTALLROOT)$(SBINDIR) $(INSTALLROOT)$(MANDIR)/man8
$(INSTALL_PROGRAM) tftpd$(X) $(INSTALLROOT)$(SBINDIR)/in.tftpd$(X)
$(INSTALL_DATA) tftpd.8 $(INSTALLROOT)$(MANDIR)/man8/in.tftpd.8
cd $(INSTALLROOT)$(MANDIR)/man8 && $(LN_S) -f in.tftpd.8 tftpd.8
clean:
rm -f tftpd tftpsubs.c tftpsubs.h tftpd.8
tftp-hpa-7.2+20261013/tftpd/cap-linux.c 0000664 0000000 0000000 00000013432 15263245305 0017174 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* cap-linux.c
*
* Linux capability management
*/
#include "tftpd.h"
#include "options.h"
#include
#include
/* A bitmask of the privileges that need to be reserved or retained */
enum priv_mask {
PRIV_NONE = 0,
PRIV_LISTEN = 1,
PRIV_PORTRANGE = 2,
PRIV_CHROOT = 4,
PRIV_SETUID = 8,
PRIV_SETGID = 16,
PRIV_ALL = 31
};
struct need_priv {
enum priv_mask when;
cap_value_t cap;
};
static const struct need_priv need_privs[] =
{
{ PRIV_LISTEN, CAP_NET_BIND_SERVICE },
{ PRIV_PORTRANGE, CAP_NET_BIND_SERVICE },
{ PRIV_CHROOT, CAP_SYS_CHROOT },
{ PRIV_SETUID, CAP_SETUID },
{ PRIV_SETGID, CAP_SETGID },
};
/*
* Set the current capability set to "now", unless already dropped;
* permanently drop all in the "drop" set.
*
* If a bit is set in both the "now" and "drop" set, it will actually be
* dropped on the *next* call.
*/
static void capset_privs(enum priv_mask now, enum priv_mask drop)
{
static enum priv_mask effective;
static enum priv_mask permitted;
static enum priv_mask dropped;
enum priv_mask keep;
static cap_t ocap = NULL;
static bool ocap_failed = false;
cap_t ncap = NULL;
const struct need_priv *np;
int err;
dropped |= drop;
if (!ocap) {
if (ocap_failed)
return;
ocap = cap_get_proc();
if (!ocap) {
if (errno != EPERM)
goto fail;
tftpd_log(LOG_WARNING,
"failed to query capabilities, cannot drop: %s",
strerror(errno));
ocap_failed = true;
return;
}
/*
* Compute the effective and permitted set as per enum priv_mask
*/
permitted = PRIV_ALL;
ARRAY_FOREACH(np, need_privs) {
cap_flag_value_t v;
if (cap_get_flag(ocap, np->cap, CAP_PERMITTED, &v) || !v)
permitted &= ~np->when;
}
dropped |= PRIV_ALL & ~permitted; /* In effect, already dropped */
now &= permitted;
keep = permitted & (now | ~dropped);
/* Never bypass the cap setting the first time */
} else {
now &= permitted;
keep = permitted & (now | ~dropped);
if (now == effective && keep == permitted)
return; /* Nothing to do */
}
ncap = cap_init();
if (!ncap)
goto fail;
/*
* ncap is empty at this point. Note that the inheritable
* capability set is left as at all times, since tftpd should
* never exec() anything.
*/
ARRAY_FOREACH(np, need_privs) {
if (np->when & keep) {
cap_set_flag(ncap, CAP_PERMITTED, 1, &np->cap, CAP_SET);
if (np->when & now)
cap_set_flag(ncap, CAP_EFFECTIVE, 1, &np->cap, CAP_SET);
}
}
if (cap_compare(ocap, ncap) && cap_set_proc(ncap))
goto fail;
effective = now;
permitted = keep;
ocap = ncap;
ncap = NULL;
err = 0;
goto finish;
fail:
err = errno;
finish:
if (ncap)
cap_free(ncap);
if (err) {
tftpd_log(LOG_CRIT, "failed to drop unwanted capabilities: %s",
strerror(err));
exit(EX_NOPERM);
}
}
static bool can_drop_setuid(uid_t uid)
{
uid_t ruid, euid, suid;
if (getresuid(&ruid, &euid, &suid))
return errno == EPERM;
return uid == ruid || uid == euid || uid == suid;
}
static bool can_drop_setgid(gid_t gid)
{
gid_t rgid, egid, sgid;
int ngroups, i;
gid_t *list;
bool ok;
if (getresgid(&rgid, &egid, &sgid))
return errno == EPERM;
if (gid == rgid || gid == egid || gid == sgid)
return true;
ngroups = getgroups(0, NULL);
if (ngroups < 0)
return false;
list = xmalloc(ngroups * sizeof(gid_t));
ngroups = getgroups(ngroups, list);
/* This implicitly handles ngroups < 0 */
ok = false;
for (i = 0; i < ngroups; i++) {
if (gid == list[i]) {
ok = true;
break;
}
}
xfree(list);
return ok;
}
static uintmax_t read_uint_file(const char *file)
{
uintmax_t val;
FILE *f = fopen(file, "r");
if (!f)
return -1ULL;
if (fscanf(f, "%"SCNuMAX, &val) < 1)
val = -1ULL;
fclose(f);
return val;
}
static bool portrange_needs_priv_ports(void)
{
uintmax_t unpriv;
if (!xopt.portrange_from)
return false;
unpriv = read_uint_file("/proc/sys/net/ipv4/ip_unprivileged_port_start");
return xopt.portrange_from < unpriv;
}
void capset_none(void)
{
capset_privs(PRIV_NONE, PRIV_NONE);
}
void capset_before_initgroups(void)
{
enum priv_mask drop = 0;
if (!dopt.standalone)
drop |= PRIV_LISTEN;
if (!portrange_needs_priv_ports())
drop |= PRIV_PORTRANGE;
if (!dopt.secure)
drop |= PRIV_CHROOT;
if (can_drop_setuid(dopt.user.pw->pw_uid))
drop |= PRIV_SETUID;
capset_privs(PRIV_SETGID, drop);
}
void capset_after_initgroups(void)
{
enum priv_mask drop = 0;
if (can_drop_setgid(dopt.user.pw->pw_gid))
drop |= PRIV_SETGID;
capset_privs(PRIV_NONE, drop);
}
/* --- these two are called only if standalone --- */
void capset_before_listen(void)
{
capset_privs(PRIV_LISTEN, PRIV_LISTEN);
}
void capset_before_socket_bind(void)
{
capset_privs(PRIV_PORTRANGE, PRIV_PORTRANGE);
}
void capset_before_chroot(void)
{
capset_privs(PRIV_CHROOT, PRIV_CHROOT);
}
void capset_before_setid(void)
{
capset_privs(PRIV_SETUID|PRIV_SETGID, PRIV_ALL);
}
void capset_drop_all(void)
{
capset_privs(PRIV_NONE, PRIV_ALL);
}
const char *capset_get_type(void)
{
return "Linux";
}
tftp-hpa-7.2+20261013/tftpd/cap-none.c 0000664 0000000 0000000 00000000762 15263245305 0016776 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* cap-none.c
*
* Dummy capability hooks
*/
void capset_none(void) { }
void capset_before_initgroups(void) { }
void capset_after_initgroups(void) { }
void capset_before_listen(void) { }
void capset_before_socket_bind(void) { }
void capset_before_chroot(void) { }
void capset_before_setid(void) { }
void capset_drop_all(void) { }
const char *capset_get_type(void)
{
return "none";
}
tftp-hpa-7.2+20261013/tftpd/cap.c 0000664 0000000 0000000 00000000710 15263245305 0016032 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* cap.c
*
* Capabilities handling
*/
#include "cap.h"
#define CAP_TYPE_NONE 0
#define CAP_TYPE_LINUX 1
#ifdef HAVE_CAP_SET_PROC
#ifdef __linux__
#define CAP_TYPE CAP_TYPE_LINUX
#endif
#endif
#ifndef CAP_TYPE
#define CAP_TYPE CAP_TYPE_NONE
#endif
#if CAP_TYPE == CAP_TYPE_LINUX
#include "cap-linux.c"
#else
#include "cap-none.c"
#endif
tftp-hpa-7.2+20261013/tftpd/cap.h 0000664 0000000 0000000 00000001036 15263245305 0016041 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
/*
* cap.h
*
* Capabilities handling hooks
*/
#ifndef TFTPD_CAP_H
#define TFTPD_CAP_H 1
#include "config.h"
void capset_none(void);
void capset_before_initgroups(void);
void capset_after_initgroups(void);
void capset_before_listen(void);
void capset_before_socket_bind(void);
void capset_before_chroot(void);
void capset_before_setid(void);
void capset_drop_all(void);
const char *capset_get_type(void);
#endif /* TFTPD_CAP_H */
tftp-hpa-7.2+20261013/tftpd/listen.c 0000664 0000000 0000000 00000006721 15263245305 0016575 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
/*
* Create sockets for and listen on one or more addresses, and add
* them to a given pollset. If ai_fam is not AI_UNSPEC, only listen on
* that specific family.
*/
#include "config.h" /* Must be included first */
#include "tftpd.h"
#include "options.h"
#include "common/pollset.h"
#ifndef AI_IDN
#define AI_IDN 0
#endif
int listen_to(struct pollset *set, const char *name, sa_family_t ai_fam)
{
char *ns = xstrdup(name);
char *np = ns;
const char *hostname = ns;
const char *service = NULL;
struct addrinfo hints;
struct addrinfo *addrs = NULL;
const struct addrinfo *ai;
int err = EINVAL;
int nsockets = 0;
#ifndef HAVE_IPV6
ai_fam = AF_INET;
#endif
memset(&hints, 0, sizeof(hints));
hints.ai_family = ai_fam;
hints.ai_flags = AI_PASSIVE | AI_IDN;
hints.ai_socktype = SOCK_DGRAM;
/* Allow a bracketed hostname (e.g. IPv6 address) */
if (*np == '[') {
hostname = ++np;
while (*np) {
if (*np == ']') {
*np++ = '\0';
break;
}
np++;
}
if (*np == ':')
service = np+1;
} else if (*np == '*' || *np == ':') {
hostname = "";
if (*np == '*')
np++;
if (*np == ':')
service = np+1;
} else {
hostname = np;
while (*np) {
if (*np == ':') {
*np++ = '\0';
service = np;
break;
}
np++;
}
}
if (!*hostname)
hostname = NULL;
if (!service || !*service)
service = dopt.service;
err = getaddrinfo(hostname, service, &hints, &addrs);
if (err) {
tftpd_log(LOG_ERR,
"cannot resolve local %sbind address: %s:%s (%s)",
net_family(ai_fam), hostname ? hostname : "*",
service, gai_strerror(err));
err = ENOENT;
goto fail;
}
for (ai = addrs; ai; ai = ai->ai_next) {
int fd;
if (ai_fam != AF_UNSPEC && ai->ai_family != ai_fam)
continue;
if (ai->ai_socktype != SOCK_DGRAM)
continue;
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd < 0) {
err = errno;
tftpd_log(LOG_ERR, "failed to create %ssocket: %s",
net_family(ai->ai_family), strerror(err));
continue;
}
switch (ai->ai_family) {
case AF_INET:
#ifdef IP_FREEBIND
setsockint(fd, IPPROTO_IP, IP_FREEBIND, 1);
#endif
break;
#ifdef HAVE_IPV6
case AF_INET6:
#ifdef IPV6_FREEBIND
setsockint(fd, IPPROTO_IPV6, IPV6_FREEBIND, 1);
#endif
#ifdef IPV6_V6ONLY
setsockint(fd, IPPROTO_IPV6, IPV6_V6ONLY, 1);
#endif
break;
#endif
default:
break;
}
if (bind(fd, ai->ai_addr, ai->ai_addrlen)) {
char *aname;
err = errno;
aname = net_address(ai->ai_addr, ai->ai_addrlen);
tftpd_log(LOG_ERR, "failed to bind to %s: %s",
aname, strerror(err));
xfree(aname);
continue;
}
nsockets++;
pollset_add(set, fd);
}
if (nsockets)
err = 0;
fail:
if (addrs)
freeaddrinfo(addrs);
xfree(ns);
return err;
}
tftp-hpa-7.2+20261013/tftpd/logging.c 0000664 0000000 0000000 00000011473 15263245305 0016725 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 1999-2009, 2026 H. Peter Anvin
* Copyright (c) 2011-2014 Intel Corporation; author: H. Peter Anvin
* All rights reserved.
*/
#include "config.h" /* Must be included first */
#include "options.h"
#include "tftpd.h"
/*
* Logging framework
*/
static void tftpd_log_file(int priority, const char *fmt, ...);
static void tftpd_log_file_tagged(int priority, const char *fmt, ...);
static void tftpd_reopenlog_file(void);
static void tftpd_reopenlog_syslog(void);
static void tftpd_rotatelog_file(void);
static const struct tftpd_log_ops log_ops_file = {
.log = tftpd_log_file,
.reopen_log = tftpd_reopenlog_file,
.rotate_log = tftpd_rotatelog_file,
};
static const struct tftpd_log_ops log_ops_file_tagged = {
.log = tftpd_log_file_tagged,
.reopen_log = tftpd_reopenlog_file,
.rotate_log = tftpd_rotatelog_file,
};
static const struct tftpd_log_ops log_ops_syslog = {
.log = syslog,
.reopen_log = tftpd_reopenlog_syslog,
.rotate_log = tftpd_reopenlog_syslog,
};
const struct tftpd_log_ops *log_ops = &log_ops_file;
static FILE *log_filehandle;
static const char *prio_name(unsigned int priority)
{
static const char * const log_markers[] = {
/* Human readable */
[LOG_EMERG] = "emergency: ",
[LOG_ALERT] = "alert: ",
[LOG_CRIT] = "critical: ",
[LOG_ERR] = "error: ",
[LOG_WARNING] = "warning: ",
[LOG_NOTICE] = "notice: ",
[LOG_INFO] = "info: ",
[LOG_DEBUG] = "debug: "
};
const char *tag;
if (unlikely(priority >= ARRAY_SIZE(log_markers)))
return "";
tag = log_markers[priority];
if (unlikely(!tag))
return "";
return tag;
}
static void tftpd_log_file(int priority, const char *fmt, ...)
{
va_list ap;
fprintf(log_filehandle, "%s[%lu]: %s",
_progname ? _progname : "tftpd",
(unsigned long)_progpid,
prio_name(priority));
va_start(ap, fmt);
vfprintf(log_filehandle, fmt, ap);
va_end(ap);
putc('\n', log_filehandle);
}
static void tftpd_log_file_tagged(int priority, const char *fmt, ...)
{
va_list ap;
fprintf(log_filehandle, "<%d>", priority);
va_start(ap, fmt);
vfprintf(log_filehandle, fmt, ap);
va_end(ap);
putc('\n', log_filehandle);
}
/*
* dup() stdout/stderr when used as log output so that closing the
* standard descriptors doesn't break anything.
*/
static void tftpd_openlog_fd(int new_fd)
{
FILE *old_fh = log_filehandle;
int old_fd;
if (new_fd <= 2) {
int dup_fd = dup(new_fd);
if (dup_fd < 0) {
fprintf(stderr, "%s: dup(%d) for logging failed: %s\n",
_progname, new_fd, strerror(errno));
exit(EX_OSERR);
}
new_fd = dup_fd;
}
fflush(NULL);
old_fd = fileno(old_fh);
if (old_fd != new_fd) {
FILE *new_fh;
new_fh = fdopen(new_fd, "at");
if (new_fh) {
if (old_fd > 2)
fclose(old_fh);
setvbuf(new_fh, NULL, _IOLBF, BUFSIZ);
log_filehandle = new_fh;
log_ops = dopt.log_tagged ? &log_ops_file_tagged : &log_ops_file;
} else {
if (new_fd > 2)
close(new_fd);
fprintf(stderr, "%s: fdopen for logging failed: %s\n",
_progname, strerror(errno));
exit(EX_OSERR);
}
}
}
static void tftpd_openlog_file(bool rotate)
{
const char * const path = dopt.logfile;
int fd;
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd < 0) {
tftpd_log(rotate ? LOG_ERR : LOG_CRIT,
"cannot %s log file '%s': %s",
rotate ? "reopen" : "open", path, strerror(errno));
if (!rotate)
exit(EX_CANTCREAT);
} else {
tftpd_openlog_fd(fd);
}
}
static void tftpd_reopenlog_file(void)
{
fflush(log_filehandle);
}
static void tftpd_rotatelog_file(void)
{
if (dopt.log_type == LOG_FILE)
tftpd_openlog_file(true);
}
static void tftpd_openlog_syslog(void)
{
openlog(_progname, LOG_PID | LOG_NDELAY, LOG_DAEMON);
log_ops = &log_ops_syslog;
}
static void tftpd_reopenlog_syslog(void)
{
closelog();
tftpd_openlog_syslog();
}
/* This should be run very early, after set_progname() */
void tftpd_initlog(void)
{
/* Temporarily log directly to stderr */
log_filehandle = stderr;
log_ops = &log_ops_file;
}
void tftpd_openlog(void)
{
switch (dopt.log_type) {
case LOG_SYS:
tftpd_openlog_syslog();
break;
case LOG_STDOUT: /* == 1 */
case LOG_STDERR: /* == 2 */
tftpd_openlog_fd(dopt.log_type);
break;
case LOG_FILE:
tftpd_openlog_file(false);
break;
default:
break;
}
}
tftp-hpa-7.2+20261013/tftpd/misc.c 0000664 0000000 0000000 00000001266 15263245305 0016231 0 ustar 00root root 0000000 0000000 /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright 2001-2026 H. Peter Anvin - All Rights Reserved */
/*
* misc.c
*
* Minor help routines.
*/
#include "tftpd.h"
/*
* Set the signal handler and flags, and error out on failure.
*/
void set_signal(int signum, sighandler_t handler, int flags)
{
if (tftp_signal(signum, handler, flags)) {
tftpd_log(LOG_ERR, "sigaction: %s", strerror(errno));
exit(EX_OSERR);
}
}
/*
* Set a signal mask and die on failure
*/
void tftpd_sigmask(int how, const sigset_t *set, sigset_t *oset)
{
if (tftp_sigmask(how, set, oset)) {
tftpd_log(LOG_ERR, "sigmask: %s", strerror(errno));
exit(EX_OSERR);
}
}
tftp-hpa-7.2+20261013/tftpd/options.h 0000664 0000000 0000000 00000003160 15263245305 0016771 0 ustar 00root root 0000000 0000000 /* ----------------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin - All Rights Reserved
*
* ----------------------------------------------------------------------- */
/*
* Parsed tftpd command-line configuration.
*/
#ifndef TFTPD_OPTIONS_H
#define TFTPD_OPTIONS_H
#include "config.h"
#include "common/options.h"
#include "strlist.h"
#define DAEMON_DEFAULT_MAP_STEPS 4096 /* Timeout after this many steps */
enum normalizations {
NORM_NONE,
NORM_ROOT,
NORM_PATH
};
enum log_type {
LOG_SYS,
LOG_STDOUT, /* MUST BE 1 */
LOG_STDERR, /* MUST BE 2 */
LOG_FILE
};
struct daemon_options {
bool readonly;
bool cancreate;
bool secure;
bool jail;
bool validate;
bool unixperms;
bool standalone;
bool nodaemon;
bool systemd;
bool reject_all_options;
bool spec_umask;
enum log_type log_type;
bool log_tagged;
uintmax_t max_upload;
uintmax_t max_windowbytes;
int verbosity;
int map_steps;
int mtu_adj;
intmax_t waittime;
mode_t my_umask;
const char *service;
const char *logfile;
const char *path_prefix;
const char *rewrite_file;
const char *map_test_file;
const char *pidfile;
struct strlist listen_addrs;
int ndirs;
const char * const **dirs;
enum normalizations normalize;
struct user_info {
const char *name; /* User name */
struct passwd *pw; /* Corresponding password entry */
} user;
};
extern struct daemon_options dopt;
#endif
tftp-hpa-7.2+20261013/tftpd/path.c 0000664 0000000 0000000 00000016046 15263245305 0016234 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin
*/
/*
* This breaks down a path name into its constituents, removing
* . and .. components.
*
* Returns NULL if the path is invalid (notably if it requires access
* above the topmost directory level.)
*
* To match historical behavior, the path must be absolute, starting
* with an explicit /.
*
* This returns a list of pointers into a string array, all allocated
* as a single heap allocation.
*/
#include "config.h"
#include "common/tftpsubs.h"
#include "path.h"
/*
* Validate a filename character. On Unix, disallow ASCII control
* characters (< 32, 127); on Windows, also disallow \ : and other
* characters disallowed in file names (use rewrite to translate \
* into / just as on Unix, if desired.)
*/
static bool is_valid_char(unsigned char c)
{
switch (c) {
#ifdef _WIN32
case '<':
case '>':
case ':':
case '"':
case '\\': /* Slashes only for pathname separators! */
case '|':
case '?':
case '*':
return false;
#endif
default:
return c >= ' ';
}
}
/*
* Return true if the given character is a pathname separator that
* should be collapsed when merging paths.
*/
static bool is_dir_separator(char c)
{
#ifdef _WIN32
return c == '/' || c == '\\';
#else
return c == '/';
#endif
}
/*
* Validate a filename (path component) for the platform, beyond what
* is_valid_char() does.
*/
#ifndef _WIN32
#define is_valid_filename(file) true
#else
/*
* This is Win32-specific code; assume _strnicmp() exists.
*
* Illegal on Windows: names ending in ' ', '.'
* One of 22 special names either standalone or followed by '.' + anything,
* case insensitive.
*/
static bool is_valid_filename(const char *file)
{
const char *p;
bool last_ok = false;
char c;
p = file;
do {
c = *p;
switch (c) {
case '.':
last_ok = false;
/* fall through */
case '\0':
switch (p-file) {
case 3:
if (!_strnicmp(file, "aux", 3) ||
!_strnicmp(file, "con", 3) ||
!_strnicmp(file, "nul", 3) ||
!_strnicmp(file, "prn", 3))
return false;
break;
case 4:
if ((unsigned char)(p[-1] - '1') < 9) {
if (!_strnicmp(file, "com", 3) ||
!_strnicmp(file, "lpt", 3))
return false;
}
break;
default:
break;
}
break;
case ' ':
last_ok = false;
break;
default:
last_ok = true;
break;
}
p++;
} while (c);
return last_ok;
}
#endif /* _WIN32 */
/*
* Canonicalize a path by removing components (. and ..) and validate illegal
* filenames (currently only on Windows) beyond what is_valid_char()
* can do.
*
* If successful, return the number of entries dropped (in which case *dpp
* will have been adjusted accordingly), or return -1 if the filename
* is invalid or would ascend past the root.
*/
static int adjust_tail(const char ***dpp, const char **top)
{
size_t drop = 0;
const char **dp = *dpp;
const char *last;
/* These are sanity checks which should never trigger, but... */
if (!dp || dp < top)
return -1;
else if (dp == top)
return 0;
/* Get the last path component */
last = dp[-1];
if (!is_valid_filename(last))
return -1;
if (last[0] == '.') {
if (!last[1]) {
/* . component */
drop = 1;
} else if (last[1] == '.' && !last[2]) {
/* .. component */
drop = 2;
}
if (dp < top+drop)
return -1;
*dpp -= drop;
return (int)drop;
} else {
return 0;
}
}
/*
* Parse, validate and canonicalize a path. If "strict" is set,
* reject paths that contain . or .. components as well as paths
* without a leading slash.
*/
const char **parse_path(const char *path, bool strict)
{
bool was_slash;
const char *p;
const char **dirs, **dp;
char *q;
size_t path_len;
size_t ndirs;
int dropped;
if (strict && *path != '/')
return NULL; /* Path not absolute */
/*
* Allocate space for the dirs list. The *maximum possible* number
* equals the number of spans of non-slash characters.
*/
was_slash = true; /* Implicit leading slash */
ndirs = 0;
for (p = path; *p; p++) {
if (!is_valid_char(*p))
return NULL; /* Invalid character in path */
if (*p == '/') {
was_slash = true;
} else if (was_slash) {
ndirs++;
was_slash = false;
}
}
path_len = p - path;
dirs = dp = xmalloc((ndirs+1) * sizeof *dirs + path_len + 1);
q = (char *)&dirs[ndirs+1];
memcpy(q, path, path_len + 1);
was_slash = true;
while (*q) {
if (*q == '/') {
*q = '\0';
if (!was_slash) {
dropped = adjust_tail(&dp, dirs);
if (dropped < 0 || (dropped && strict))
goto fail;
}
was_slash = true;
} else if (was_slash) {
*dp++ = q;
was_slash = false;
}
q++;
}
if (!was_slash) {
dropped = adjust_tail(&dp, dirs);
if (dropped < 0 || (dropped && strict))
goto fail;
}
*dp = NULL;
return dirs;
fail:
free(dirs);
return NULL;
}
/*
* Construct a canonical form path from a directory list, optionally
* prepended with a path prefix. Returns a newly allocated string.
*/
char *build_path(const char *prefix, const char * const *dirs)
{
size_t size = 1; /* Space for NUL terminator */
size_t prefix_len = 0;
const char * const *dp;
char *path, *q;
if (prefix) {
prefix_len = strlen(prefix);
while (prefix_len && is_dir_separator(prefix[prefix_len-1]))
prefix_len--;
}
size += prefix_len;
for (dp = dirs; *dp; dp++) {
size_t len = strlen(*dp);
size += len+1; /* / + string */
}
q = path = xmalloc(size);
if (prefix_len) {
q = mempcpy(q, prefix, prefix_len);
}
for (dp = dirs; *dp; dp++) {
*q++ = '/';
q = stpcpy(q, *dp);
}
/* If the dirs list is empty, stpcpy() won't have added a null byte */
*q = '\0';
return path;
}
/*
* Compare two path lists.
* Returns:
* 0 on an explicit mismatch
* 1 if the a is shorter but matches (is a prefix)
* 2 if the b is shorter but matches (is a prefix)
* 3 on an exact match
*/
unsigned int compare_paths(const char * const *a, const char * const *b)
{
while (1) {
if (!*a) {
return *b ? 1 : 3;
} else if (!*b) {
return 2;
} else if (strcmp(*a, *b)) {
return 0;
}
a++;
b++;
}
}
tftp-hpa-7.2+20261013/tftpd/path.h 0000664 0000000 0000000 00000000617 15263245305 0016236 0 ustar 00root root 0000000 0000000 /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright (c) 2026 Intel Corporation; Author: H. Peter Anvin */
#ifndef TFTPD_PATH_H
#define TFTPD_PATH_H 1
#include "config.h"
const char **parse_path(const char *path, bool strict);
char *build_path(const char *prefix, const char * const *dirs);
unsigned int compare_paths(const char * const *a, const char * const *b);
#endif /* TFTPD_PATH_H */
tftp-hpa-7.2+20261013/tftpd/recvfrom.c 0000664 0000000 0000000 00000023205 15263245305 0017116 0 ustar 00root root 0000000 0000000 /* ----------------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2001-2025 H. Peter Anvin - All Rights Reserved
*
* ----------------------------------------------------------------------- */
/*
* recvfrom.c
*
* Emulate recvfrom() using recvmsg(), but try to capture the local address
* since some TFTP clients consider it an error to get the reply from another
* IP address than the request was sent to.
*
*/
#include "config.h" /* Must be included first! */
#include "common/tftpsubs.h"
#include "recvfrom.h"
#ifdef HAVE_MACHINE_PARAM_H
#include /* Needed on some versions of FreeBSD */
#endif
#include "tftpd.h"
/*
* The following socket-configuration helpers do not depend on recvmsg()
* or msghdr::msg_control support, and are used by both the recvmsg()-based
* myrecvfrom() implementation below and its non-recvmsg() fallback, so
* they are compiled unconditionally.
*/
void set_socket_nonblock(int fd, bool flag)
{
int flags;
#if defined(HAVE_FCNTL) && (O_NONBLOCK != 0)
/* Posixly correct */
flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
goto err;
if (flag)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0)
goto err;
#else
flags = flag ? 1 : 0;
if (ioctl(fd, FIONBIO, &flags) < 0)
goto err;
#endif
return;
err:
tftpd_log(LOG_ERR, "Cannot set nonblock flag on socket: %s",
strerror(errno));
exit(EX_OSERR);
}
/* Disable pmtu discovery */
static void pmtu_discovery_off(int fd)
{
#if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
setsockint(fd, IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DONT);
#endif
}
/* Try to enable getting the receive address in recvmsg() */
static void enable_recvdstaddr(int fd)
{
#ifdef IP_RECVDSTADDR
setsockint(fd, IPPROTO_IP, IP_RECVDSTADDR, 1);
#endif
#ifdef IP_PKTINFO
setsockint(fd, IPPROTO_IP, IP_PKTINFO, 1);
#endif
#ifdef HAVE_IPV6
#ifdef IPV6_RECVPKTINFO
setsockint(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, 1);
#endif
#endif
}
/*
* Configure a socket for myrecvfrom(). It should also be suitable
* for select().
*
* The "peer" flag indicates that this a connected peer socket.
*/
void tftpd_config_socket(int fd, bool peer)
{
/* Set socket as nonblocking */
#ifdef __CYGWIN__
/* On Cygwin, a nonblocking socket returns immediately from select()! */
set_socket_nonblock(fd, false);
#else
set_socket_nonblock(fd, true);
#endif
/* Disable pmtu discovery (useless for TFTP and breaks things) */
pmtu_discovery_off(fd);
/* Get our own address in recvmsg()*/
if (!peer)
enable_recvdstaddr(fd);
}
#if defined(HAVE_RECVMSG) && defined(HAVE_STRUCT_MSGHDR_MSG_CONTROL)
#ifdef HAVE_SYS_UIO_H
# include
#endif
#ifdef IP_PKTINFO
# ifndef HAVE_STRUCT_IN_PKTINFO_IPI_ADDR
# ifdef __linux__
/* Assume this version of glibc simply lacks the definition */
struct in_pktinfo {
int ipi_ifindex;
struct in_addr ipi_spec_dst;
struct in_addr ipi_addr;
};
# else
# undef IP_PKTINFO /* No definition, no way to get it */
# endif
# endif
#endif
#ifndef CMSG_LEN
# define CMSG_LEN(size) (sizeof(struct cmsghdr) + (size))
#endif
#ifndef CMSG_SPACE
# define CMSG_SPACE(size) (sizeof(struct cmsghdr) + (size))
#endif
/*
* Check to see if this is a valid local address, meaning that we can
* legally bind to it.
*/
static bool address_is_local(const union sock_addr *addr)
{
union sock_addr sa1, sa2;
int sockfd = -1;
int e;
bool rv = false;
socklen_t addrlen;
memcpy(&sa1, addr, sizeof sa1);
/* Multicast or universal broadcast address? */
if (sa1.sa.sa_family == AF_INET) {
if (ntohl(sa1.si.sin_addr.s_addr) >= (224UL << 24))
return false;
sa1.si.sin_port = 0; /* Any port */
}
#ifdef HAVE_IPV6
else if (sa1.sa.sa_family == AF_INET6) {
if (IN6_IS_ADDR_MULTICAST(&sa1.s6.sin6_addr))
return false;
sa1.s6.sin6_port = 0; /* Any port */
}
#endif
else
return false;
sockfd = socket(sa1.sa.sa_family, SOCK_DGRAM, 0);
if (sockfd < 0)
goto err;
if (bind(sockfd, &sa1.sa, sizeof sa1))
goto err;
addrlen = sizeof sa2;
if (getsockname(sockfd, &sa2.sa, &addrlen))
goto err;
if (sa1.sa.sa_family != sa2.sa.sa_family)
goto err;
if (sa2.sa.sa_family == AF_INET)
rv = sa1.si.sin_addr.s_addr == sa2.si.sin_addr.s_addr;
#ifdef HAVE_IPV6
else if (sa2.sa.sa_family == AF_INET6)
rv = !!IN6_ARE_ADDR_EQUAL(&sa1.s6.sin6_addr, &sa2.s6.sin6_addr);
#endif
else
rv = false;
err:
e = errno;
if (sockfd >= 0)
close(sockfd);
errno = e;
return rv;
}
static void normalize_ip6_compat(union sock_addr *myaddr)
{
#ifdef HAVE_IPV6
static const uint8_t ip6_compat_prefix[12] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
struct sockaddr_in in;
if (myaddr->sa.sa_family == AF_INET6 &&
!memcmp(&myaddr->s6.sin6_addr, ip6_compat_prefix,
sizeof ip6_compat_prefix)) {
bzero(&in, sizeof in);
in.sin_family = AF_INET;
in.sin_port = myaddr->s6.sin6_port;
memcpy(&in.sin_addr, (const char *)&myaddr->s6.sin6_addr +
sizeof ip6_compat_prefix, sizeof in.sin_addr);
memcpy(&myaddr->si, &in, sizeof in);
}
#else
(void)myaddr;
#endif
}
#ifdef HAVE_RECVMSG
int
myrecvfrom(int s, void *buf, int len, unsigned int flags,
union sock_addr *from, union sock_addr *myaddr)
{
struct msghdr msg;
struct iovec iov;
int n;
struct cmsghdr *cmptr;
union {
struct cmsghdr cm;
#ifdef IP_PKTINFO
char control[CMSG_SPACE(sizeof(struct in_addr)) +
CMSG_SPACE(sizeof(struct in_pktinfo))];
#else
char control[CMSG_SPACE(sizeof(struct in_addr))];
#endif
#ifdef HAVE_IPV6
#ifdef HAVE_STRUCT_IN6_PKTINFO_IPI6_ADDR
char control6[CMSG_SPACE(sizeof(struct in6_addr)) +
CMSG_SPACE(sizeof(struct in6_pktinfo))];
#else
char control6[CMSG_SPACE(sizeof(struct in6_addr))];
#endif
#endif
} control_un;
#ifdef IP_PKTINFO
struct in_pktinfo pktinfo;
#endif
#ifdef HAVE_STRUCT_IN6_PKTINFO_IPI6_ADDR
struct in6_pktinfo pktinfo6;
#endif
#endif
bzero(&msg, sizeof msg); /* Clear possible system-dependent fields */
msg.msg_control = control_un.control;
msg.msg_controllen = sizeof(control_un);
msg.msg_flags = 0;
msg.msg_name = &from->sa;
msg.msg_namelen = sizeof(*from);
iov.iov_base = buf;
iov.iov_len = len;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
if ((n = recvmsg(s, &msg, flags)) < 0)
return n; /* Error */
if (myaddr) {
bzero(myaddr, sizeof(*myaddr));
myaddr->sa.sa_family = from->sa.sa_family;
if (msg.msg_controllen < sizeof(struct cmsghdr) ||
(msg.msg_flags & MSG_CTRUNC))
return n; /* No information available */
for (cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL;
cmptr = CMSG_NXTHDR(&msg, cmptr)) {
if (from->sa.sa_family == AF_INET) {
myaddr->sa.sa_family = AF_INET;
#ifdef IP_RECVDSTADDR
if (cmptr->cmsg_level == IPPROTO_IP &&
cmptr->cmsg_type == IP_RECVDSTADDR) {
memcpy(&myaddr->si.sin_addr, CMSG_DATA(cmptr),
sizeof(struct in_addr));
}
#endif
#ifdef IP_PKTINFO
if (cmptr->cmsg_level == IPPROTO_IP &&
cmptr->cmsg_type == IP_PKTINFO) {
memcpy(&pktinfo, CMSG_DATA(cmptr),
sizeof(struct in_pktinfo));
memcpy(&myaddr->si.sin_addr, &pktinfo.ipi_addr,
sizeof(struct in_addr));
}
#endif
}
#ifdef HAVE_IPV6
else if (from->sa.sa_family == AF_INET6) {
myaddr->sa.sa_family = AF_INET6;
#ifdef IP6_RECVDSTADDR
if (cmptr->cmsg_level == IPPROTO_IPV6 &&
cmptr->cmsg_type == IPV6_RECVDSTADDR)
memcpy(&myaddr->s6.sin6_addr, CMSG_DATA(cmptr),
sizeof(struct in6_addr));
#endif
#ifdef HAVE_STRUCT_IN6_PKTINFO_IPI6_ADDR
if (cmptr->cmsg_level == IPPROTO_IPV6 &&
(
#ifdef IPV6_RECVPKTINFO
cmptr->cmsg_type == IPV6_RECVPKTINFO ||
#endif
cmptr->cmsg_type == IPV6_PKTINFO)) {
memcpy(&pktinfo6, CMSG_DATA(cmptr),
sizeof(struct in6_pktinfo));
memcpy(&myaddr->s6.sin6_addr, &pktinfo6.ipi6_addr,
sizeof(struct in6_addr));
}
#endif
}
#endif
}
normalize_ip6_compat(myaddr);
/* If the address is not a valid local address,
* then bind to any address...
*/
if (!address_is_local(myaddr)) {
if (myaddr->sa.sa_family == AF_INET)
((struct sockaddr_in *)myaddr)->sin_addr.s_addr = INADDR_ANY;
#ifdef HAVE_IPV6
else if (myaddr->sa.sa_family == AF_INET6)
memset(&myaddr->s6.sin6_addr, 0, sizeof(struct in6_addr));
#endif
}
}
normalize_ip6_compat(from);
return n;
}
#else /* pointless... */
int
myrecvfrom(int s, void *buf, int len, unsigned int flags,
union sock_addr *from, union sock_addr *myaddr)
{
/* There is no way we can get the local address, fudge it */
socklen_t fromlen = sizeof(*from);
int n;
n = recvfrom(s, buf, len, flags, &from->sa, &fromlen);
bzero(myaddr, sizeof(*myaddr));
if (n >= 0) {
myaddr->sa.sa_family = from->sa.sa_family;
sa_set_port(myaddr, htons(TFTP_IP_PORT));
}
return n;
}
#endif
tftp-hpa-7.2+20261013/tftpd/recvfrom.h 0000664 0000000 0000000 00000001501 15263245305 0017116 0 ustar 00root root 0000000 0000000 /* ----------------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2001-2025 H. Peter Anvin - All Rights Reserved
*
* ----------------------------------------------------------------------- */
/*
* recvfrom.h
*
* Header for recvfrom substitute and socket configuration functions
*/
#include "config.h"
int
myrecvfrom(int s, void *buf, int len, unsigned int flags,
union sock_addr *from, union sock_addr *myaddr);
void tftpd_config_socket(int fd, bool peer);
void set_socket_nonblock(int fd, bool flag);
/* On Cygwin, a nonblocking socket can cause immediate return from select?! */
#ifdef __CYGWIN__
#define cygwin_set_socket_nonblock(fd,flag) set_socket_nonblock(fd,flag)
#else
#define cygwin_set_socket_nonblock(fd,flag) ((void)0)
#endif
tftp-hpa-7.2+20261013/tftpd/remap.c 0000664 0000000 0000000 00000054130 15263245305 0016400 0 ustar 00root root 0000000 0000000 /* ----------------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2001-2025 H. Peter Anvin - All Rights Reserved
*
* ----------------------------------------------------------------------- */
/*
* remap.c
*
* Perform regular-expression based filename remapping.
*/
#include "config.h" /* Must be included first! */
#include "tftpd.h"
#include "options.h"
#include "remap.h"
#ifdef WITH_REGEX
#include
#include
#define RULE_REWRITE 0x01 /* This is a rewrite rule */
#define RULE_GLOBAL 0x02 /* Global rule (repeat until no match) */
#define RULE_EXIT 0x04 /* Exit after matching this rule */
#define RULE_RESTART 0x08 /* Restart at the top after matching this rule */
#define RULE_ABORT 0x10 /* Terminate processing with an error */
#define RULE_INVERSE 0x20 /* Execute if regex *doesn't* match */
#define RULE_IPV4 0x40 /* IPv4 only */
#define RULE_IPV6 0x80 /* IPv6 only */
#define RULE_HASFILE 0x100 /* Valid if rule results in a valid filename */
#define RULE_RRQ 0x200 /* Get (read) only */
#define RULE_WRQ 0x400 /* Put (write) only */
#define RULE_SEDG 0x800 /* sed-style global */
#define RULE_JUMP 0x1000 /* Jump rule */
#define RULE_LABEL 0x2000 /* Label */
#define RULE_NOREGEX 0x4000 /* The rule has no regular expression */
#define RULE_HAS_REGEX(x) (!((x) & RULE_NOREGEX))
#if defined(HAVE_WCHAR_H) && defined(HAVE_WCTYPE_H) && \
defined(HAVE_MBRTOWC) && defined(HAVE_TOWLOWER)
# define WITH_MB 1
#else
# define WITH_MB 0
#endif
struct rule {
struct rule *next;
unsigned int line;
unsigned int rule_flags;
regex_t rx;
const char *pattern; /* Replacement pattern or label name */
};
#if WITH_MB
typedef wint_t xform_int;
#define xform_toupper towupper
#define xform_tolower towlower
#else
typedef int xform_int;
#define xform_toupper toupper
#define xform_tolower tolower
#endif
typedef xform_int (*xform_func)(xform_int xc);
struct xform_state {
xform_func xform;
char *out;
size_t len;
bool err;
#if WITH_MB
mbstate_t ps;
#endif
};
static xform_int xform_null(xform_int xc)
{
return xc;
}
static void xform_init(struct xform_state *xs, char *string)
{
memset(xs, 0, sizeof *xs);
xs->xform = xform_null;
xs->out = string;
}
#if WITH_MB
static const char *xform_out(struct xform_state *xs, const char *p, size_t len)
{
static char dummy_mb_buf[MB_LEN_MAX];
mbstate_t ips;
char *q = xs->out;
memset(&ips, 0, sizeof ips);
while (len && *p && *p != '\\') {
wchar_t wc;
ssize_t nb = mbrtowc(&wc, p, len, &ips);
if (nb > 0) {
len -= nb;
p += nb;
wc = xs->xform(wc);
nb = wcrtomb(q ? q : dummy_mb_buf, wc, &xs->ps);
if (nb > 0) {
xs->len += nb;
if (q)
q += nb;
}
} else {
/* Conversion error */
xs->err = true;
break;
}
}
if (q) {
*q = '\0';
xs->out = q;
}
return p;
}
#else
static const char *xform_out(struct xform_state *xs, const char *p, size_t len)
{
char *q = xs->out;
while (len && *p && *p != '\\') {
if (q)
q++ = xs->xform((unsigned char)*p);
xs->len++;
p++;
len--;
}
if (q) {
*q = '\0';
xs->out = q;
}
return p;
}
#endif
/*
* Do \-substitution. Call with string == NULL to get length only.
* "start" indicates an offset into the input buffer where the pattern
* match was started; *nextp points to the first character after the
* pattern expansion.
*
* If start is set to MATCHONLY == (size_t)-1 or the pmatch array indicates
* that no match was found, then the before and after match contents of
* the input string are discarded.
*/
#define MATCHONLY ((size_t)-1)
static size_t null_macrosub(char macro, const char **macrodata)
{
(void)macro;
(void)macrodata;
return (size_t)-1;
}
static size_t xsmemcpy(struct xform_state *xs, const char *from, size_t bytes)
{
if (xs->out) {
xs->out = mempcpy(xs->out, from, bytes);
*xs->out = '\0'; /* Enforce null termination */
}
xs->len += bytes;
return xs->len;
}
static size_t
do_genmatchstring(char *string, const char *pattern,
const char *ibuf, const regmatch_t *pmatch,
match_pattern_callback macrosub,
size_t start, size_t *nextp)
{
size_t endbytes;
struct xform_state xs;
const char *input;
const char *pattern_end = strchr(pattern, '\0');
if (!macrosub)
macrosub = null_macrosub;
xform_init(&xs, string);
if (start == MATCHONLY) {
input = ibuf;
endbytes = 0;
} else if (pmatch[0].rm_so == -1) {
return xsmemcpy(&xs, ibuf, strlen(ibuf)+1);
} else {
input = ibuf + start;
endbytes = strlen(input) - pmatch[0].rm_eo;
xsmemcpy(&xs, ibuf, start + pmatch[0].rm_so);
}
/* Transform matched section */
while (*pattern) {
if (*pattern == '\\') {
char macro = pattern[1];
pattern += 2;
switch (macro) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
const regmatch_t *pm = &pmatch[macro - '0'];
if (pm->rm_so != -1) {
xform_out(&xs, input + pm->rm_so,
pm->rm_eo - pm->rm_so);
}
break;
}
case 'L':
xs.xform = xform_tolower;
break;
case 'U':
xs.xform = xform_toupper;
break;
case 'E':
xs.xform = xform_null;
break;
case '\0':
pattern--;
/* fall through */
case '\\':
xs.len++;
if (xs.out)
*xs.out++ = '\\';
break;
default:
{
const char *macrodata;
size_t sublen = macrosub(macro, ¯odata);
if (sublen != (size_t)-1) {
xform_out(&xs, macrodata, sublen);
} else {
/* Ignore the backslash prefix */
pattern--;
}
break;
}
}
} else {
pattern = xform_out(&xs, pattern, pattern_end - pattern);
}
}
/* Pointer to post-substitution tail */
if (nextp)
*nextp = xs.len;
/* Copy section after match */
xsmemcpy(&xs, input + pmatch[0].rm_eo, endbytes);
return xs.err ? (size_t)-1 : xs.len;
}
/*
* Ditto, but allocate the string in a new buffer
*/
static size_t
genmatchstring(char **string, const char *pattern,
const char *ibuf, const regmatch_t *pmatch,
match_pattern_callback macrosub,
size_t start, size_t *nextp)
{
size_t len;
char *buf;
len = do_genmatchstring(NULL, pattern, ibuf, pmatch,
macrosub, start, NULL);
if (len == (size_t)-1) {
*string = NULL;
return len;
}
*string = buf = xmalloc(len + 1);
return do_genmatchstring(buf, pattern, ibuf, pmatch,
macrosub, start, nextp);
}
/*
* Extract a string terminated by non-escaped whitespace; ignoring
* leading whitespace. Consider an unescaped # to be a comment marker,
* functionally \n.
*/
static size_t readescstring(char *buf, char **str)
{
char *p = *str;
bool wasbs = false;
size_t len = 0;
while (*p && isspace(*p))
p++;
if (!*p) {
*buf = '\0';
*str = p;
return 0;
}
while (*p) {
if (!wasbs && (isspace(*p) || *p == '#')) {
*buf = '\0';
*str = p;
return len;
}
/* Important: two backslashes leave us in the !wasbs state! */
wasbs = !wasbs && (*p == '\\');
*buf++ = *p++;
len++;
}
*buf = '\0';
*str = p;
return len;
}
/*
* Parse a line into a set of instructions. Needs a work buffer
* no shorter than the length of the line including final \0.
*/
static int parseline(char *line, struct rule *r, unsigned int lineno,
char *buffer)
{
char *p;
int rv;
int rxflags = REG_EXTENDED;
struct badcombo {
unsigned int flags;
char name[4];
};
static const struct badcombo badcombos[] = {
{ RULE_REWRITE | RULE_INVERSE, "r~" },
{ RULE_REWRITE | RULE_ABORT, "ra" },
{ RULE_REWRITE | RULE_JUMP, "rj" },
{ RULE_ABORT | RULE_JUMP, "aj" },
{ RULE_ABORT | RULE_RESTART, "as" },
{ RULE_EXIT | RULE_JUMP, "ej" },
{ RULE_EXIT | RULE_ABORT, "ae" },
{ RULE_EXIT | RULE_RESTART, "es" },
{ RULE_EXIT | RULE_HASFILE, "eE" },
{ RULE_HASFILE | RULE_JUMP, "Ej" },
{ RULE_HASFILE | RULE_ABORT, "aE" },
{ RULE_HASFILE | RULE_RESTART, "Es" },
{ 0, "" }
};
const struct badcombo *bc;
memset(r, 0, sizeof *r);
r->line = lineno;
if (!readescstring(buffer, &line))
return 0; /* No rule found */
p = buffer;
if (*buffer == ':') {
/* It is a label */
r->rule_flags = RULE_LABEL | RULE_NOREGEX;
p++;
if (*p) {
r->pattern = xstrdup(p);
return 1;
}
}
for (; *p; p++) {
switch (*p) {
case 'r':
r->rule_flags |= RULE_REWRITE;
break;
case 'g':
if (r->rule_flags & RULE_GLOBAL)
r->rule_flags |= RULE_SEDG;
else
r->rule_flags |= RULE_GLOBAL;
break;
case 'e':
r->rule_flags |= RULE_EXIT;
break;
case 'E':
r->rule_flags |= RULE_HASFILE;
break;
case 's':
r->rule_flags |= RULE_RESTART;
break;
case 'a':
r->rule_flags |= RULE_ABORT;
break;
case 'j':
r->rule_flags |= RULE_JUMP;
break;
case 'i':
rxflags |= REG_ICASE;
break;
case '~':
r->rule_flags |= RULE_INVERSE;
rxflags |= REG_NOSUB;
break;
case '4':
r->rule_flags |= RULE_IPV4;
break;
case '6':
r->rule_flags |= RULE_IPV6;
break;
case 'G':
r->rule_flags |= RULE_RRQ;
break;
case 'P':
r->rule_flags |= RULE_WRQ;
break;
default:
tftpd_log(LOG_ERR,
"remap: line %u: invalid operation flag \"%c\"",
*p, lineno);
return -1; /* Error */
break;
}
}
for (bc = badcombos; bc->flags; bc++) {
if ((r->rule_flags & bc->flags) == bc->flags) {
tftpd_log(LOG_ERR, "remap: line %u: rule flags %c and %c cannot be combined",
lineno, bc->name[0], bc->name[1]);
return -1;
}
}
if (!(r->rule_flags & RULE_REWRITE)) {
/* RULE_GLOBAL and RULE_SEDG are meaningless without RULE_REWRITE */
r->rule_flags &= ~(RULE_GLOBAL|RULE_SEDG);
}
if (RULE_HAS_REGEX(r->rule_flags)) {
/* Read and compile the regex */
if (!readescstring(buffer, &line)) {
tftpd_log(LOG_ERR, "remap: line %u: regex missing", lineno);
return -1; /* Error */
}
if ((rv = regcomp(&r->rx, buffer, rxflags)) != 0) {
char *errbuf = xmalloc(BUFSIZ);
regerror(rv, &r->rx, errbuf, BUFSIZ);
tftpd_log(LOG_ERR, "regex: line %u: bad regex: %s",
lineno, errbuf);
return -1; /* Error */
}
}
/* Read the rewrite pattern, if any */
if (readescstring(buffer, &line))
r->pattern = xstrdup(buffer);
else
r->pattern = xstrdup("");
return 1; /* Valid rule found */
}
#define MIN_LINE 64 /* Minimum size of allocated buffer */
/* Read a line into an allocated buffer; drops \n \r \0 */
static size_t read_line(FILE *f, char **bufp, size_t *bufsizep)
{
char *buf = *bufp;
size_t bufsize = *bufsizep;
size_t len = 0;
while (1) {
int c = 0;
while (len+1 < bufsize) {
c = getc(f);
if (c == EOF) {
buf[len] = '\0';
return len ? len : (size_t)-1;
} else if (c == '\n') {
buf[len] = '\0';
return len;
} else if (c != '\0' && c != '\r') {
buf[len++] = c;
}
}
if (bufsize < MIN_LINE)
bufsize = MIN_LINE;
else
bufsize <<= 1;
*bufsizep = bufsize;
*bufp = buf = xrealloc(buf, bufsize);
}
}
/* Read a rule file */
struct rule *parserulefile(FILE * f)
{
char *line = NULL;
char *parsebuf = NULL;
size_t linesize = 0;
size_t parsebufsize = 0;
struct rule *first_rule = NULL;
struct rule **last_rule = &first_rule;
struct rule *this_rule = xmalloc(sizeof(struct rule));
int rv;
unsigned int lineno = 0;
size_t len;
bool err = false;
while ((len = read_line(f, &line, &linesize)) != (size_t)-1) {
lineno++;
if (parsebufsize < linesize)
parsebuf = xrealloc(parsebuf, parsebufsize = linesize);
rv = parseline(line, this_rule, lineno, parsebuf);
if (rv < 0)
err = true;
if (rv > 0) {
*last_rule = this_rule;
last_rule = &this_rule->next;
this_rule = xmalloc(sizeof(struct rule));
}
}
xfree(this_rule); /* Last one is always unused */
xfree(parsebuf);
xfree(line); /* Free buffer */
if (err) {
/* Bail on error, we have already logged an error message */
exit(EX_CONFIG);
}
return first_rule;
}
/* Destroy a rule file data structure */
void freerules(struct rule *r)
{
struct rule *next;
while (r) {
next = r->next;
if (RULE_HAS_REGEX(r->rule_flags))
regfree(&r->rx);
xfree((void *)r->pattern);
xfree(r);
r = next;
}
}
static void clear_pmatch(int pmatches, regmatch_t *pmatch)
{
int i;
for (i = 0; i < pmatches; i++)
pmatch[i].rm_so = pmatch[i].rm_eo = -1;
}
/* Execute a rule set on a string; returns a malloc'd new string. */
char *rewrite_string(const struct formats *pf,
const char *input, const struct rule *rules,
int mode, int af, match_pattern_callback macrosub,
const char **errmsg)
{
char *current = xstrdup(input);
char *newstr = current;
const char *accerr;
const struct rule *ruleptr = rules;
regmatch_t pmatch[10];
int deadman = dopt.map_steps;
unsigned int bad_flags;
if (!rules)
return current;
/* Default error */
*errmsg = "Remap table failure";
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: input: %s", current);
}
bad_flags = RULE_LABEL | RULE_NOREGEX;
if (mode != RRQ) bad_flags |= RULE_RRQ;
if (mode != WRQ) bad_flags |= RULE_WRQ;
if (af != AF_INET) bad_flags |= RULE_IPV4;
if (af != AF_INET6) bad_flags |= RULE_IPV6;
ruleptr = rules;
while (ruleptr) {
const bool inverse = !!(ruleptr->rule_flags & RULE_INVERSE);
const int pmatches = inverse ? 0 : 10;
const int matchsense = inverse ? REG_NOMATCH : 0;
bool was_match;
const char *whatami;
const struct rule *next = ruleptr->next;
if (ruleptr->rule_flags & bad_flags)
goto nextrule;
if (!deadman--)
goto dead;
newstr = current;
/* Clear the pmatch[] array for good measure */
clear_pmatch(10, pmatch);
was_match = regexec(&ruleptr->rx, newstr, pmatches, pmatch, 0)
== matchsense;
if (!was_match)
goto nextrule; /* Rule did not match */
if (dopt.verbosity >= 5) {
tftpd_log(LOG_INFO, "remap: line %u: hit on %s%.*s%s, replacement: \"%s\"",
ruleptr->line,
inverse ? "~" : "\"",
pmatch[0].rm_eo - pmatch[0].rm_so,
inverse ? "" : newstr + pmatch[0].rm_so,
inverse ? "" : "\"",
ruleptr->pattern);
}
whatami = "match";
if (ruleptr->rule_flags & RULE_REWRITE) {
size_t ggoffset = 0;
whatami = "rewrite";
while (1) {
char *newerstr;
size_t len;
size_t gg0 = ggoffset + pmatch[0].rm_so;
len = genmatchstring(&newerstr, ruleptr->pattern, newstr,
pmatch, macrosub, ggoffset, &ggoffset);
if (len == (size_t)-1) {
xfree(newstr);
return NULL;
}
if (dopt.verbosity >= 4) {
tftpd_log(LOG_INFO, "remap: line %u: rewrite step: \"%.*s\" -> \"%.*s\" [%d]",
ruleptr->line,
pmatch[0].rm_eo - pmatch[0].rm_so, newstr + gg0,
(int)(ggoffset - gg0), newerstr + gg0,
(int)(ggoffset - gg0));
}
if (newstr != current)
xfree(newstr);
newstr = newerstr;
if (!(ruleptr->rule_flags & RULE_GLOBAL))
break;
if (!(ruleptr->rule_flags & RULE_SEDG))
ggoffset = 0;
else if (ggoffset >= len)
break;
clear_pmatch(pmatches, pmatch);
if (regexec(&ruleptr->rx, newstr + ggoffset, pmatches,
pmatch, ggoffset ? REG_NOTBOL : 0) != matchsense)
break;
if (!deadman--)
goto dead;
}
}
if ((ruleptr->rule_flags & RULE_HASFILE) &&
pf->f_validate(newstr, mode, pf, &accerr)) {
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: line %u: ignoring %s (%s)",
ruleptr->line, whatami, accerr);
}
was_match = false;
if (newstr != current) {
xfree(newstr);
newstr = current;
}
} else if (newstr != current) {
xfree(current);
current = newstr;
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: line %u: rewrite result: %s",
ruleptr->line, current);
}
}
if (!was_match)
goto nextrule;
newstr = NULL;
if (ruleptr->rule_flags & (RULE_ABORT|RULE_JUMP)) {
if ((ssize_t)genmatchstring(&newstr, ruleptr->pattern, current,
pmatch, macrosub, MATCHONLY, NULL)
<= 0) {
xfree(newstr);
newstr = NULL;
}
}
if (ruleptr->rule_flags & RULE_ABORT) {
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: line %u: abort: %s",
ruleptr->line, current);
}
*errmsg = newstr;
newstr = NULL;
goto quit;
}
if (ruleptr->rule_flags & (RULE_EXIT|RULE_HASFILE)) {
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: line %u: exit",
ruleptr->line);
}
return current; /* Exit here, we're done */
}
if (ruleptr->rule_flags & RULE_RESTART) {
next = rules;
} else if (ruleptr->rule_flags & RULE_JUMP) {
if (!newstr) {
tftpd_log(LOG_ERR, "remap: line %u: no label in j rule",
ruleptr->line);
goto quit;
}
for (next = rules; next; next = next->next) {
if ((next->rule_flags & RULE_LABEL) &&
!strcmp(newstr, next->pattern))
break;
}
if (!next) {
tftpd_log(LOG_ERR, "remap: line %u: label not found: %s",
ruleptr->line, newstr);
goto quit;
}
}
if (dopt.verbosity >= 3) {
if (next != ruleptr->next) {
if ((next->rule_flags & RULE_LABEL) && next->pattern[0]) {
tftpd_log(LOG_INFO, "remap: line %u: jump to %s",
ruleptr->line, next->pattern);
} else {
tftpd_log(LOG_INFO, "remap: line %u: jump to line %u",
ruleptr->line, next->line);
}
}
}
nextrule:
ruleptr = next;
}
if (dopt.verbosity >= 3) {
tftpd_log(LOG_INFO, "remap: done: %s", current);
}
return current;
dead: /* Deadman expired */
tftpd_log(LOG_ERR,
"remap: Breaking loop after %d steps, input = %s, last = %s",
dopt.map_steps, input, newstr);
quit:
if (newstr != current)
xfree(newstr);
xfree(current);
return NULL; /* Did not terminate! */
}
#else /* WITH_REGEX */
struct rule *parserulefile(FILE *f)
{
return NULL;
}
void freerules(struct rule *r)
{
(void)r;
}
char *rewrite_string(const struct formats *pf,
const char *input, const struct rule *rules,
int mode, int af, match_pattern_callback macrosub,
const char **errmsg)
{
(void)pf;
(void)rules;
(void)mode;
(void)af;
(void)macrosub;
(void)errmsg;
return xstrdup(input);
}
#endif
tftp-hpa-7.2+20261013/tftpd/remap.h 0000664 0000000 0000000 00000002312 15263245305 0016400 0 ustar 00root root 0000000 0000000 /* ----------------------------------------------------------------------- *
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2001-2025 H. Peter Anvin - All Rights Reserved
*
* ----------------------------------------------------------------------- */
/*
* remap.h
*
* Prototypes for regular-expression based filename remapping.
*/
#ifndef TFTPD_REMAP_H
#define TFTPD_REMAP_H
/* Opaque type */
struct rule;
struct formats;
/*
* This is called by the remap engine when it encounters macros such
* as \i. It should put the output in a static buffer and put the
* buffer address in *output, then return the length of the output
* not including the terminal null.
*
* Return (size_t)-1 for an invalid macro, which then will be handled
* by the substitution code.
*/
typedef size_t (*match_pattern_callback) (char, const char **);
/* Execute a rule set on a string; returns a malloc'd new string. */
char *rewrite_string(const struct formats *, const char *,
const struct rule *, int, int,
match_pattern_callback, const char **);
/* Read a rule file */
struct rule *parserulefile(FILE *);
/* Destroy a rule file data structure */
void freerules(struct rule *);
#endif
tftp-hpa-7.2+20261013/tftpd/sample.rules 0000664 0000000 0000000 00000002311 15263245305 0017457 0 ustar 00root root 0000000 0000000 #
# Sample rule file for the -m (remapping option)
#
# This file has three fields: operation, regex, remapping
#
# The operation is a combination of the following letters:
#
# r - rewrite the matched string with the remapping pattern
# i - case-insensitive matching
# g - repeat until no match (used with "r")
# e - exit (with success) if we match this pattern, do not process
# subsequent rules
# s - start over from the first rule if we match this pattern
# a - abort (refuse the request) if we match this rule
# G - this rule applies to TFTP GET requests only
# P - this rule applies to TFTP PUT requests only
#
# The regex is a regular expression in the style of egrep(1).
#
# The remapping is a pattern, all characters are verbatim except \
# \0 copies the full string that matched the regex
# \1..\9 copies the 9 first (..) expressions in the regex
# \\ is an escaped \
#
# "#" begins a comment, unless \-escaped
#
ri ^[a-z]: # Remove "drive letters"
rg \\ / # Convert backslashes to slashes
rg \# @ # Convert hash marks to @ signs
rg /../ /..no../ # Convert /../ to /..no../
e ^ok/ # These are always ok
r ^[^/] /tftpboot/\0 # Convert non-absolute files
a \.pvt$ # Reject requests for private files
tftp-hpa-7.2+20261013/tftpd/strlist.c 0000664 0000000 0000000 00000001425 15263245305 0016777 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
#include "config.h"
#include "common/tftpsubs.h" /* xmalloc()/xfree() */
#include "strlist.h"
struct liststr *strlist_add(struct strlist *list, const char *str)
{
size_t len = strlen(str);
struct liststr *ls;
/* sizeof(*ls) includes space for the final NUL */
ls = xmalloc(sizeof(*ls) + len);
ls->next = NULL;
ls->len = len;
memcpy(ls->str, str, len+1);
*list->endp = ls;
list->endp = &ls->next;
return ls;
}
struct strlist *strlist_free(struct strlist *list)
{
struct liststr *ls, *next;
for (ls = list->list; ls; ls = next) {
next = ls->next;
xfree(ls);
}
return strlist_init(list);
}
tftp-hpa-7.2+20261013/tftpd/strlist.h 0000664 0000000 0000000 00000001264 15263245305 0017005 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
* All rights reserved.
*/
#ifndef TFTP_STRLIST_H
#define TFTP_STRLIST_H 1
#include "config.h"
struct liststr {
struct liststr *next;
size_t len;
char str[1];
};
struct strlist {
struct liststr *list;
struct liststr **endp;
};
static inline struct strlist *strlist_init(struct strlist *list)
{
list->list = NULL;
list->endp = &list->list;
return list;
}
static inline bool strlist_isempty(const struct strlist *list)
{
return !list->list;
}
struct liststr *strlist_add(struct strlist *list, const char *str);
struct strlist *strlist_free(struct strlist *);
#endif
tftp-hpa-7.2+20261013/tftpd/tftpd.8.in 0000664 0000000 0000000 00000064053 15263245305 0016754 0 ustar 00root root 0000000 0000000 .\" -*- nroff -*- --------------------------------------------------------- *
.\"
.\" SPDX-License-Identifier: BSD-4-Clause-UC
.\"
.\" Copyright (c) 1990, 1993, 1994
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Copyright 2001-2009, 2026 H. Peter Anvin - All Rights Reserved
.\"
.\"----------------------------------------------------------------------- */
.TH TFTPD 8 "20 September 2026" "tftp-hpa @@VERSION@@" "System Manager's Manual"
.SH NAME
.B tftpd
\- Trivial File Transfer Protocol server
.SH SYNOPSIS
.B in.tftpd
.RI [ options... ]
.I directory...
.SH DESCRIPTION
.B tftpd
is a server for the Trivial File Transfer Protocol. The TFTP protocol
is extensively used to support remote booting of diskless devices.
The server can be run as a standalone daemon or it can be started by
.MR inetd 8 ,
.MR xinetd 8 ,
or
.MR systemd 1 .
.PP
.I directory...
should specify one or more directories to which
.B tftpd
may have access. Note that if the
.B \-\-path-prefix
option (see below) has been specified, the directory names listed
should not include the
.I prefix
itself.
.PP
The directory names must follow the rules described under
\fBPATH VALIDATION\fP, or they will be rejected; notably they must
begin with
.RB \\[lq] / \\[rq]
and may not contain
.RB \\[lq] . \\[rq]
or
.RB \\[lq] .. \\[rq]
components.
.PP
.RB \\[lq] / \\[rq]
is only allowed as a
.I directory
in conjunction with the
.B \-\-path-prefix
option.
.SH OPTIONS
.PP
Some options are configurable at compile time and may not be available
on any one specific system. Run
.B tftpd
with the
.B \-V
option to see which specific options are available on your system.
.TP
\fB\-4\fP, \fB\-\-ipv4\fP
Connect with IPv4 only, even if IPv6 support was compiled in.
.TP
\fB\-6\fP, \fB\-\-ipv6\fP
Connect with IPv6 only, if compiled in.
.TP
\fB\-l\fP, \fB\-\-listen\fP
Run the server in standalone (listen) mode, rather than run from
a service daemon. In standalone mode, the
.B \-\-address
option can be used to specify a specific local address or port to
listen to and the
.B \-\-port
can be used to specify a default listen port.
.TP
\fB\-L\fP, \fB\-\-foreground\fP
Similar to
.B \-\-listen
but do not detach from the foreground process. Implies
.BR \-\-listen .
.TP
\fB\-a\fP, \fB\-\-address\fP \fI[address][:port]\fP
Specify a specific
.I address
and
.I port
to listen to when running in standalone mode (with the
.B \-\-listen
or
.B \-\-foreground
options.) Numeric IPv6 adresses must be enclosed in square brackets
to avoid ambiguity with the optional
.I port
information.
.IP
If no
.I address
is specified, the default is to listen to all local addresses.
.IP
.I port
can be either a decimal number between 1 and 65535, or a service name
specified in the
.MR services 5
database. If no
.I port
is specified, the default is used; see the
.B \-\-service
option.
.IP
The
.B \-\-address
option may be specified multiple times, and if the
.I address
is a host name that resolves to multiple addresses,
.B tftpd
will bind to all of them.
.TP
\fB\-S\fP, \fB\-\-service\fP, \fB\-\-port\fP \fIport\fP
Specify the port/service name to use in standalone mode unless a
.I port
is explicitly specified in the
.B \-\-address option. Regardless of which name is used for the option, the
.I port
can be either a decimal number or a service name specified in the
.MR services 5
database. The default is "tftp".
.TP
\fB\-c\fP, \fB\-\-create\fP
Allow new files to be created. By default,
.B tftpd
will only allow upload of files that already exist. Files are created
with default permissions allowing anyone to read or write them, unless
the
.B \-\-permissive
or
.B \-\-umask
options are specified.
.TP
\fB\-\-ro\fP, \fB\-\-read-only\fP
Disable all upload functionality, no matter what the filesystem
permissions are set to. All write requests will be denied immediately.
.TP
\fB\-\-max-upload\fP, \fB\-\-max-size\fP \fIsize\fP
Limit uploads to at most \fIsize\fP bytes. A write request that includes
an RFC 2349 \fBtsize\fP value greater than \fIsize\fP is denied immediately.
Uploads without \fBtsize\fP, or whose data exceeds their specified
\fBtsize\fP, are terminated with an error. A \fIsize\fP of zero is
equivalent to \fB\-\-read-only\fP.
.TP
\fB\-s\fP, \fB\-\-secure\fP, \fB\-\-chroot\fP
Change root directory on startup using
.MR chroot 2 .
This means the remote host does not
need to pass along the directory as part of the transfer, and may add
security. When
.B \-\-secure
is specified, exactly one
.I directory
should be specified on the command line.
.IP
Note that when
.B \-\-secure
is used, none of the path name checks
described under
.I "PATH VALIDATION"
below are performed unless
.B \-\-validate
is also specified; any desired checks will have to be implemented
using explicit remap rules.
.IP
Using
.B \-\-secure
requires
.B tftpd
to be started out as root, and run as root for a considerable amount
of time. Consider very carefully if this is genuinely desirable as
oppposed to running the daemon as an unprivileged user and using the
.BR \-\-map-file ,
.BR \-\-normalize ,
and/or
.B \-\-path-prefix
options instead, or if supported on your system, the
.B \-\-jail
option.
.TP
\fB\-j\fP, \fB\-\-jail\fP
Resolve file names under a virtual root directory. This is an
alternative to
.B \-\-secure
which may allow the daemon to not be started as root, but requires
that the
.MR openat2 2
system call to be supported on the running system; as of September
2026 this is only supported on newer Linux systems. If your system
does not support
.B \-\-jail
it exits with an error message. When
.B \-\-jail
is specified, exactly one
.I directory
should be specified on the command line.
.IP
Note that when
.B \-\-jail
is used, none of the path name checks
described under
.I "PATH VALIDATION"
below are performed unless
.B \-\-validate
is also specified; any desired checks will have to be implemented
using explicit remap rules.
.TP
\fB\-\-validate\fP
Perform path validation even if
.B \-\-secure
or
.B \-\-jail
are used. Normally path validation is only performed when neither of
those options are specified. See
.I "PATH VALIDATION" below.
.TP
\fB\-\-path-prefix\fP \fIprefix\fP
Prepends \fIprefix\fP to the local filesystem path
.I after
filename remapping and path validation (see below) have taken
place.
.B tftpd
verifies that
\fIprefix\fP
refers to an existing directory, but performs no other validity or
permissions checks.
.IP
If the
.B \-\-secure
or
.B \-\-jail
option is used,
.I prefix
is instead prepended to the root path; in other words:
.IP
.B \-\-path-prefix
/var/lib
.B \-\-secure
/tftpboot
.IP
is exactly equivalent to:
.IP
.B \-\-secure
/var/lib/tftpboot
.TP
\fB\-u\fP, \fB\-\-user\fP \fIusername\fP
Specify the username which
.B tftpd
will run as; the default is "nobody". The user ID, group ID, and (if
possible on the platform) the supplementary group IDs will be set to
the ones specified in the system permission database for this
username.
.TP
\fB\-U\fP, \fB\-\-umask\fP \fIumask\fP
Sets the \fIumask\fP for newly created files to the specified value.
The default is zero (anyone can read or write) if the
.B \-\-permissive
option is not specified, or inherited from the invoking process if
.B \-\-permissive
is specified.
.IP
See
.MR umask 2 .
.TP
\fB\-p\fP, \fB\-\-permissive\fP
Perform no additional permissions checks above the normal
system-provided access controls for the user specified via the
.B \-\-user
option.
.TP
\fB\-P\fP, \fB\-\-pidfile\fP \fIpidfile\fP
When run in standalone mode, write the process ID of the listening
server into \fIpidfile\fP. On normal termination (SIGTERM, SIGINT, or
inactivity timeout) the pid file is automatically removed.
.TP
\fB\-t\fP, \fB\-\-timeout\fP \fItimeout\fP
How long, in seconds, to wait for a connection before terminating the
server. Typically when run from a service daemon, the service daemon
will then respawn the server if a new connection arrives.
.IP
The default is 0 (unlimited) if run standalone, otherwise 900 (15 minutes.)
.TP
\fP\fB\-T\fP, \fB\-\-retransmit\fP \fItimeout\fP
Determine the default packet timeout, in microseconds, before a packet
is retransmitted. This can be modified by the client if the
.B timeout
or
.B utimeout
option is negotiated. The default is 1000000 (1 second.)
.IP
For subsequent retransmissions of the same packet,
.B tftpd
applies exponential backoff as required by
RFC 1123.
.TP
\fB\-m\fP, \fB\-\-map-file\fP \fIremap-file\fP
Specify the use of filename remapping. The
.I remap-file
is a file containing the remapping rules, if compiled in.
See the section on filename remapping below.
.TP
\fB\-\-map-steps\fP \fIsteps\fP
Specify the number of remapping rules that may be executed before the
filename mapping fails. The default is 4096.
.TP
\fB\-\-map-test\fP \fIinputfile\fP
Read the lines in the file \fIinputfile\fP and process each of them as
if they were a file name received from a client. Each valid
rewritten filename is then written to standard output, and
.B tftpd terminates.
.IP
Implies
.BR "\-\-stderr \-\-foreground" .
.IP
Use the
.B \-\-ipv4
and
.B \-\-ipv6
options to simulate an IPv4 or IPv6 client. If
.B \-\-create
is included on the command line, simulate a PUT (WRQ) request,
otherwise simulate a GET (RRQ) request.
.IP
If the
.B \-\-normalize
option is used, the output will also be normalized.
.TP
\fB\-\-normalize\fP[=\fImode\fP]
Normalize the path name. If remapping is used, normalization is
applied after remapping.
.I mode
can be
.BR none ,
.BR root ,
or
.BR path .
.IP
If
.I mode
is
.BR none ,
no normalization is done. This is the default.
.IP
If
.I mode
is
.BR root ,
then a leading slash is prepended if there is none.
.IP
If
.I mode
is
.BR path ,
then a leading slash is prepended if there is none, duplicate slashes
and
.RB \\[lq] . \\[rq]
pathname components are removed, and
.RB \\[lq] .. \\[rq]
pathname components are removed together with the previous pathname
component, if one exists. This is the default if
.I mode
is not specified. Note that the actual file system contents are not
examined; thus, symbolic links or missing directories are not taken
into account.
.IP
This option can be used with
.B \-\-path-prefix
to obtain an effect similar to
.B \-\-secure
or
.B \-\-jail
without needing a full remap file. See "FILENAME PROCESSING" below.
.TP
\fB\-v\fP, \fB\-\-verbose\fP
Increase the logging verbosity of
.BR tftpd .
This flag can be specified multiple times for even higher verbosity.
.TP
\fB\-\-verbosity\fP \fIvalue\fP
Set the verbosity value to \fIvalue\fP. This is equivalent to
specifying the
.B \-v
option
.I value
times.
.TP
\fB\-r\fP, \fB\-\-refuse\fP, \fB\-\-reject\fP \fItftp-option\fP
Indicate that a specific RFC 2347 TFTP option should never be
accepted, even if requested by the client. This can be used to work
around broken clients.
.TP
\fB\-\-refuse\-all\fP, \fB\-\-reject-all\fP
Disable all RFC 2347 options. Requests containing options proceed
directly to the normal TFTP data stage without an option acknowledgment.
.TP
\fB\-B\fP, \fB\-\-blocksize\fP \fImax-block-size\fP
Specifies the maximum permitted block size. The permitted range for
this parameter is from 512 to 65464, or it can be specified as
.RB \\[lq] mtu \\[rq],
or \[lq]\fBmtu-\fP\fIslack\fP\[rq].
When
.B mtu
is specified,
.B tftpd
will try to query the maximum transmission unit (MTU) from the kernel
and size the maximum block size accordingly. If
.I slack
is specified, the MTU value will be adjusted downward by
.I slack
bytes.
.IP
Some embedded clients request large block sizes and yet do not handle
fragmented packets correctly; for that reason
\fB\-\-blocksize mtu\fP
is recommended if you might have these kinds of clients on your network.
.TP
\fB\-W\fP, \fB\-\-windowsize\fP \fImax-window-size\fP
Specifies the maximum accepted RFC 7440 \fBwindowsize\fP option value.
The permitted range is from 1 to 32768. A client request exceeding
this limit is reduced to this value. If the resulting window is one
block, the \fBwindowsize\fP option is not returned and the transfer
uses normal lockstep operation.
.IP
The compile-time default is set by the \fBTFTPD_MAX_WINDOWSIZE\fP
configure variable and defaults to 256.
.TP
\fB\-\-window-bytes\fP \fImax-window-bytes\fP
Limits the negotiated window such that the negotiated block size
multiplied by the window size does not exceed \fImax-window-bytes\fP.
A value of zero, the default, disables this limit. A limit that permits
fewer than two blocks causes the server to use normal lockstep operation
instead of returning a \fBwindowsize\fP option.
.IP
The compile-time default is set by the \fBTFTPD_MAX_WINDOWBYTES\fP
configure variable) and defaults to 4194304 (4 MiB).
.TP
\fB\-R\fP, \fB\-\-port-range\fP, \fB\-\-ports\fP \fImin-port:max-port\fP
Force the server port number (the Transaction ID) to be in the
specified range of port numbers. This can be used to make filewall
rules or packet tracing easier.
.IP
The
.I min-port
and
.I max-port
values must be decimal numbers between 1 and 65535.
.TP
\fB\-\-syslog\fP
Send log messages to syslog. This is the default.
.TP
\fB\-\-stderr\fP[=\fIformat\fP]
Send log messages to standard error instead of syslog. The optional
.RI = format
is shorthand for
\[lq]\fB\-\-stderr\fP \fB\-\-logformat\fP \fIformat\fP\[rq].
.TP
\fB\-\-stdout\fP[=\fIformat\fP]
Send log messages to standard output instead of syslog. The optional
.RI = format
is shorthand for
\[lq]\fB\-\-stdout\fP \fB\-\-logformat\fP \fIformat\fP\[rq].
.TP
\fB\-\-logfile\fP \fIfile\fP
Send log messages to \fIfile\fP instead of syslog. The file is opened
for appending, and created with mode 0644 if it does not exist. If
.B tftpd
is running in standalone (listening) mode, the file will be closed and
reopened if SIGHUP is received, to allow log file rotation.
.TP
\fB\-\-logformat\fP \fIformat\fP
Set the log output format. The currently defined log formats are:
.RS
.TP
\fBhuman\fP
Use human-readable priority tags. This is the default.
.TP
\fBtag\fP
Use machine-readable priority tags.
.RE
.IP
Since syslog generates its own tags,
.B \-\-logformat
does not apply to syslog output.
.TP
\fB\-\-systemd\fP
Use
.B systemd
socket activation. This option is only used in a
.B systemd
unit file. See
.MR systemd.socket 5 .
.IP
This also makes the
.B tftpd
process run in the foreground, as if the
.B \-\-foreground
option had been specified, but unlike the
.B \-\-foreground
option it does not change the default for the
.B \-\-timeout
option.
.TP
\fB\-V\fP, \fB\-\-version\fP
Print the version number and configuration to standard output, then
exit gracefully. No daemon process is started and no listening sockets
are set up.
.SH "RFC 2347 OPTION NEGOTIATION"
This version of
.B tftpd
supports RFC 2347 option negotation. Currently implemented options
are:
.TP
\fBblksize\fP (RFC 2348)
Set the transfer block size to anything less than or equal to the
specified option. This version of
.B tftpd
can support any block size up to the theoretical maximum of 65464
bytes.
.TP
\fBblksize2\fP (nonstandard)
Set the transfer block size to anything less than or equal to the
specified option, but restrict the possible responses to powers of 2.
The maximum is 32768 bytes (the largest power of 2 less than or equal
to 65464.)
.TP
\fBtsize\fP (RFC 2349)
Report the size of the file that is about to be transferred. This
version of
.B tftpd
only supports the
.B tsize
option for binary (octet) mode transfers. For upload (write)
transactions, it is acknowledged unchanged and, if
.B \-\-max-upload
is specified, used to enforce the upload limit.
.TP
\fBtimeout\fP (RFC 2349)
Set the time before the server retransmits a packet, in seconds.
.TP
\fButimeout\fP (nonstandard)
Set the time before the server retransmits a packet, in microseconds.
.TP
\fBwindowsize\fP (RFC 7440)
Set the number of data blocks sent before an acknowledgment is required.
The maximum value is set by the
.B \-\-windowsize
and
.B \-\-window-bytes
options. A window can be retransmitted in whole or in part depending
on the specific acknowledgement packets received from the client.
.TP
\fBrollover\fP (nonstandard)
Set the block number to resume at after a block number rollover. The
default and recommended value is 0, but some clients expect 1 instead.
.PP
This version of
.B tftpd
only accepts 0 and 1 as valid rollover values.
.TP
\fBcookie\fP (nonstandard)
The
.B cookie
option accepts an arbitrary string of up to 255 bytes, and echoes it
back to the client as part of the reply (OACK) packet. The cookie
string can be used:
.IP "1." 4n
By the client, to identify that the reply packet matches the request
packet. Standard TFTP makes this difficult, because the TFTP server
normally returns the initial response using a different port number,
and under some circumstances even a different IP address.
.IP "2." 4n
By the server, to detect duplicate reception (due to retransmission)
of request packets, as opposed to a new transmission session.
.PP
The
.B \-\-refuse
option can be used to disable specific options; this may be necessary
to work around bugs in specific TFTP client implementations. For
example, some TFTP clients have been found to request the
.B blksize
option, but crash with an error if they actually get the option
accepted by the server.
.PP
The
.B \-\-refuse-all
option disables
.I all
TFTP options, and thus the server will never return an OACK packet.
.SH "FILENAME PROCESSING"
The filename requested by the server goes through the following steps,
in this order:
.PP
.IP "1." 4n
If the
.B \-\-map-file
option is used, filename remapping. See "FILENAME REMAPPING" below.
.IP "2." 4n
If the
.B \-\-normalize
option is used, filename normalization. See the
.B \-\-normalize
option above.
.IP "3." 4n
If the
.B \-\-secure
or
.B \-\-jail
options are
.I not
used, or the
.B \-\-validate
option is specified, path validation. See "PATH VALIDATION" below.
.IP "4." 4n
If the
.B \-\-path-prefix
option is used, the path prefix is prepended.
.SH "FILENAME REMAPPING"
The
.B \-\-map-file
option specifies a file which contains filename remapping rules. Each
non-comment line (comments begin with hash marks,
.BR # )
contains either a label, preceeded by a colon:
.IP
\fB:\fP\fIlabel\fP
.PP
or an
.IR operation ,
specified below, followed by an extended regular expression
.I regex
(see
.MR regex 7 ),
and optionally a
.IR "replacement pattern" .
The operation indicated by
.I operation
is performed if the
.I regex
matches all or part of the filename. Rules are processed from the top
down, and by default, all rules are processed even if there is a
match.
.PP
Sometimes it is useful to have a rule that \fIalways\fP matches, in
that case, the regular expression:
.IP
.B ^
.PP
(a single caret symbol) can be used.
.PP
The
.I operation
can be any valid combination of the following characters:
.TP
.B r
Replace the substring matched by
.I regex
by the
.IR "replacement pattern" .
The replacement pattern may contain escape sequences; see below.
.br
\fBr\fP cannot be used with \fB~\fP, \fBa\fP, or \fBj\fP.
.TP
.B g
Repeat the replacement until it no longer matches, searching the whole
string, including replacements, from the beginning each time.
.br
\fBg\fP is always used with \fBr\fP.
.TP
.B gg
Repeat the replacement until it no longer matches, but only on the portion
of the string that has not yet been matched, similar to how the
.B s
command with the
.B g
option works in
.MR sed 1 .
.br
\fBgg\fP is always used with \fBr\fP.
.TP
.B i
Match the
.I regex
case-insensitively. By default it is case sensitive.
.TP
.B e
If this rule matches, end rule processing after executing the rule.
.br
\fBe\fP cannot be used with \fBa\fP, \fBE\fP, \fBj\fP, or \fBs\fP.
.TP
.B E
If this rule matches,
\fIand the result matches a filename that can be transferred\fP,
end rule processing after executing the rule. If this is used with
.BR r ,
then if the substitution does \fInot\fP result in a valid filename,
the substitution is undone.
.br
\fBE\fP cannot be used with \fBa\fP, \fBe\fP, \fBj\fP, or \fBs\fP.
.TP
.B s
If this rule matches, start rule processing over from the very first
rule after executing this rule.
.br
\fBs\fP cannot be used with \fBa\fP, \fBe\fP, \fBE\fP, or \fBj\fP.
.TP
.B a
If this rule matches, refuse the request and send an access denied
error to the client.
.br
\fBa\fP cannot be used with \fBe\fP, \fBE\fP, \fBj\fP, \fBr\fP, or
\fBs\fP.
.TP
.B j
If this rule matches, jump to the label specified by \fIreplacement pattern\fP.
.TP
.B G
This rule applies to GET (RRQ) requests only.
.TP
.B P
This rule applies to PUT (WRQ) requests only.
.TP
.B 4
This rule applies to IPv4 sessions only.
.TP
.B 6
This rule applies to IPv6 sessions only.
.TP
.B ~
Inverse the sense of this rule, i.e. execute the
.I operation
only if the
.I regex
.I doesn't
match.
.br
\fB~\fP cannot be used with \fBr\fP.
.PP
The following escape sequences are recognized as part of a
.IR "replacement pattern" :
.TP
\fB\\0\fP
The entire string matched by the
.IR regex .
.TP
\fB\\1\fP to \fB\\9\fP
The strings matched by each of the first nine parenthesized
subexpressions,
.BR ( ... ) ,
of the
.I regex
pattern.
.TP
\fB\\i\fP
The IP address of the requesting host, in dotted-quad notation for
IPv4 (e.g. 192.0.2.169) or conventional colon form for IPv6
(e.g. 2001:db8::1).
.TP
\fB\\x\fP
The IP address of the requesting host, in expanded hexadecimal
notation (e.g. C00002A9 for IPv4, or 20010DB8000000000000000000000001
for IPv6).
.TP
\fB\\\\\fP
Literal backslash.
.TP
\fB\\\fP\fIwhitespace\fP
Literal whitespace.
.TP
\fB\\#\fP
Literal hash mark.
.TP
\fB\\U\fP
Turns all subsequent letters to upper case.
.TP
\fB\\L\fP
Turns all subsequent letters to lower case.
.TP
\fB\\E\fP
Cancels the effect of \fB\\U\fP or \fB\\L\fP.
.PP
If the mapping file is changed, you need to send
.B SIGHUP
to any outstanding
.B tftpd
process.
.SH "PATH VALIDATION"
If the
.B \-\-secure
or
.B \-\-jail
options are
.I not
given on the command line, or the
.B \-\-validate
option
.I is
given,
.B tftpd
will perform the following validation and canonicalization of the final path
name, before verifying that the path falls inside one of the
directories specified on the command line (similarly canonicalized):
.IP "1." 4n
The path name must begin with
.RB \\[lq] / \\[rq].
.IP "2." 4n
The path must not contain
.RB \\[lq] . \\[rq]
or
.RB \\[lq] .. \\[rq]
components.
.IP "3." 4n
The path name must not contain ASCII control characters (0-31).
.IP "4." 4n
Consecutive and terminal slashes are removed.
.IP "5." 4n
On Windows platforms, the characters
.B < > : \[dq] \(rs | ? *
that are invalid in filenames are prohibited. Only forward slashes
.RB (\\[lq] / \\[rq])
are permitted as a path separator. A path
name component cannot end in a
.RB \\[lq] . \\[rq]
or space character, and each path name component is checked against the
list of hard-coded Windows reserved filenames.
.PP
Validation and canonicalization are performed
.I after
filename remapping, if remapping is used.
.PP
If the
.B \-\-path-prefix
option is specified, then the path prefix is prepended
.I after
path validation has taken place.
.PP
When
.B \-\-secure
or
.B \-\-jail
is used, no path validation is performed by
.B tftpd
itself.
.SH "SECURITY"
The use of TFTP services does not require an account or password on
the server system. Due to the lack of authentication information,
.B tftpd
will allow only publicly readable files (o+r) to be accessed, unless the
.B \-\-permissive
option is specified. Files may be written only if they already exist
and are publicly writable, unless the
.B \-\-create
option is specified. Note that this extends the concept of ``public''
to include all users on all hosts that can be reached through the
network; this may not be appropriate on all systems, and its
implications should be considered before enabling TFTP service.
.PP
If there is no need for the server to accept write (upload) requests,
it is a good idea to specify the
.B \-\-read-only
command line option to prevent any accidental setting of filesystem
permissions to inadvertently allow uploads.
.PP
It is strongly recommended to use some kind of firewall or
packet-filter solution to restrict access to the TFTP port. TFTP only
uses the TFTP port itself for the initial (request) packet, and so the
cost of such a filter is neglible.
.PP
The server should be set to run as the user with the lowest possible
privilege; please see the
.B \-\-user
flag. It is strongly recommended to set up a specific user account for
.BR tftpd ,
rather than letting it run as "nobody", to guard against privilege
leaks between applications.
.PP
Access to files is restricted by the list of directories passed to
.B tftpd
on the command line. Alternatively, the
.B \-\-secure
or
.B \-\-jail
flag can be used to set up a virtual root environment for the server
to run in once a connection has been set up.
.PP
The filename mapping facility
.RB ( \-\-map-file
flag) support can be used to provide fine-grained control of
permissions as well handle nonstandard path names requested by
clients, such as Windows clients expecting to be able to use
.B \(rs
as path separators.
.PP
Make sure to examine the "FILENAME PROCESSING" flow to ensure than the
path names actually processed are the ones intended.
.SH "CONFORMING TO"
RFC 1123,
.IR "Requirements for Internet Hosts \- Application and Support" .
.br
RFC 1350,
.IR "The TFTP Protocol (revision 2)" .
.br
RFC 2347,
.IR "TFTP Option Extension" .
.br
RFC 2348,
.IR "TFTP Blocksize Option" .
.br
RFC 2349,
.IR "TFTP Timeout Interval and Transfer Size Options" .
.br
RFC 7440,
.IR "TFTP Windowsize Option"
.SH "AUTHOR"
This version of
.B tftpd
is maintained by H. Peter Anvin . It was derived from,
but has substantially diverged from, an OpenBSD source base, with
added patches by Markus Gutschke and Gero Kulhman.
.SH "BUGS"
TFTP is an incredibly inefficient protocol, even with the
.B windowsize
option enabled. These inefficiencies are inherent in the protocol and
can be partially worked around, but never fixed. Its only
justification is that an embedded TFTP client can be implemented in an
extremely small ROM.
.PP
Embedded TCP stacks are now readily available, and generally occupy
less storage than the hardware driver layer. Vendors of embedded
network hardware should strongly consider using a simple TCP-based
protocol such as HTTP/1.0 instead.
.PP
\[lq]Those who do not understand TCP are condemned to reimplement it,
poorly, at the wrong level.\[rq]
.SH "SEE ALSO"
.MR tftp 1 ,
.MR chroot 2 ,
.MR openat2 2 ,
.MR umask 2 ,
.MR services 5 ,
.MR systemd.socket 5 ,
.MR systemd.unit 5 ,
.MR regex 7 ,
.MR inetd 8 ,
.MR xinetd 8 .
tftp-hpa-7.2+20261013/tftpd/tftpd.c 0000664 0000000 0000000 00000210030 15263245305 0016406 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-4-Clause-UC
*
* Copyright (c) 1983 Regents of the University of California.
* Copyright (c) 1999-2009, 2026 H. Peter Anvin
* Copyright (c) 2011-2014 Intel Corporation; author: H. Peter Anvin
* All rights reserved.
*/
#include "config.h" /* Must be included first */
#include "cap.h"
#include "tftpd.h"
#include "path.h"
#include "strlist.h"
#include "options.h"
#include "common/clock.h"
/*
* Trivial file transfer protocol server.
*
* This version includes many modifications by Jim Guyton
*/
#include
#include
#include
#include
#include
#include "common/tftpsubs.h"
#include "common/tftp-io.h"
#include "common/tftp-xfer.h"
#include "common/pollset.h"
#include "recvfrom.h"
#include "remap.h"
#ifdef HAVE_SYS_FILIO_H
#include /* Necessary for FIONBIO on Solaris */
#endif
#if defined(HAVE_OPENAT2) && \
defined(RESOLVE_IN_ROOT) && \
defined(RESOLVE_NO_MAGICLINKS)
#define WITH_JAIL 1
struct unlink_info {
int parent; /* file descriptor to the directory */
char *filename;
char dirname[];
};
static struct unlink_info *unlink_info;
#else
#define WITH_JAIL 0
static char *unlink_info;
#endif
#ifndef O_PATH
#define O_PATH O_RDONLY
#endif
#ifndef O_DIRECTORY
#define O_DIRECTORY 0
#endif
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
/* Default daemon wait timeout when not running standalone */
#define DEFAULT_WAITTIME (900 * USEC_PER_SEC);
static int peer;
static uintmax_t timeout = DEF_TIMEOUT; /* Current timeout value */
static uintmax_t rexmtval = DEF_TIMEOUT; /* Basic timeout value */
static uintmax_t maxtimeout = TIMEOUT_LIMIT * DEF_TIMEOUT;
static bool timeout_quit;
static sigjmp_buf timeoutbuf;
static sigjmp_buf *active_timeoutbuf = &timeoutbuf;
static uint16_t rollover_val = 0;
#define PKTSIZE (MAX_SEGSIZE + 4)
#define IO_RING_MIN_BYTES (256U * 1024U)
#define MAX_MAX_WINDOWSIZE 32768 /* More than this gets dangerous */
#ifndef MAX_WINDOWSIZE
# define MAX_WINDOWSIZE MAX_MAX_WINDOWSIZE
#endif
#ifndef MAX_WINDOWBYTES
# define MAX_WINDOWBYTES 0
#endif
#if MAX_WINDOWSIZE < 1
# error MAX_WINDOWSIZE must be at least 1
#endif
static unsigned int windowsize;
static unsigned int segsize;
static union sock_addr myaddr; /* Local address */
static union sock_addr from; /* Remote address */
static const char *from_str = "";
enum tsize_mode {
TSIZE_NAK, /* tsize not possible */
TSIZE_READ, /* tsize valid read size from server */
TSIZE_WRITE /* tsize write size from client */
};
static struct tsize {
enum tsize_mode mode;
off_t size;
} tsize;
struct daemon_options dopt = {
.log_type = LOG_SYS,
.max_windowbytes = MAX_WINDOWBYTES,
.map_steps = DAEMON_DEFAULT_MAP_STEPS,
.waittime = -1,
.service = "tftp",
.user = { .name = "nobody" },
.max_upload = OFF_T_MAX
};
struct common_options xopt = {
#ifdef HAVE_IPV6
.ai_fam = AF_UNSPEC,
#else
.ai_fam = AF_INET,
#endif
.max_windowsize = MAX_WINDOWSIZE,
.blksize = MAX_SEGSIZE,
.rexmtval = DEF_TIMEOUT,
};
#ifdef WITH_REGEX
static struct rule *rewrite_rules = NULL;
static size_t rewrite_macros(char macro, const char **output);
#else
#define rewrite_rules NULL
#define rewrite_macros NULL
#endif
static void rewrite_test(FILE *);
#if WITH_JAIL
static int jail_root = AT_FDCWD;
#endif
static char *normalize_path(char *name);
static FILE *file;
noreturn static void run_worker(struct tftphdr *tp, int n);
noreturn static void tftp(struct tftphdr *tp, int n);
static void nak(int, const char *);
static void timer(int);
static void parse_option(const char *opt, const char *val, size_t len);
static size_t negotiate_options(struct tftphdr **tpp);
static unsigned int io_ring_slots(void);
static bool io_is_threaded(void);
enum protocol_option_flags {
POF_NONE = 0,
POF_REFUSE = 1, /* Option to be refused */
POF_REQ = 2, /* Option requested */
POF_ACK = 4 /* Option to be granted */
};
enum otype {
POT_UINT, /* Unsigned integer */
POT_STR, /* Arbitrary string */
};
struct daemon_protocol_option {
const char * const name; /* Canonical name */
const uint8_t nsize; /* Size of the name string including NUL */
const uint8_t otype; /* Option type */
uint16_t dsize; /* Option data length, including NUL */
enum protocol_option_flags flags;
const char *client_name; /* Pointer to name in request buffer */
uintmax_t uint; /* Numeric value */
char *str; /* Data as string, on heap */
};
#define UOPT(n) { n, sizeof(n), POT_UINT, 0, POF_NONE, NULL, 0, NULL }
#define SOPT(n) { n, sizeof(n), POT_STR , 0, POF_NONE, NULL, 0, NULL }
/* Keep this in sync with enum protocol_options_enum in common/tftp.h */
static struct daemon_protocol_option protocol_options[PO_NUM_OPTS] = {
[PO_BLKSIZE] = UOPT("blksize"),
[PO_BLKSIZE2] = UOPT("blksize2"),
[PO_COOKIE] = SOPT("cookie"),
[PO_ROLLOVER] = UOPT("rollover"),
[PO_TIMEOUT] = UOPT("timeout"),
[PO_TSIZE] = UOPT("tsize"),
[PO_UTIMEOUT] = UOPT("utimeout"),
[PO_WINDOWSIZE] = UOPT("windowsize")
};
/*
* Returns a pointer to the option structure if it was requested
* by the client and not configured to be refused.
*/
static inline struct daemon_protocol_option *
opt_requested(enum protocol_option_enum opt)
{
struct daemon_protocol_option *po = &protocol_options[opt];
if ((po->flags & (POF_REQ|POF_REFUSE)) == POF_REQ)
return po;
else
return NULL;
}
static inline bool opt_granted(const struct daemon_protocol_option *po)
{
/* The options must have been both requested and acknowledgeable */
return (po->flags & (POF_ACK|POF_REQ|POF_REFUSE)) == (POF_ACK|POF_REQ);
}
/* Signal handlers: just set a variable and return */
static volatile sig_atomic_t reload_signal = 0;
static volatile sig_atomic_t exit_signal = 0;
static void handle_exit(int sig)
{
exit_signal = sig;
pollset_notify_signal(sig);
}
static void handle_reload(int sig)
{
reload_signal = sig;
pollset_notify_signal(sig);
}
/* Handle timeout signal or timeout event */
static void timer(int sig)
{
(void)sig; /* Suppress unused warning */
timeout <<= 1;
if (timeout >= maxtimeout || timeout_quit)
exit(0);
siglongjmp(*active_timeoutbuf, 1);
}
#ifdef WITH_REGEX
static struct rule *read_remap_rules(const char *rulefile)
{
FILE *f;
struct rule *rulep;
f = fopen(rulefile, "rt");
if (!f) {
tftpd_log(LOG_ERR, "Cannot open map file: %s: %s",
rulefile, strerror(errno));
exit(EX_NOINPUT);
}
rulep = parserulefile(f);
fclose(f);
return rulep;
}
#endif
/*
* Rules for locking files; return 0 on success, -1 on failure
*/
static int lock_file(int fd, bool lock_write)
{
(void)lock_write;
#if defined(HAVE_FCNTL) && HAVE_DECL_F_SETLK
struct flock fl;
fl.l_type = lock_write ? F_WRLCK : F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0; /* Whole file */
return fcntl(fd, F_SETLK, &fl);
#elif defined(HAVE_FLOCK) && HAVE_DECL_LOCK_SH && HAVE_DECL_LOCK_EX
return flock(fd, lock_write ? LOCK_EX|LOCK_NB : LOCK_SH|LOCK_NB);
#else
return 0; /* Hope & pray... */
#endif
}
#ifndef MSG_TRUNC
#define MSG_TRUNC 0
#endif
static int recv_time(int s, void *rbuf, int len, unsigned int flags,
uintmax_t *timeout_us_p)
{
int rv = tftp_recv_time(s, rbuf, len, flags, NULL, NULL, timeout_us_p);
if (rv < 0 && errno == ETIMEDOUT)
timer(0); /* Should not return */
return rv;
}
struct daemon_xfer_context {
uintmax_t timeout;
};
static int daemon_xfer_send(void *vctx, const void *packet, int length)
{
(void)vctx;
return send(peer, packet, length, 0) == length ? 0 : -1;
}
static int daemon_xfer_recv(void *vctx, void *packet, int length)
{
struct daemon_xfer_context *ctx = vctx;
return recv_time(peer, packet, length, MSG_TRUNC, &ctx->timeout);
}
static void daemon_xfer_received(void *vctx, const struct tftphdr *packet,
int length)
{
(void)vctx;
(void)packet;
(void)length;
}
static void daemon_xfer_retry_enter(void *vctx, sigjmp_buf *retrybuf,
bool restarted)
{
(void)vctx;
active_timeoutbuf = retrybuf;
if (!restarted)
timeout = rexmtval;
}
static void daemon_xfer_retry_leave(void *vctx)
{
(void)vctx;
active_timeoutbuf = &timeoutbuf;
}
static void daemon_xfer_wait_begin(void *vctx)
{
struct daemon_xfer_context *ctx = vctx;
ctx->timeout = timeout;
}
static void daemon_xfer_dally(uint16_t last_acked)
{
int n;
struct tftphdr hdr;
timeout_quit = true;
n = recv_time(peer, &hdr, 4, MSG_TRUNC, &timeout);
timeout_quit = false;
if (n >= 4 && hdr.th_opcode == htons(DATA) &&
hdr.th_block == htons(last_acked)) {
hdr.th_opcode = htons(ACK);
(void)send(peer, &hdr, 4, 0);
}
}
static const struct tftp_xfer_ops daemon_xfer_ops = {
daemon_xfer_send,
daemon_xfer_recv,
daemon_xfer_received,
daemon_xfer_retry_enter,
daemon_xfer_retry_leave,
daemon_xfer_wait_begin
};
static void tftpd_out_of_memory(void)
{
tftpd_log(LOG_CRIT, "fatal error: %s", strerror(errno));
exit(EX_OSERR);
}
static long getenv_ulong(const char *var)
{
const char *val = getenv(var);
char *ep;
unsigned long n;
if (!val || !*val)
return -1;
errno = 0;
n = strtoul(val, &ep, 0);
if (errno || ep == val || *ep || n > LONG_MAX)
return -1;
return n;
}
static enum normalizations parse_normalize(const char *str)
{
if (!str)
return NORM_PATH;
switch (*str) {
case '\0':
return NORM_PATH;
case 'a':
if (!strcmp(str, "all"))
return NORM_PATH;
break;
case 'p':
if (!strcmp(str, "path"))
return NORM_PATH;
break;
case 'n':
if (!strcmp(str, "no") || !strcmp(str, "none"))
return NORM_NONE;
break;
case 'y':
if (!strcmp(str, "yes"))
return NORM_PATH;
break;
case 'r':
if (!strcmp(str, "root"))
return NORM_ROOT;
break;
case '/':
if (!str[1])
return NORM_ROOT;
break;
default:
break;
}
tftpd_log(LOG_ERR, "invalid --normalize option: %s\n", str);
exit(EX_USAGE);
}
static void parse_logformat(const char *fmt)
{
if (!fmt)
return; /* --stdout or --stderr without argment */
switch (fmt[0]) {
case '\0':
tftpd_log(LOG_ERR, "missing log format");
exit(EX_USAGE);
break;
case 't':
if (!strcmp(fmt, "tag") || !strcmp(fmt, "tagged")) {
dopt.log_tagged = true;
return;
}
break;
case 'h':
if (!strcmp(fmt, "human")) {
dopt.log_tagged = false;
return;
}
break;
default:
break;
}
tftpd_log(LOG_ERR, "invalid log format: %s", fmt);
exit(EX_USAGE);
}
enum long_only_options {
OPT_VERBOSITY = 256,
OPT_SYSLOG,
OPT_STDERR,
OPT_STDOUT,
OPT_LOGFILE,
OPT_MAP_TEST,
OPT_MAP_STEPS,
OPT_SYSTEMD,
OPT_WINDOW_BYTES,
OPT_REJECT_ALL,
OPT_PATH_PREFIX,
OPT_NORMALIZE,
OPT_VALIDATE,
OPT_READONLY,
OPT_MAX_UPLOAD,
OPT_LOG,
OPT_LOGFORMAT
};
static const struct option long_options[] = {
{ "ipv4", 0, NULL, '4' },
{ "ipv6", 0, NULL, '6' },
{ "create", 0, NULL, 'c' },
{ "secure", 0, NULL, 's' },
{ "chroot", 0, NULL, 's' },
{ "jail", 0, NULL, 'j' },
{ "permissive", 0, NULL, 'p' },
{ "verbose", 0, NULL, 'v' },
{ "verbosity", 1, NULL, OPT_VERBOSITY },
{ "version", 0, NULL, 'V' },
{ "listen", 0, NULL, 'l' },
{ "foreground", 0, NULL, 'L' },
{ "address", 1, NULL, 'a' },
{ "blocksize", 1, NULL, 'B' },
{ "windowsize", 1, NULL, 'W' },
{ "window-bytes", 1, NULL, OPT_WINDOW_BYTES },
{ "user", 1, NULL, 'u' },
{ "umask", 1, NULL, 'U' },
{ "refuse", 1, NULL, 'r' },
{ "reject", 1, NULL, 'r' },
{ "refuse-all", 0, NULL, OPT_REJECT_ALL },
{ "reject-all", 0, NULL, OPT_REJECT_ALL },
{ "timeout", 1, NULL, 't' },
{ "retransmit", 1, NULL, 'T' },
{ "port-range", 1, NULL, 'R' },
{ "ports", 1, NULL, 'R' },
{ "service", 1, NULL, 'S' },
{ "path-prefix", 1, NULL, OPT_PATH_PREFIX },
{ "port", 1, NULL, 'S' },
{ "map-file", 1, NULL, 'm' },
{ "map-steps", 1, NULL, OPT_MAP_STEPS },
{ "pidfile", 1, NULL, 'P' },
{ "syslog", 0, NULL, OPT_SYSLOG },
{ "stderr", 2, NULL, OPT_STDERR },
{ "stdout", 2, NULL, OPT_STDOUT },
{ "logfile", 1, NULL, OPT_LOGFILE },
{ "logformat", 1, NULL, OPT_LOGFORMAT },
{ "map-test", 1, NULL, OPT_MAP_TEST },
{ "systemd", 0, NULL, OPT_SYSTEMD },
{ "normalize", 2, NULL, OPT_NORMALIZE },
{ "validate", 0, NULL, OPT_VALIDATE },
{ "ro", 0, NULL, OPT_READONLY },
{ "read-only", 0, NULL, OPT_READONLY },
{ "max-upload", 1, NULL, OPT_MAX_UPLOAD },
{ "max-size", 1, NULL, OPT_MAX_UPLOAD },
{ NULL, 0, NULL, 0 }
};
static const char short_options[] = "46csjpvVlLa:B:W:u:U:r:t:T:R:S:m:P:";
static struct pollset *listen_set;
static void close_listen_set(void)
{
if (listen_set)
pollset_close(&listen_set);
}
static bool is_directory(const char *path)
{
struct stat st;
if (stat(path, &st) < 0)
return false;
if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
return false;
}
return true;
}
/*
* Abort after a privilege-dropping set*id(); if errno is EPERM, then
* assume the process is already restricted.
*/
static int check_drop(int v)
{
if (!v || errno == EPERM)
return v;
tftpd_log(LOG_CRIT, "cannot drop provileges: %s", strerror(errno));
exit(EX_OSERR);
}
int main(int argc, char **argv)
{
struct tftphdr *tp;
uint16_t th_opcode;
int n;
int fd = -1;
pid_t pid;
int c;
char *ep;
bool patherr;
pollset_cursor cursor;
int nullfd;
uintmax_t v;
set_progname(argv[0]);
tftpd_initlog();
out_of_memory = tftpd_out_of_memory;
capset_none();
#ifdef HAVE_LOCALE_H
setlocale(LC_CTYPE, ""); /* For to(w)(lower|upper)() */
#endif
/* Randomness is used for port (transfer ID) assignment */
random_init();
/* Initialize the list and pollset of listen addresses */
listen_set = pollset_new();
atexit(close_listen_set);
strlist_init(&dopt.listen_addrs);
/*
* This creates a /dev/null file descriptor, and backfills any
* standard file descriptors left unopened with that descriptor.
*/
nullfd = get_nullfd();
if (nullfd < 0) {
tftpd_log(LOG_ERR, "opening %s failed: %s",
_PATH_DEVNULL, strerror(errno));
exit(EX_OSFILE);
}
while ((c = getopt_long(argc, argv, short_options, long_options, NULL))
!= -1)
switch (c) {
case '4':
xopt.ai_fam = AF_INET;
break;
#ifdef HAVE_IPV6
case '6':
xopt.ai_fam = AF_INET6;
break;
#endif
case 'c':
dopt.cancreate = true;
break;
case 's':
dopt.secure = true;
break;
case 'j':
#if WITH_JAIL
dopt.jail = true;
#else
tftpd_log(LOG_ERR, "--jail not supported by this OS or build");
exit(EX_USAGE);
#endif
break;
case 'p':
dopt.unixperms = true;
break;
case 'l':
dopt.standalone = true;
break;
case 'L':
dopt.standalone = true;
dopt.nodaemon = true;
break;
case 'a':
dopt.standalone = true;
strlist_add(&dopt.listen_addrs, optarg);
break;
case 't':
v = parse_uint(optarg, 0, TYPE_MAX(intmax_t)/USEC_PER_SEC);
if (v != BAD_NUM)
dopt.waittime = v * USEC_PER_SEC;
break;
case 'S':
if (!optarg || !*optarg) {
tftpd_log(LOG_ERR, "Missing service name");
exit(EX_USAGE);
}
dopt.service = optarg;
break;
case 'B':
if (!parse_blocksize_arg(optarg, SEGSIZE)) {
tftpd_log(LOG_ERR,
"Bad maximum block size argument: %s", optarg);
exit(EX_USAGE);
}
break;
case 'W':
v = parse_uint(optarg, 0, MAX_MAX_WINDOWSIZE);
if (v == BAD_NUM) {
tftpd_log(LOG_ERR,
"Invalid maximum windowsize value (1-%d): %s\n",
MAX_MAX_WINDOWSIZE, optarg);
exit(EX_USAGE);
}
if (!v)
v = 1;
xopt.max_windowsize = v;
break;
case OPT_WINDOW_BYTES:
v = parse_uint(optarg, 0, OFF_T_MAX);
if (v == BAD_NUM) {
tftpd_log(LOG_ERR, "Bad window-bytes value: %s", optarg);
exit(EX_USAGE);
}
dopt.max_windowbytes = v;
break;
case 'T':
v = parse_uint(optarg, MIN_TIMEOUT, MAX_TIMEOUT);
if (v == BAD_NUM) {
tftpd_log(LOG_ERR, "Bad timeout value: %s", optarg);
exit(EX_USAGE);
}
xopt.rexmtval = v;
break;
case 'R':
if (sscanf(optarg, "%u:%u",
&xopt.portrange_from,
&xopt.portrange_to) != 2 ||
!xopt.portrange_from ||
xopt.portrange_from > xopt.portrange_to ||
xopt.portrange_to >= 65535) {
tftpd_log(LOG_ERR, "Bad port range: %s", optarg);
exit(EX_USAGE);
}
break;
case 'u':
dopt.user.name = optarg;
break;
case 'U':
errno = 0;
dopt.my_umask = strtoul(optarg, &ep, 8); /* Octal!! */
if (errno || ep == optarg || *ep) {
tftpd_log(LOG_ERR, "Invalid umask: %s", optarg);
exit(EX_USAGE);
}
dopt.spec_umask = true;
break;
case 'r':
{
struct daemon_protocol_option *po;
ARRAY_FOREACH(po, protocol_options) {
if (ascii_strcaseeq(optarg, po->name)) {
po->flags |= POF_REFUSE;
goto done_refuse;
}
}
tftpd_log(LOG_ERR, "Unknown option: %s", optarg);
exit(EX_USAGE);
done_refuse:
break;
}
case OPT_REJECT_ALL:
dopt.reject_all_options = true;
break;
case 'm':
#ifdef WITH_REGEX
if (dopt.rewrite_file) {
tftpd_log(LOG_ERR, "Multiple -m options");
exit(EX_USAGE);
}
dopt.rewrite_file = optarg;
#else
tftpd_log(LOG_ERR, "--map-file not supported by this build");
exit(EX_USAGE);
#endif
break;
case OPT_MAP_STEPS:
v = parse_uint(optarg, 1, INT_MAX);
if (v == BAD_NUM) {
tftpd_log(LOG_ERR, "Bad --map-steps option: %s", optarg);
exit(EX_USAGE);
}
dopt.map_steps = v;
break;
case OPT_MAP_TEST:
dopt.map_test_file = optarg;
dopt.log_type = LOG_STDERR;
dopt.log_tagged = false;
break;
case 'v':
dopt.verbosity++;
break;
case OPT_VERBOSITY:
dopt.verbosity = parse_uint(optarg, 0, INT_MAX);
break;
case OPT_SYSLOG:
dopt.log_type = LOG_SYS;
break;
case OPT_STDERR:
dopt.log_type = LOG_STDERR;
parse_logformat(optarg);
break;
case OPT_STDOUT:
dopt.log_type = LOG_STDOUT;
parse_logformat(optarg);
break;
case OPT_LOGFORMAT:
parse_logformat(optarg);
break;
case OPT_LOGFILE:
if (!*optarg) {
tftpd_log(LOG_ERR, "Missing log file name");
exit(EX_USAGE);
}
dopt.log_type = LOG_FILE;
dopt.logfile = optarg;
break;
case OPT_SYSTEMD:
dopt.nodaemon = true;
dopt.systemd = true;
break;
case OPT_PATH_PREFIX:
dopt.path_prefix = *optarg ? optarg : NULL;
break;
case 'V':
print_configuration(stdout);
exit(0);
break;
case 'P':
dopt.pidfile = optarg;
break;
case OPT_NORMALIZE:
dopt.normalize = parse_normalize(optarg);
break;
case OPT_VALIDATE:
dopt.validate = true;
break;
case OPT_READONLY:
dopt.readonly = true;
break;
case OPT_MAX_UPLOAD:
v = parse_uint(optarg, 0, OFF_T_MAX);
if (v == BAD_NUM) {
tftpd_log(LOG_ERR, "Invalid maximum upload size: %s",
optarg);
exit(EX_USAGE);
}
dopt.max_upload = v;
break;
default:
tftpd_log(LOG_ERR, "Unknown option: '%c'", optopt);
break;
}
rexmtval = timeout = xopt.rexmtval;
maxtimeout = rexmtval * TIMEOUT_LIMIT;
/* Always validate when --secure or --jail are not used */
if (!dopt.secure && !dopt.jail)
dopt.validate = true;
/* If max_upload == 0, the server is readonly */
if (!dopt.max_upload)
dopt.readonly = true;
tftpd_openlog();
#ifdef WITH_REGEX
if (dopt.rewrite_file)
rewrite_rules = read_remap_rules(dopt.rewrite_file);
#endif
if (dopt.map_test_file) {
FILE *tf;
capset_drop_all();
tf = fopen(dopt.map_test_file, "r");
if (!tf) {
tftpd_log(LOG_ERR, "%s: cannot open map test file: %s",
dopt.map_test_file, strerror(errno));
exit(EX_NOINPUT);
}
rewrite_test(tf);
fclose(tf);
exit(0);
}
if (dopt.path_prefix) {
if (!is_directory(dopt.path_prefix)) {
tftpd_log(LOG_ERR, "%s: invalid path prefix: %s",
dopt.path_prefix, strerror(errno));
exit(EX_DATAERR);
}
}
/*
* The user to run as
*/
dopt.user.pw = getpwnam(dopt.user.name);
if (!dopt.user.pw) {
tftpd_log(LOG_ERR, "no user %s: %s", dopt.user.name, strerror(errno));
exit(EX_NOUSER);
}
/*
* Set up the supplementary group list as early as possible.
*/
capset_before_initgroups();
#if defined(HAVE_INITGROUPS)
if (initgroups(dopt.user.name, dopt.user.pw->pw_gid) && errno != EPERM) {
tftpd_log(LOG_CRIT, "cannot set group list for user %s",
dopt.user.name);
exit(EX_OSERR);
}
#elif defined(HAVE_SETGROUPS)
/* If we can't get the supplementary group list, at least clear it */
if (setgroups(0, NULL) && errno != EPERM) {
tftpd_log(LOG_CRIT, "cannot clear group list for user %s",
dopt.user.name);
exit(EX_OSERR);
}
#endif
capset_after_initgroups();
dopt.dirs = xmalloc((argc - optind + 1) * sizeof(char *));
patherr = false;
for (dopt.ndirs = 0; optind != argc; optind++) {
const char *path = argv[optind];
const char * const *pathlist = parse_path(path, dopt.validate);
if (!pathlist) {
tftpd_log(LOG_ERR, "invalid directory path: %s", path);
patherr = true;
} else if (!pathlist[0] && !dopt.path_prefix) {
tftpd_log(LOG_ERR, "/ as directory path requires --path-prefix");
patherr = true;
}
dopt.dirs[dopt.ndirs++] = pathlist;
}
dopt.dirs[dopt.ndirs] = NULL;
if (patherr)
exit(EX_DATAERR);
if (!dopt.ndirs) {
tftpd_log(LOG_ERR, "directory list not specified");
exit(EX_USAGE);
}
if (dopt.secure && dopt.jail) {
tftpd_log(LOG_ERR, "--chroot and --jail are mutually exclusive");
exit(EX_USAGE);
}
if (dopt.secure || dopt.jail) {
if (dopt.ndirs != 1) {
tftpd_log(LOG_ERR, "--chroot or --jail require exactly one directory");
exit(EX_USAGE);
}
char *securepath = build_path(dopt.path_prefix, dopt.dirs[0]);
if (dopt.secure) {
if (chdir(securepath)) {
tftpd_log(LOG_ERR, "%s: %s", securepath, strerror(errno));
exit(EX_NOINPUT);
}
} else
#if WITH_JAIL
if (dopt.jail) {
/* This uses openat2() partly as a test */
static const struct open_how how = {
.flags = O_PATH | O_DIRECTORY,
.resolve = RESOLVE_NO_MAGICLINKS
};
jail_root = openat2(AT_FDCWD, securepath, &how, sizeof how);
if (jail_root < 0) {
if (errno == ENOSYS || errno == EINVAL) {
tftpd_log(LOG_ERR, "--jail not supported on this system");
exit(EX_OSERR);
} else {
tftpd_log(LOG_ERR, "%s: %s", securepath, strerror(errno));
exit(EX_NOINPUT);
}
}
} else
#endif
exit(EX_SOFTWARE); /* Should never happen */
free(securepath);
}
if (dopt.pidfile && !dopt.standalone) {
tftpd_log(LOG_WARNING, "not in standalone mode, ignoring pid file");
dopt.pidfile = NULL;
}
/*
* If no wait time is specified, set it to infinite if
* standalone, otherwise to DEFAULT_WAITTIME.
*
* If a wait time of 0 is specified, set it to infinite.
*/
if (dopt.waittime <= 0) {
if (!dopt.waittime || dopt.standalone)
dopt.waittime = -1;
else
dopt.waittime = DEFAULT_WAITTIME;
}
/*
* If we're running standalone, open the listening sockets,
* daemonize the process and add a pid file if requested.
*/
if (dopt.standalone || dopt.systemd) {
struct liststr *ls;
if (dopt.systemd) {
int startfd = 3; /* Fixed by systemd protocol */
long nfds = getenv_ulong("LISTEN_FDS");
long listen_pid = getenv_ulong("LISTEN_PID");
if (dopt.standalone) {
tftpd_log(LOG_ERR, "--systemd is mutually exclusive with the --address, --standalone and --foreground options");
exit(EX_USAGE);
}
if (listen_pid == getpid() && nfds > 0
&& nfds <= INT_MAX-startfd) {
while (nfds--)
pollset_add(listen_set, startfd++);
} else {
tftpd_log(LOG_ERR, "--systemd specified, but no file descriptors passed");
exit(EX_NOINPUT);
}
} else {
if (strlist_isempty(&dopt.listen_addrs))
strlist_add(&dopt.listen_addrs, ":");
capset_before_listen();
for (ls = dopt.listen_addrs.list; ls; ls = ls->next)
listen_to(listen_set, ls->str, xopt.ai_fam);
capset_none();
}
strlist_free(&dopt.listen_addrs);
if (pollset_isempty(listen_set)) {
tftpd_log(LOG_ERR, "no listen addresses available");
exit(EX_NOINPUT);
}
/* Daemonize this process */
/* Note: when running in secure mode (-s), we must not chdir, since
we are already in the proper directory. */
if (!dopt.nodaemon && daemon(dopt.secure, true) < 0) {
tftpd_log(LOG_ERR, "cannot daemonize: %s", strerror(errno));
exit(EX_OSERR);
}
} else {
if (pollset_isempty(listen_set)) {
/*
* inetd mode: 0 is our socket descriptor. dup() it so it is
* not one of the special descriptor numbers.
*/
fd = dup(0);
if (fd < 0) {
tftpd_log(LOG_ERR, "dup failed: %s", strerror(errno));
exit(EX_OSERR);
}
pollset_add(listen_set, fd);
}
}
/* Block out stdin/stdout/stderr */
dup2(nullfd, 0);
dup2(nullfd, 1);
dup2(nullfd, 2);
if (dopt.pidfile) {
FILE *pf = fopen(dopt.pidfile, "w");
if (!pf) {
tftpd_log(LOG_ERR,
"cannot open pid file '%s' for writing: %s",
dopt.pidfile, strerror(errno));
dopt.pidfile = NULL;
} else {
bool err = fprintf(pf, "%d\n", getpid()) < 0;
bool write_error = !!ferror(pf);
bool close_error = fclose(pf) != 0;
err = err || write_error || close_error;
if (err)
tftpd_log(LOG_ERR, "error writing pid file '%s': %s",
dopt.pidfile, strerror(errno));
}
}
cursor = 0;
while ((fd = pollset_next(listen_set, &cursor, NULL)) >= 0) {
tftpd_config_socket(fd, false);
cygwin_set_socket_nonblock(fd, false);
}
/* This means we don't want to wait() for children */
#ifndef SA_NOCLDWAIT
#define SA_NOCLDWAIT 0
#endif
set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP | SA_NOCLDWAIT);
/*
* These signals are handled synchronously: the handler simply
* sets a flag, and expect pollset_poll() to return EINTR.
*/
set_signal(SIGHUP, dopt.standalone ? handle_reload : handle_exit, 0);
set_signal(SIGTERM, handle_exit, 0);
set_signal(SIGINT, handle_exit, 0);
if (dopt.spec_umask || !dopt.unixperms)
umask(dopt.my_umask);
tp = xmalloc(PKTSIZE);
while (1) {
int what;
int rv;
if (exit_signal) {
if (dopt.pidfile && unlink(dopt.pidfile)) {
tftpd_log(LOG_WARNING, "error removing pid file '%s': %s",
dopt.pidfile, strerror(errno));
exit(EX_OSERR);
} else {
exit(0);
}
}
if (reload_signal) {
reload_signal = 0;
tftpd_rotatelog();
#ifdef WITH_REGEX
if (dopt.rewrite_file) {
freerules(rewrite_rules);
rewrite_rules = read_remap_rules(dopt.rewrite_file);
}
#endif
}
rv = pollset_poll(listen_set, POLLSET_IN, dopt.waittime);
if (rv == -1 && errno == EINTR)
continue; /* Signal caught, reloop */
if (rv == -1) {
tftpd_log(LOG_ERR, "listen loop: %s", strerror(errno));
exit(EX_IOERR);
} else if (rv == 0) {
exit(0); /* Timeout, return to inetd */
}
cursor = 0;
what = POLLSET_IN;
fd = pollset_next(listen_set, &cursor, &what);
if (fd <= 0)
continue;
cygwin_set_socket_nonblock(fd, true);
n = myrecvfrom(fd, tp, PKTSIZE, 0, &from, &myaddr);
cygwin_set_socket_nonblock(fd, false);
if (n < 0) {
int error = errno;
if (E_WOULD_BLOCK(error) || error == EINTR) {
continue; /* Again, from the top */
} else {
tftpd_log(LOG_ERR, "recvfrom: %s", strerror(error));
exit(EX_IOERR);
}
}
#ifdef HAVE_IPV6
if ((from.sa.sa_family != AF_INET) && (from.sa.sa_family != AF_INET6)) {
tftpd_log(LOG_ERR, "received address was not AF_INET/AF_INET6,"
" please check your inetd config");
exit(EX_PROTOCOL);
}
#else
if (from.sa.sa_family != AF_INET) {
tftpd_log(LOG_ERR, "received address was not AF_INET,"
" please check your inetd config");
exit(EX_PROTOCOL);
}
#endif
/*
* Ignore the packet out of hand if it isn't a valid request packet
*/
if (n < (int)sizeof(tp->th_opcode))
continue; /* Packet too short */
th_opcode = ntohs(tp->th_opcode);
if (th_opcode != RRQ && th_opcode != WRQ)
continue;
if (dopt.standalone) {
union sock_addr sa;
socklen_t len = sizeof sa;
if (((from.sa.sa_family == AF_INET) &&
(myaddr.si.sin_addr.s_addr == INADDR_ANY))
#ifdef HAVE_IPV6
|| ((from.sa.sa_family == AF_INET6) &&
IN6_IS_ADDR_UNSPECIFIED(&from.s6.sin6_addr))
#endif
) {
/* myrecvfrom() didn't capture the source address; but we might
have bound to a specific address, if so we should use it */
if (!getsockname(fd, &sa.sa, &len) &&
sa.sa.sa_family == from.sa.sa_family) {
switch (sa.sa.sa_family) {
case AF_INET:
myaddr.si.sin_addr = sa.si.sin_addr;
break;
#ifdef HAVE_IPV6
case AF_INET6:
myaddr.s6.sin6_addr = sa.s6.sin6_addr;
break;
#endif
default:
break;
}
}
}
}
/*
* Now that we have read the request packet from the UDP
* socket, we fork and go back to listening to the socket.
*/
fflush(NULL);
pid = fork();
if (pid < 0) {
tftpd_log(LOG_ERR, "fork: %s", strerror(errno));
exit(EX_OSERR); /* Return to inetd, just in case */
} else if (pid == 0) {
run_worker(tp, n);
abort(); /* It should not be possible to get here */
}
random_post_fork_parent();
}
}
noreturn static void run_worker(struct tftphdr *tp, int n)
{
/* Child process: handle the actual request here */
post_fork();
random_post_fork_child();
/* Ignore SIGHUP; make SIGTERM and SIGINT kill the process */
set_signal(SIGHUP, SIG_IGN, 0);
set_signal(SIGTERM, SIG_DFL, 0);
set_signal(SIGINT, SIG_DFL, 0);
/* Make sure the log socket is still connected. This has to be
done before the chroot, while /dev/log is still accessible,
so depending on the automatic re-opening by syslog() is unsafe. */
if (dopt.secure)
tftpd_reopenlog();
/*
* Trim the part of the request packet not actually used. Most of the
* time the request packet is *much* smaller, so freeing this memory
* early helps memory reuse.
*/
tp = xrealloc(tp, n);
/* Close file descriptors we don't need */
close_listen_set();
/* Convert the client address to a string */
from_str = net_address(&from.sa, sizeof from);
/*
* Get a socket. This has to be done before the chroot(), since
* some systems require access to /dev to create a socket, and
* some users want to use a portrange in the privileged region.
*/
peer = socket(myaddr.sa.sa_family, SOCK_DGRAM, 0);
if (peer < 0) {
tftpd_log(LOG_ERR, "socket: %s", strerror(errno));
exit(EX_IOERR);
}
capset_before_socket_bind();
if (pick_port_bind(peer, &myaddr)) {
tftpd_log(LOG_ERR, "bind: %s", strerror(errno));
exit(EX_IOERR);
}
/* Chroot and drop privileges */
if (dopt.secure) {
capset_before_chroot();
if (chroot(".") || chdir("/")) {
tftpd_log(LOG_ERR, "chroot: %s", strerror(errno));
exit(EX_OSERR);
}
}
capset_before_setid();
#ifdef HAVE_SETRESGID
check_drop(setresgid(dopt.user.pw->pw_gid, dopt.user.pw->pw_gid,
dopt.user.pw->pw_gid));
#elif defined(HAVE_SETREGID)
check_drop(setregid(dopt.user.pw->pw_gid, dopt.user.pw->pw_gid));
#else
check_drop(setegid(dopt.user.pw->pw_gid));
check_drop(setgid(dopt.user.pw->pw_gid));
#endif
#ifdef HAVE_SETRESUID
check_drop(setresuid(dopt.user.pw->pw_uid, dopt.user.pw->pw_uid,
dopt.user.pw->pw_uid));
#elif defined(HAVE_SETREUID)
check_drop(setreuid(dopt.user.pw->pw_uid, dopt.user.pw->pw_uid));
#else
/* Important: setuid() must come first */
check_drop(setuid(dopt.user.pw->pw_uid));
if (geteuid() != dopt.user.pw->pw_uid)
check_drop(seteuid(dopt.user.pw->pw_uid));
#endif
capset_none();
/* Process the request... */
if (connect(peer, &from.sa, sizeof from) < 0) {
tftpd_log(LOG_ERR, "connect: %s", strerror(errno));
exit(EX_IOERR);
}
tftpd_config_socket(peer, true);
tftp(tp, n);
abort(); /* It should not be possible to get here */
}
static const char *rewrite_access(const struct formats *,
const char *, int, int, const char **);
static int validate_access(const char *, int, const struct formats *,
const char **);
static void tftp_sendfile(const struct formats *, struct tftphdr *, int,
const char *);
static void tftp_recvfile(const struct formats *, struct tftphdr *, int,
const char *, uintmax_t);
static const struct formats formats[] = {
{ "netascii", rewrite_access, validate_access,
tftp_sendfile, tftp_recvfile, true},
{ "octet", rewrite_access, validate_access,
tftp_sendfile, tftp_recvfile, false },
};
/*
* Handle initial connection protocol.
*/
noreturn static void tftp(struct tftphdr *tp, int size)
{
char *cp, *end;
int argn, ecode;
const struct formats *pf = NULL;
char *origfilename, *request_filename = NULL;
const char *filename;
char *mode = NULL;
const char *errmsgptr;
const uint16_t tp_opcode = ntohs(tp->th_opcode);
const bool is_read = tp_opcode == RRQ;
uintmax_t upload_limit = 0;
char *val = NULL, *opt = NULL;
struct tftphdr *oack;
size_t oacklen;
if (dopt.readonly && !is_read) {
nak(EACCESS, "server is readonly");
exit(0);
}
origfilename = cp = (char *)&(tp->th_stuff);
argn = 0;
end = (char *)tp + size;
while (cp < end && *cp) {
do {
cp++;
} while (cp < end && *cp);
if (cp == end) {
nak(EBADOP, "request not null-terminated");
exit(0);
}
argn++;
if (argn == 1) {
mode = ++cp;
} else if (argn == 2) {
ARRAY_FOREACH(pf, formats) {
if (ascii_strcaseeq(pf->f_mode, mode))
goto found_format;
}
nak(EBADOP, "unknown mode");
exit(0);
found_format:
opt = ++cp;
} else if (argn & 1) {
val = ++cp;
} else {
parse_option(opt, val, cp-val);
opt = ++cp;
}
}
if (!pf) {
nak(EBADOP, "missing mode");
exit(0);
}
if (!is_read) {
/*
* If the client sent us tsize, verify up front that the upload is not
* too big, and cap the upload size to match the tsize.
*/
const struct daemon_protocol_option *tsize_opt;
upload_limit = dopt.max_upload;
tsize_opt = opt_requested(PO_TSIZE);
if (tsize_opt) {
if (tsize_opt->uint > upload_limit) {
nak(EACCESS, "upload exceeds maximum size");
exit(0);
} else {
upload_limit = tsize_opt->uint;
}
}
}
file = NULL;
request_filename = xstrdup(origfilename);
if (!(filename = (*pf->f_rewrite)
(pf, origfilename, tp_opcode, from.sa.sa_family, &errmsgptr))) {
nak(EACCESS, errmsgptr); /* File denied by mapping rule */
exit(0);
}
if (dopt.verbosity >= 1) {
if (!strcmp(filename, origfilename)) {
tftpd_log(LOG_NOTICE, "%s from %s filename %s",
packet_type(tp_opcode), from_str, filename);
} else {
tftpd_log(LOG_NOTICE, "%s from %s filename %s remapped to %s",
packet_type(tp_opcode), from_str, origfilename,
filename);
}
}
/*
* If "file" is already set, then a file was already validated
* and opened during remap processing.
*/
if (!file) {
ecode = (*pf->f_validate)(filename, tp_opcode, pf, &errmsgptr);
if (ecode == ENOTFOUND)
tftpd_log(LOG_NOTICE, "%s: file not found: %s",
from_str, filename);
if (ecode) {
nak(ecode, errmsgptr);
exit(0);
}
}
oacklen = negotiate_options(&oack);
/* There are no more uses of the request packet after this point */
xfree(tp);
tftp_set_socket_buffers(peer, segsize, windowsize, is_read);
switch (tp_opcode) {
case RRQ:
(*pf->f_send) (pf, oack, oacklen, request_filename);
break;
case WRQ:
(*pf->f_recv) (pf, oack, oacklen, request_filename, upload_limit);
break;
default:
/* This shouldn't happen... */
break;
}
exit(0); /* Request completed */
}
/*
* Keep at least one full window for retransmission, then for
* asynchronous I/O allow for the largest of:
* 1. one full TFTP window;
* 2. two full TFTP blocks;
* 3. IO_RING_MIN_BYTES (256 KiB by default).
*/
static unsigned int io_ring_slots(void)
{
#ifdef HAVE_PTHREAD
unsigned int io_slots;
io_slots = (segsize + IO_RING_MIN_BYTES - 1) / segsize;
if (io_slots < windowsize)
io_slots = windowsize;
if (io_slots < 2)
io_slots = 2;
return windowsize + io_slots;
#else
return windowsize;
#endif
}
static bool io_is_threaded(void)
{
#ifdef HAVE_PTHREAD
return true;
#else
return false;
#endif
}
/*
* Parse an RFC2347 option; we limit the arguments to positive
* integers which matches all our current options.
*/
static void parse_option(const char *opt, const char *val, size_t vlen)
{
struct daemon_protocol_option *po;
/* Global option-parsing variables initialization */
if (!*opt || !vlen)
return;
ARRAY_FOREACH(po, protocol_options) {
if (ascii_strcaseeq(po->name, opt)) {
/*
* Save the name in the same case as the client sent;
* it's not supposed to matter but broken TFTP clients abound.
*/
po->client_name = opt;
switch (po->otype) {
case POT_UINT:
{
uintmax_t v;
char *vend;
if (!ascii_isdigit(val[0]))
return; /* Invalid or signed number */
errno = 0;
v = strtoumax(val, &vend, 10);
if (vend != val + vlen || errno)
return; /* Invalid number */
po->uint = v;
break;
}
case POT_STR:
break;
default:
return; /* Invalid type, should not happen */
}
xfree(po->str);
po->str = xmemdup(val, po->dsize = vlen + 1);
po->flags |= POF_REQ;
return;
}
}
}
/*
* Select the options to acknowledge; return true if at least one
* option should be acknowledged.
*/
static void negotiate_blksize(void)
{
struct daemon_protocol_option *blk = opt_requested(PO_BLKSIZE);
struct daemon_protocol_option *blk2 = opt_requested(PO_BLKSIZE2);
unsigned int blksize = 0;
unsigned int max_blksize;
max_blksize = tftp_max_blksize(peer, &from);
if (blk2) {
if (blk2->uint < MIN_SEGSIZE) {
blk2 = NULL;
} else {
unsigned int lb;
if (blk2->uint > max_blksize)
blksize = max_blksize;
else
blksize = blk2->uint;
/* Round down to a power of 2 */
while ((lb = blksize & (blksize - 1)))
blksize = lb;
}
}
if (blk) {
if (blk->uint < MIN_SEGSIZE) {
blk = NULL;
} else {
if (blk->uint > max_blksize) {
blksize = max_blksize;
} else if (blksize > blk->uint) {
blk = NULL; /* blksize2 wins, reject blksize */
} else {
blksize = blk->uint;
}
}
}
if (!blksize)
blk = blk2 = NULL;
if (blk) {
blk->flags |= POF_ACK;
blk->uint = blksize;
}
if (blksize & (blksize - 1)) {
blk2 = NULL; /* Not a power of 2 */
} else if (blk2) {
blk2->flags |= POF_ACK;
blk2->uint = blksize;
}
if (!blk && !blk2)
blksize = SEGSIZE; /* No blksize option successfully negotiated */
segsize = blksize;
}
static void negotiate_windowsize(void)
{
struct daemon_protocol_option *ws = opt_requested(PO_WINDOWSIZE);
unsigned int window = 1;
if (ws && ws->uint > 1) {
if (ws->uint > xopt.max_windowsize)
window = xopt.max_windowsize;
else
window = ws->uint;
if ((uintmax_t)window * segsize > dopt.max_windowbytes)
window = dopt.max_windowbytes / (uintmax_t)segsize;
if (window > 1) {
ws->flags |= POF_ACK;
ws->uint = window;
} else {
window = 1;
}
}
windowsize = window;
}
static void negotiate_tsize(void)
{
struct daemon_protocol_option *ts = opt_requested(PO_TSIZE);
if (!ts)
return;
switch (tsize.mode) {
case TSIZE_NAK:
/* RRQ, but the size is not available (netascii) */
break;
case TSIZE_READ:
/*
* RRQ, and the size is available (octet). However, RFC 2349
* requires that the option value is 0, so refuse the option
* if the value is anything else.
*/
if (!ts->uint) {
ts->uint = tsize.size;
ts->flags |= POF_ACK;
}
break;
case TSIZE_WRITE:
/* WRQ: echo back the tsize specified. */
tsize.size = ts->uint;
ts->flags |= POF_ACK;
break;
default:
abort(); /* Impossible */
}
}
static void negotiate_timeout(void)
{
struct daemon_protocol_option *tos = opt_requested(PO_TIMEOUT);
struct daemon_protocol_option *tou = opt_requested(PO_UTIMEOUT);
unsigned long to = 0;
unsigned long tos_us = 0;
if (tos) {
if (tos->uint < MIN_TIMEOUT_SEC || tos->uint > MAX_TIMEOUT_SEC) {
tos = NULL;
} else {
to = tos_us = tos->uint * USEC_PER_SEC;
}
}
if (tou) {
if (tou->uint < MIN_TIMEOUT || tou->uint > MAX_TIMEOUT) {
tou = NULL;
} else {
/*
* utimeout takes priority over timeout, ack
* timeout if and only if it is the same value as
* utimeout.
*/
to = tou->uint;
if (tos_us != to)
tos = NULL;
}
}
if (tos)
tos->flags |= POF_ACK;
if (tou)
tou->flags |= POF_ACK;
if (to) {
rexmtval = timeout = to;
maxtimeout = rexmtval * TIMEOUT_LIMIT;
}
}
static void negotiate_rollover(void)
{
struct daemon_protocol_option *ro = opt_requested(PO_ROLLOVER);
if (ro && ro->uint <= 1) {
rollover_val = ro->uint;
ro->flags |= POF_ACK;
} else {
rollover_val = 0;
}
}
static void negotiate_cookie(void)
{
struct daemon_protocol_option *po = opt_requested(PO_COOKIE);
if (po && po->dsize <= TFTP_MAX_COOKIE+1)
po->flags |= POF_ACK;
}
/*
* Build an OACK packet in a new buffer and return the size. If there
* are NO options agreed upon, then return 0 and do not allocate a
* buffer.
*/
static size_t build_oack(struct tftphdr **tpp)
{
struct daemon_protocol_option *po;
struct tftphdr *tp;
char *p;
size_t bufsize = 0;
ARRAY_FOREACH(po, protocol_options) {
if (opt_granted(po)) {
switch (po->otype) {
case POT_UINT:
/* Update the option data buffer */
xfree(po->str);
po->dsize = xasprintf(&po->str, "%"PRIuMAX, po->uint) + 1;
break;
default:
break;
}
bufsize += po->nsize + po->dsize;
} else {
/* This option was never granted, so no need to carry its data */
xdelete(po->str);
}
}
if (!bufsize) {
/* No granted options, no OACK phase */
*tpp = NULL;
return 0;
}
*tpp = tp = xmalloc(bufsize + 2);
tp->th_opcode = htons(OACK);
p = tp->th_stuff;
ARRAY_FOREACH(po, protocol_options) {
if (opt_granted(po)) {
p = mempcpy(p, po->client_name, po->nsize);
p = mempcpy(p, po->str, po->dsize);
}
}
return p - (char *)tp;
}
static size_t negotiate_options(struct tftphdr **tpp)
{
if (dopt.reject_all_options) {
*tpp = NULL;
return 0;
}
negotiate_blksize();
negotiate_windowsize();
negotiate_tsize();
negotiate_timeout();
negotiate_rollover();
negotiate_cookie();
return build_oack(tpp);
}
/*
* Normalize a filename string according to the dopt.normalize
* setting. This string MUST have been allocated in heap storage, and
* may be changed.
*/
static char *normalize_path(char *fn)
{
if (!fn)
return fn;
if (dopt.normalize >= NORM_ROOT) {
/* Add a leading slash if missing */
if (fn[0] != '/') {
size_t len = strlen(fn);
fn = xrealloc(fn, len+2);
memmove(fn+1, fn, len+1);
fn[0] = '/';
}
}
if (dopt.normalize >= NORM_PATH) {
/* Handle // /./ /../ -- the first character is already / */
const char *p = fn;
char *q = fn;
char c;
while ((c = *p++)) {
*q++ = c;
while (c == '/') {
while ((c = *p) && c == '/')
p++;
if (c == '.') {
if (!p[1] || p[1] == '/') {
/* Skip . path component */
p += 1;
} else if (p[1] == '.' && (!p[2] || p[2] == '/')) {
/* .. path component; drop one level if there is one */
if (q > fn+1) {
q--; /* Drop immediately previous slash */
while (q > fn && q[-1] != '/')
q--;
}
p += 2;
}
c = *p;
}
}
}
*q = '\0';
}
return fn;
}
#ifdef WITH_REGEX
/*
* This is called by the remap engine when it encounters macros such
* as \i. It should put the output in a static buffer and put the
* buffer address in *output, then return the length of the output
* not including the terminal null.
*
* Return (size_t)-1 for an invalid macro, which then will be handled
* by the substitution code.
*/
static char hexchar(unsigned char c)
{
return c >= 10 ? (c + 'A' - 10) : c + '0';
}
static size_t rewrite_macros(char macro, const char **output)
{
#ifdef INET6_ADDRSTRLEN
static char obuf[INET_ADDRSTRLEN > 64 ? INET_ADDRSTRLEN : 64];
#else
static char obuf[64];
#endif
const unsigned char *cp;
size_t bytes;
*output = obuf;
switch (from.sa.sa_family) {
case AF_INET:
cp = (const unsigned char *)&from.si.sin_addr;
bytes = 4;
break;
#ifdef HAVE_IPV6
case AF_INET6:
cp = (const unsigned char *)&from.s6.sin6_addr;
bytes = 16;
break;
#endif
default:
return -1; /* Unknown address family... */
}
switch (macro) {
case 'i':
{
const char *p = inet_ntop(from.sa.sa_family, SOCKADDR_P(&from),
obuf, sizeof obuf);
return p ? strlen(p) : 0;
}
case 'x':
{
char *p = obuf;
while (bytes--) {
unsigned char c = *cp++;
*p++ = hexchar(c >> 4);
*p++ = hexchar(c & 15);
}
return (size_t)(p - obuf);
}
default:
return -1; /* No such macro */
}
}
#endif
static int test_validate_fail(const char *filename, int mode,
const struct formats *pf,
const char **errmsg)
{
(void)filename;
(void)mode;
(void)pf;
if (errmsg)
*errmsg = "Just testing...";
return EACCESS;
}
static void rewrite_test(FILE *tf)
{
static const struct formats test_dummy_format =
{ "dummy", NULL, test_validate_fail, NULL, NULL, false };
#ifdef HAVE_IPV6
/* Dummy addresses from netblocks assigned for documentation */
static const uint8_t phony_ip6_addr[16] =
{ 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef };
#endif
static const uint8_t phony_ip4_addr[4] = { 192, 0, 2, 34 };
char *line = xmalloc(MAX_SEGSIZE + 1);
int mode = dopt.cancreate ? WRQ : RRQ;
sa_family_t af = xopt.ai_fam;
memset(&from, 0, sizeof from);
switch (af) {
#ifdef HAVE_IPV6
case AF_INET6:
memcpy(&from.s6.sin6_addr, phony_ip6_addr, 16);
break;
#endif
default:
af = AF_INET;
memcpy(&from.si.sin_addr, phony_ip4_addr, 4);
break;
}
from.sa.sa_family = af;
from_str = net_address(&from.sa, sizeof from);
while (fgets(line, MAX_SEGSIZE + 1, tf)) {
const char *msg;
char *out;
char *nl = strchr(line, '\n');
if (!nl)
continue;
*nl = '\0';
out = rewrite_string(&test_dummy_format, line, rewrite_rules,
mode, af, rewrite_macros, &msg);
out = normalize_path(out);
if (out) {
printf("%s\n", out);
xfree(out);
} else {
printf("ERROR: %s\n", msg);
}
}
xfree(line);
}
/*
* Modify the filename, if applicable. If it returns NULL, deny the access.
* Returns either filename or a newly malloc'd buffer.
*/
static const char *rewrite_access(const struct formats *pf,
const char *filename,
int mode, int af, const char **msg)
{
char *fn;
fn = rewrite_string(pf, filename, rewrite_rules, mode,
af, rewrite_macros, msg);
fn = normalize_path(fn);
return fn;
}
/*
* Validate file access and open the corresponding file. Returns 0 if
* OK and the global variable "file" contains an open file handle. On
* failure, returns an error code. The error code is negative if it is
* an errno and strerror() should be used for the error message, or
* positive if it is a TFTP status code and *errmsg is set.
*
* Since we have no uid or gid, for now require
* file to exist and be publicly readable/writable, unless -p
* specified. If we were invoked with arguments from inetd then the
* file must also be in one of the given directory prefixes. Note
* also, full path name must be given as we have no login directory.
*
* This function is also responsible for canonicalizing file paths.
*
* If "validate" is not set, the file path is used as-is, and kernel
* is expected to enforce any namespace restrictions. "validate" is
* forced set after command line parsing if neither "secure" nor
* "jail" are set.
*/
static int validate_access(const char *filename, int mode,
const struct formats *pf,
const char **errmsg)
{
const bool is_read = mode == RRQ;
struct stat stbuf;
int fd, omode;
char *fnbuf = NULL;
const char * const **dirp;
char stdio_mode[3];
bool unlinkable;
tsize.mode = TSIZE_NAK;
*errmsg = NULL;
unlink_info = NULL;
if (dopt.validate) {
const char **pathlist = parse_path(filename, true);
if (!pathlist) {
*errmsg = "Invalid pathname specified";
return (EACCESS);
}
for (dirp = dopt.dirs; *dirp; dirp++) {
if (compare_paths(pathlist, *dirp) & 2)
break;
}
if (!*dirp) {
*errmsg = "Forbidden directory";
return (EACCESS);
}
filename = fnbuf = build_path(dopt.path_prefix, pathlist);
free(pathlist);
}
tftpd_log(LOG_DEBUG, "%s: final filename: %s", from_str, filename);
/*
* We use different a different permissions scheme if `cancreate' is
* set.
*/
omode = pf->f_convert ? O_TEXT : O_BINARY;
if (is_read) {
omode |= O_RDONLY;
unlinkable = false;
} else {
omode |= O_WRONLY;
/* O_NOFOLLOW here prevents creating a file at the end of symlink */
if (dopt.cancreate)
omode |= O_CREAT | O_NOFOLLOW;
#ifndef HAVE_FTRUNCATE
omode |= O_TRUNC; /* This really sucks on a dupe */
#endif
unlinkable = dopt.cancreate;
}
fd = -1;
#if WITH_JAIL
{
int parent = jail_root;
const char *openname = filename;
struct open_how how;
memset(&how, 0, sizeof how);
if (parent != AT_FDCWD)
how.resolve = RESOLVE_IN_ROOT | RESOLVE_NO_MAGICLINKS;
if (unlinkable) {
size_t filename_len = strlen(filename);
size_t dirname_len;
struct unlink_info *uli;
const char *p;
/*
* This is messy because of the lack of an unlinkat2()
* system call, so if a file is created it might be necessary
* to have a directory file descriptor by which to unlink it...
*/
how.flags = O_DIRECTORY | O_PATH;
unlink_info = uli = xmalloc(sizeof *uli + filename_len + 2);
p = strrchr(filename, '/');
p = p ? p+1 : filename; /* First character in the filename */
dirname_len = p - filename;
memcpy(uli->dirname, filename, dirname_len);
uli->dirname[dirname_len] = '\0';
uli->filename = uli->dirname + dirname_len + 1;
memcpy(uli->filename, p, filename_len - dirname_len + 1);
uli->parent = parent;
if (dirname_len) {
parent = openat2(parent, uli->dirname, &how, sizeof how);
if (parent < 0)
goto open_failed;
uli->parent = parent;
}
openname = uli->filename;
}
how.flags = omode;
how.mode = (omode & O_CREAT) ? 0666 : 0;
fd = openat2(parent, openname, &how, sizeof how);
}
#else
{
if (unlinkable)
unlink_info = xstrdup(filename);
fd = open(filename, omode, 0666);
}
#endif
open_failed:
if (fd < 0)
fd = -errno;
xfree(fnbuf);
if (fd < 0) {
xdelete(unlink_info);
return fd;
}
if (fstat(fd, &stbuf) < 0)
exit(EX_OSERR); /* This shouldn't happen */
/* A duplicate RRQ or (worse!) WRQ packet could really cause havoc... */
if (lock_file(fd, !is_read))
exit(0); /* Assume a transfer is already underway */
if (is_read) {
if (!dopt.unixperms && (stbuf.st_mode & (S_IREAD >> 6)) == 0) {
close(fd);
*errmsg = "File must have global read permissions";
return (EACCESS);
}
tsize.size = stbuf.st_size;
/* We don't know the tsize if conversion is needed */
tsize.mode = pf->f_convert ? TSIZE_NAK : TSIZE_READ;
} else {
if (!dopt.unixperms) {
if ((stbuf.st_mode & (S_IWRITE >> 6)) == 0) {
close(fd);
*errmsg = "File must have global write permissions";
return (EACCESS);
}
}
#ifdef HAVE_FTRUNCATE
/* We didn't get to truncate the file at open() time */
if (ftruncate(fd, (off_t) 0)) {
close(fd);
*errmsg = "Cannot reset file size";
return (EACCESS);
}
#endif
tsize.mode = TSIZE_WRITE;
}
stdio_mode[0] = is_read ? 'r' : 'w';
stdio_mode[1] = (pf->f_convert) ? 't' : 'b';
stdio_mode[2] = '\0';
file = fdopen(fd, stdio_mode);
if (file == NULL)
exit(EX_OSERR); /* Internal error */
return (0);
}
/*
* Send the requested file.
*/
static void tftp_sendfile(const struct formats *pf, struct tftphdr *oap,
int oacklen, const char *filename)
{
struct tftphdr ack; /* ack packet */
uint16_t ap_opcode, ap_block;
uintmax_t r_timeout;
int n;
struct daemon_xfer_context context;
struct tftp_xfer xfer;
struct tftp_xfer_result result;
struct tftp_io * volatile io = NULL;
if (oap) {
timeout = rexmtval;
(void)sigsetjmp(timeoutbuf, 1);
send_oack:
r_timeout = timeout;
if (send(peer, oap, oacklen, 0) != oacklen) {
tftpd_log(LOG_WARNING, "tftpd: oack: %s\n", strerror(errno));
goto out;
}
for (;;) {
n = recv_time(peer, &ack, sizeof ack, 0, &r_timeout);
if (n < 0) {
tftpd_log(LOG_WARNING, "tftpd: read: %s", strerror(errno));
goto out;
}
if (n < 2)
continue;
ap_opcode = ntohs(ack.th_opcode);
ap_block = ntohs(ack.th_block);
if (ap_opcode == ERROR) {
tftpd_log(LOG_WARNING,
"%s: client rejected negotiated options", from_str);
goto out;
} else if (n >= 4 && ap_opcode == ACK) {
if (ap_block == 0)
break;
else
goto send_oack;
}
}
}
xfree(oap);
io = tftp_io_reader_start(file, pf->f_convert, windowsize,
io_ring_slots(), segsize, io_is_threaded());
if (!io) {
nak(-errno, NULL);
goto out;
}
xfer.blocksize = segsize;
xfer.windowsize = windowsize;
xfer.max_bytes = UINTMAX_MAX;
xfer.rollover = rollover_val;
xfer.resend_oack = false;
xfer.control = &ack;
xfer.control_size = sizeof ack;
xfer.context = &context;
xfer.ops = &daemon_xfer_ops;
xfer.io_context = io;
xfer.io_ops = &tftp_io_xfer_ops;
tftp_xfer_send(&xfer, &result);
switch (result.status) {
case TFTP_XFER_READ_ERROR:
nak(-result.error, NULL);
break;
case TFTP_XFER_SEND_ERROR:
errno = result.error;
tftpd_log(LOG_WARNING, "%s: write: %s", from_str, strerror(errno));
break;
case TFTP_XFER_RECV_ERROR:
errno = result.error;
tftpd_log(LOG_WARNING, "%s: read(ack): %s", from_str, strerror(errno));
break;
case TFTP_XFER_OK:
tftpd_log(LOG_NOTICE, "%s: read completed: %s", from_str, filename);
break;
default:
break;
}
out:
tftp_io_stop(io);
io = NULL;
(void)fclose(file);
file = NULL;
}
/*
* Receive a file.
*/
static void discard_upload(void)
{
if (!dopt.cancreate) {
int fd = fileno(file);
if (fflush(file))
tftpd_log(LOG_WARNING, "%s: error flushing partial upload: %s",
from_str, strerror(errno));
if (ftruncate(fd, 0))
tftpd_log(LOG_WARNING, "%s: error truncating partial upload: %s",
from_str, strerror(errno));
}
if (fclose(file))
tftpd_log(LOG_WARNING, "%s: error closing partial upload: %s",
from_str, strerror(errno));
file = NULL;
if (dopt.cancreate) {
#if WITH_JAIL
if (unlinkat(unlink_info->parent, unlink_info->filename, 0)) {
tftpd_log(LOG_WARNING, "%s: error removing partial upload %s%s%s: %s",
from_str,
unlink_info->dirname,
unlink_info->dirname[0] ? "/" : "",
unlink_info->filename, strerror(errno));
}
#else
if (unlink(unlink_info)) {
tftpd_log(LOG_WARNING, "%s: error removing partial upload %s: %s",
from_str, unlink_info, strerror(errno));
}
#endif
}
}
static void commit_upload(void)
{
if (fclose(file))
tftpd_log(LOG_WARNING, "%s: error closing uploaded file: %s",
from_str, strerror(errno));
file = NULL;
}
static void unlink_info_cleanup(void)
{
if (!unlink_info)
return;
#if WITH_JAIL
if (unlink_info->parent != jail_root)
close(unlink_info->parent);
#endif
xdelete(unlink_info);
}
static void tftp_recvfile(const struct formats *pf,
struct tftphdr *oack, int oacklen,
const char *filename, uintmax_t max_upload)
{
struct daemon_xfer_context context;
struct tftp_xfer xfer;
struct tftp_xfer_result result;
struct tftphdr *initial_reply;
int initial_reply_len;
struct tftp_io * volatile io = NULL;
struct tftphdr *datapkt;
size_t datapktsize;
result.status = TFTP_XFER_WRITE_ERROR;
if (oack) {
initial_reply = oack;
initial_reply_len = oacklen;
} else {
/* No OACK */
initial_reply = xmalloc(4);
initial_reply->th_opcode = htons(ACK);
initial_reply->th_block = 0;
initial_reply_len = 4;
}
io = tftp_io_writer_start(file, pf->f_convert, io_ring_slots(), segsize,
io_is_threaded());
if (!io) {
nak(-errno, NULL);
goto out;
}
xfer.blocksize = segsize;
xfer.windowsize = windowsize;
xfer.max_bytes = max_upload;
xfer.rollover = rollover_val;
xfer.resend_oack = false;
xfer.control = NULL;
xfer.control_size = 0;
xfer.context = &context;
xfer.ops = &daemon_xfer_ops;
xfer.io_context = io;
xfer.io_ops = &tftp_io_xfer_ops;
datapktsize = xfer.blocksize + 4;
datapkt = xmalloc(datapktsize);
tftp_xfer_recv(&xfer, datapkt, datapktsize,
&initial_reply, initial_reply_len, NULL, 0, &result);
xfree(datapkt);
switch (result.status) {
case TFTP_XFER_BAD_DATA:
nak(EBADOP, "data packet too large");
break;
case TFTP_XFER_SIZE_EXCEEDED:
nak(EACCESS, "upload exceeds maximum size");
break;
case TFTP_XFER_WRITE_ERROR:
nak(-result.error, NULL);
break;
case TFTP_XFER_SEND_ERROR:
errno = result.error;
tftpd_log(LOG_WARNING, "%s: write(ack): %s", from_str, strerror(errno));
break;
case TFTP_XFER_RECV_ERROR:
errno = result.error;
tftpd_log(LOG_WARNING, "%s: read: %s", from_str, strerror(errno));
break;
case TFTP_XFER_OK:
tftpd_log(LOG_NOTICE, "%s: write completed: %s", from_str, filename);
break;
default:
break;
}
tftp_io_stop(io);
io = NULL;
out:
if (result.status != TFTP_XFER_OK) {
discard_upload();
} else {
commit_upload();
daemon_xfer_dally(result.last_block);
}
unlink_info_cleanup();
}
/*
* Send a nak packet (error message).
* Error code passed in is one of the
* standard TFTP codes, or a negative
* errno.
*/
static void nak(int error, const char *msg)
{
struct tftphdr *tp;
int length;
msg = error_msg(error);
length = strlen(msg) + 1;
tp = xmalloc(length + 4);
/* Convert negative errno to TFTP error codes */
switch (error) {
case -ENOENT:
case -ENOTDIR:
case -EPERM:
error = ENOTFOUND;
break;
case -ENOSPC:
error = ENOSPACE;
break;
case -EEXIST:
error = EEXISTS;
break;
default:
if (error < 0 || !*msg)
error = EUNDEF;
break;
}
tp->th_opcode = htons(ERROR);
tp->th_code = htons(error);
memcpy(tp->th_msg, msg, length);
length += 4; /* Add space for header */
if (dopt.verbosity >= 2) {
tftpd_log(LOG_INFO, "%s: sending ERROR %d: %s)",
from_str, error, tp->th_msg);
}
if (send(peer, tp, length, 0) != length)
tftpd_log(LOG_WARNING, "%s: sending ERROR failed: %s",
from_str, strerror(errno));
xfree(tp);
}
tftp-hpa-7.2+20261013/tftpd/tftpd.h 0000664 0000000 0000000 00000002674 15263245305 0016430 0 ustar 00root root 0000000 0000000 /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright 2001-2026 H. Peter Anvin - All Rights Reserved */
/*
* tftpd.h
*
* Prototypes for various functions that are part of the tftpd server.
*/
#ifndef TFTPD_TFTPD_H
#define TFTPD_TFTPD_H
#include "config.h"
#include
#include "common/tftpsubs.h"
#include "common/pollset.h"
typedef PRINTF_FUNC(2,3) void (*log_func)(int, const char *, ...);
struct tftpd_log_ops {
log_func log;
void (*open_log)(FILE *);
void (*reopen_log)(void);
void (*rotate_log)(void);
};
extern const struct tftpd_log_ops *log_ops;
#define tftpd_log (log_ops->log)
#define tftpd_reopenlog (log_ops->reopen_log)
#define tftpd_rotatelog (log_ops->rotate_log)
void tftpd_initlog(void);
void tftpd_openlog(void);
void set_signal(int, void (*)(int), int);
void tftpd_sigmask(int how, const sigset_t *set, sigset_t *oset);
int listen_to(struct pollset *set, const char *name, sa_family_t ai_fam);
struct formats {
const char *f_mode;
const char *(*f_rewrite) (const struct formats *, const char *,
int, int, const char **);
int (*f_validate) (const char *, int, const struct formats *,
const char **);
void (*f_send) (const struct formats *, struct tftphdr *, int,
const char *);
void (*f_recv) (const struct formats *, struct tftphdr *, int,
const char *, uintmax_t);
bool f_convert;
};
#endif
tftp-hpa-7.2+20261013/tftpd/version.c 0000664 0000000 0000000 00000001251 15263245305 0016755 0 ustar 00root root 0000000 0000000 /*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2026 H. Peter Anvin
*/
#include "common/tftpsubs.h"
#include "cap.h"
#include "version.h"
#ifdef WITH_REGEX
#define WITH_REGEX_STR "yes"
#else
#define WITH_REGEX_STR "no"
#endif
#ifdef HAVE_PTHREAD
#define WITH_THREADS_STR "yes"
#else
#define WITH_THREADS_STR "no"
#endif
const char version_string[] = VERSION;
void print_configuration(FILE *f)
{
fprintf(f, "%s\n"
"Filename remap: %s\n"
"I/O threads: %s\n"
"Capabilities: %s\n",
version_string,
WITH_REGEX_STR,
WITH_THREADS_STR,
capset_get_type());
}
tftp-hpa-7.2+20261013/version 0000664 0000000 0000000 00000000004 15263245305 0015406 0 ustar 00root root 0000000 0000000 7.3
tftp-hpa-7.2+20261013/xinetd/ 0000775 0000000 0000000 00000000000 15263245305 0015277 5 ustar 00root root 0000000 0000000 tftp-hpa-7.2+20261013/xinetd/tftp 0000664 0000000 0000000 00000000776 15263245305 0016211 0 ustar 00root root 0000000 0000000 # default: off
# description: The tftp server serves files using the trivial file transfer \
# protocol. The tftp protocol is often used to boot diskless \
# workstations, download configuration files to network-aware printers, \
# and to start the installation process for some operating systems.
service tftp
{
socket_type = dgram
protocol = udp
wait = yes
user = root
server = /usr/sbin/in.tftpd
server_args = -s /tftpboot
disable = yes
per_source = 11
cps = 100 2
flags = IPv4
}