tftp

v1.2.3-rc0

TFTP Release Notes

Tftp 1.2.3

Improvements and New Features

The license and copyright header has changed format to include an SPDX-License-Identifier. At the same time, most files have been updated to follow a uniform standard for license headers.

Own Id: OTP-19575 Aux Id: PR-9670

Tftp 1.2.2

Fixed Bugs and Malfunctions

Fix specs in tftp:read_file function.

Own Id: OTP-19446 Aux Id: PR-9327, ERIERL-1179

Tftp 1.2.1

Improvements and New Features

The legacy dependency to error_logger has been removed. logger is now used.

Own Id: OTP-19114

Tftp 1.2

Improvements and New Features

There is a new tftp_logger callback behavior module.

Own Id: OTP-18787 Aux Id: PR-7700

The documentation has been migrated to use Markdown and ExDoc.

Own Id: OTP-18955 Aux Id: PR-8026

Tftp 1.1.1

Fixed Bugs and Malfunctions

Replaced unintentional Erlang Public License 1.1 headers in some files with the intended Apache License 2.0 header.

Own Id: OTP-18815 Aux Id: PR-7780

Tftp 1.1

Improvements and New Features

The implementation has been fixed to use proc_lib:init_fail/2,3 where appropriate, instead of proc_lib:init_ack/1,2.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-18490 Aux Id: OTP-18471, GH-6339, PR-6843

Tftp 1.0.4

Improvements and New Features

Replace size/1 with either tuple_size/1 or byte_size/1

The size/1 BIF is not optimized by the JIT, and its use can result in worse types for Dialyzer.

When one knows that the value being tested must be a tuple, tuple_size/1 should always be preferred.

When one knows that the value being tested must be a binary, byte_size/1 should be preferred. However, byte_size/1 also accepts a bitstring (rounding up size to a whole number of bytes), so one must make sure that the call to byte_size/ is preceded by a call to is_binary/1 to ensure that bitstrings are rejected. Note that the compiler removes redundant calls to is_binary/1, so if one is not sure whether previous code had made sure that the argument is a binary, it does not harm to add an is_binary/1 test immediately before the call to byte_size/1.

Own Id: OTP-18432 Aux Id: GH-6672,PR-6793,PR-6784,PR-6787,PR-6785,PR-6682,PR-6800,PR-6797,PR-6798,PR-6799,PR-6796,PR-6813,PR-6671,PR-6673,PR-6684,PR-6694,GH-6677,PR-6696,PR-6670,PR-6674

Tftp 1.0.3

Fixed Bugs and Malfunctions

Missing runtime dependencies has been added to this application.

Own Id: OTP-17243 Aux Id: PR-4557

Tftp 1.0.2

Improvements and New Features

Removed compiler warnings.

Own Id: OTP-16317 Aux Id: OTP-16183

Tftp 1.0.1

Fixed Bugs and Malfunctions

Improved documentation.

Own Id: OTP-15190

TFTP 1.0

First released version

Inets application was split into multiple smaller protocol specific applications. The TFTP application is a standalone TFTP client and server with the same functionality as TFTP in Inets.

Own Id: OTP-14113

Overview

Trivial File Transfer Protocol (TFTP) is a very simple protocol used to transfer files over the transport datagram protocol UDP.

On the client side, function read_file/3 and write_file/3 spawn a temporary client process establishing contact with a TFTP daemon and perform the file transfer.

tftp uses a callback module to handle the file transfer. Two such callback modules are provided, tftp_binary and tftp_file. See read_file/3 and write_file/3 for details. You can also implement your own callback modules, see callbacks.

Security Considerations

As stated in (RFC 1350) be aware that "Since TFTP includes no login or access control mechanisms, care must be taken in the rights granted to a TFTP server process so as not to violate the security of the server hosts file system. TFTP is often installed with controls such that only files that have public read access are available via TFTP and writing files via TFTP is disallowed."

Examples

The start/1 function starts a daemon process listening for UDP packets on a port. When it receives a request for read or write, it spawns a temporary server process handling the transfer.

This is a simple example of starting the TFTP server and reading the content of a sample file using the TFTP client.

Step 1. Create a sample file to be used for the transfer:

      $ echo "Erlang/OTP 21" > file.txt

Step 2. Start the TFTP server:

      1> {ok, Pid} = tftp:start([{port, 19999}]).
      {ok,<0.65.0>}

Step 3. Start the TFTP client (in another shell):

      1> tftp:read_file("file.txt", binary, [{port, 19999}]).
      {ok,<<"Erlang/OTP 21\n">>}

tftp behaviour

Trivial FTP.

Interface module for the tftp application.

Overwiew

This is a complete implementation of the following IETF standards:

RFC 1350, The TFTP Protocol (revision 2).
RFC 2347, TFTP Option Extension.
RFC 2348, TFTP Blocksize Option.
RFC 2349, TFTP Timeout Interval and Transfer Size Options.

The only feature that not is implemented in this release is the "netascii" transfer mode.

The start function starts a daemon process which, listens for UDP packets on a port. When it receives a request for read or write it spawns a temporary server process which handles the actual transfer of the file. On the client side the read_file/3 and write_file/3 functions spawns a temporary client process which establishes contact with a TFTP daemon and performs the actual transfer of the file.

Most of the options are common for both the client and the server side, but some of them differs a little.

Callbacks

A tftp callback module is to be implemented as a tftp behavior and export the functions listed in the following.

On the server side, the callback interaction starts with a call to open/5 with the registered initial callback state. open/5 is expected to open the (virtual) file. Then either function Module:read/1 or Module:write/2 is invoked repeatedly, once per transferred block. At each function call, the state returned from the previous call is obtained. When the last block is encountered, function Module:read/1 or Module:write/2 is expected to close the (virtual) file and return its last state. Function Module:abort/3 is only used in error situations. Function prepare/5 is not used on the server side.

On the client side, the callback interaction is the same, but it starts and ends a bit differently. It starts with a call to prepare/5 with the same arguments as open/5 takes. prepare/5 is expected to validate the TFTP options suggested by the user and to return the subset of them that it accepts. Then the options are sent to the server, which performs the same TFTP option negotiation procedure. The options that are accepted by the server are forwarded to function open/5 on the client side. On the client side, function open/5 must accept all option as-is or reject the transfer. Then the callback interaction follows the same pattern as described for the server side. When the last block is encountered in Module:read/1 or Module:write/2, the returned state is forwarded to the user and returned from read_file/3 or write_file/3.

If a callback (performing the file access in the TFTP server) takes too long time (more than the double TFTP time-out), the server aborts the connection and sends an error reply to the client. The server simply assumes that the client has given up.

If the TFTP server receives yet another request from the same client (same host and port) while it already has an active connection to the client, it ignores the new request if the request is equal to the first one (same filename and options). This implies that the (new) client will be served by the already ongoing connection on the server side. By not setting up yet another connection, in parallel with the ongoing one, the server consumes less resources.

Summary

Types

access()

Access mode.

connection_option()

All options most of them common to the client and server.

error_code()

Error reason codes.

option()

Specific TFTP protocol options

peer()

Information about the peer provided for callback.

Callbacks: Client API

open(Peer, Access, Filename, Mode, SuggestedOptions, State)

Opens a file for read or write access.

Callbacks

abort/3

Invoked when the file transfer is aborted.

prepare(Peer, Access, Filename, Mode, SuggestedOptions, InitialState)

Prepares to open a file on the client side.

read(State)

Reads a chunk from the file.

write/2

Writes a chunk to the file.

Client API

read_file(RemoteFilename, LocalFilename, Options)

Reads a (virtual) file RemoteFilename from a TFTP server.

write_file(RemoteFilename, LocalFilename, Options)

Writes a (virtual) file RemoteFilename to a TFTP server.

Server API

change_config(Pid, Options)

Changes configuration a TFTP Server

info(Pid)

Returns information about all TFTP server.

start(Options)

Starts a daemon process listening for UDP packets on a port.

Types

access()

(not exported)

-type access() :: read | write.

Access mode.

connection_option()

(not exported)

-type connection_option() :: {atom(), term()} | option().

All options most of them common to the client and server.

{debug, Level::none | error | warning | brief | normal | verbose | all}

Controls the level of debug printouts. Default is none.

{host, Host::inet:hostname()} -

The name or IP address of the host where the TFTP daemon resides. This option is only used by the client.

{port, Port::inet:port_number()}

The TFTP port where the daemon listens. Defaults is the standardized number 69. On the server side, it can sometimes make sense to set it to 0, meaning that the daemon just picks a free port (which one is returned by function info/1).

If a socket is connected already, option {udp, [{fd, integer()}]} can be used to pass the open file descriptor to gen_udp. This can be automated by using a command-line argument stating the prebound file descriptor number. For example, if the port is 69 and file descriptor 22 is opened by setuid_socket_wrap, the command-line argument "-tftpd_69 22" triggers the prebound file descriptor 22 to be used instead of opening port 69. The UDP option {udp, [{fd, 22}]} is automatically added. See init:get_argument/ about command-line arguments and gen_udp:open/2 about UDP options.

{port_policy, random | inet:port_number() | {range, Min::inet:port_number(), Max::inet:port_nuber()}

Policy for the selection of the temporary port that is used by the server/client during the file transfer. Default is random, which is the standardized policy. With this policy a randomized free port is used. A single port or a range of ports can be useful if the protocol passes through a firewall.

{udp, Options::gen_udp:option}

{use_tsize, boolean()}

Flag for automated use of option tsize. With this set to true, the write_file/3 client determines the filesize and sends it to the server as the standardized tsize option. A read_file/3 client acquires only a filesize from the server by sending a zero tsize.

{max_tsize, MaxTsize::pos_integer() | infinity}

Threshold for the maximal filesize in bytes. The transfer is aborted if the limit is exceeded. Default is infinity.

{max_conn, MaxConn::pos_integer() | infinity}

Threshold for the maximal number of active connections. The daemon rejects the setup of new connections if the limit is exceeded. Default is infinity.

TftpOption::option()

Name and value of a TFTP option.

{reject, Feature:: access() | TftpKey::string()}

Controls which features to reject. This is mostly useful for the server as it can restrict the use of certain TFTP options or read/write access.

{callback, {RegExp ::string(), Module::module(), State :: term()}}

Registration of a callback module. When a file is to be transferred, its local filename is matched to the regular expressions of the registered callbacks. The first matching callback is used during the transfer. See read_file/3 and write_file/3.

The callback module must implement the tftp behavior, see callbacks.

{logger, module()}

Callback module for customized logging of errors, warnings, and info messages. The callback module must implement the tftp_logger behavior. The default module is tftp_logger.

{max_retries, MaxRetries::non_neg_integer()}

Threshold for the maximal number of retries. By default the server/client tries to resend a message up to five times when the time-out expires.

error_code()

(not exported)

-type error_code() ::
          undef | enoent | eacces | enospc | badop | eexist | baduser | badopt | pos_integer().

Error reason codes.

option()

-type option() :: {string(), Value :: string()}.

Specific TFTP protocol options

peer()

(not exported)

-type peer() :: {PeerType :: inet | inet6, PeerHost :: inet:ip_address(), PeerPort :: port()}.

Information about the peer provided for callback.

Callbacks: Client API

open(Peer, Access, Filename, Mode, SuggestedOptions, State)

(since OTP 18.1)

-callback open(Peer :: peer(),
               Access :: access(),
               Filename :: file:name(),
               Mode :: string(),
               SuggestedOptions :: [option()],
               State :: [] | [{root_dir, string()}] | term()) ->
                  {ok, AcceptedOptions :: [option()], NewState :: term()} |
                  {error, {Code :: error_code(), string()}}.

Opens a file for read or write access.

On the client side, where the open/5 call has been preceded by a call to prepare/5, all options must be accepted or rejected.

On the server side, where there is no preceding prepare/5 call, no new options can be added, but those present in SuggestedOptions can be omitted or replaced with new values in AcceptedOptions.

Callbacks

abort/3

(since OTP 18.1)

-callback abort(Code :: error_code(), string(), State :: term()) -> ok.

Invoked when the file transfer is aborted.

The callback function is expected to clean up its used resources after the aborted file transfer, such as closing open file descriptors and so on. The function is not invoked if any of the other callback functions returns an error, as it is expected that they already have cleaned up the necessary resources. However, it is invoked if the functions fail (crash).

prepare(Peer, Access, Filename, Mode, SuggestedOptions, InitialState)

(since OTP 18.1)

-callback prepare(Peer :: peer(),
                  Access :: access(),
                  Filename :: file:name(),
                  Mode :: string(),
                  SuggestedOptions :: [option()],
                  InitialState :: [] | [{root_dir, string()}]) ->
                     {ok, AcceptedOptions :: [option()], NewState :: term()} |
                     {error, {Code :: error_code(), string()}}.

Prepares to open a file on the client side.

No new options can be added, but those present in SuggestedOptions can be omitted or replaced with new values in AcceptedOptions.

This is followed by a call to open/4 before any read/write access is performed. AcceptedOptions is sent to the server, which replies with the options that it accepts. These are then forwarded to open/4 as SuggestedOptions.

read(State)

(since OTP 18.1)

-callback read(State :: term()) ->
                  {more, binary(), NewState :: term()} |
                  {last, binary(), integer()} |
                  {error, {Code :: error_code(), string()}}.

Reads a chunk from the file.

The callback function is expected to close the file when the last file chunk is encountered. When an error is encountered, the callback function is expected to clean up after the aborted file transfer, such as closing open file descriptors, and so on. In both cases there will be no more calls to any of the callback functions.

write/2

(since OTP 18.1)

-callback write(binary(), State :: term()) ->
                   {more, NewState :: term()} |
                   {last, FileSize :: integer()} |
                   {error, {Code :: error_code(), string()}}.

Writes a chunk to the file.

The callback function is expected to close the file when the last file chunk is encountered. When an error is encountered, the callback function is expected to clean up after the aborted file transfer, such as closing open file descriptors, and so on. In both cases there will be no more calls to any of the callback functions.

Client API

read_file(RemoteFilename, LocalFilename, Options)

-spec read_file(RemoteFilename, LocalFilename, Options) -> {ok, LastCallbackState} | {error, Reason}
                   when
                       RemoteFilename :: file:filename(),
                       LocalFilename :: file:filename_all() | binary,
                       Options :: [connection_option()],
                       LastCallbackState :: term(),
                       Reason :: term().

Reads a (virtual) file RemoteFilename from a TFTP server.

If LocalFilename is the atom binary, tftp_binary is used as callback module. It concatenates all transferred blocks and returns them as one single binary in LastCallbackState.

If LocalFilename is a string and there are no registered callback modules, tftp_file is used as callback module. It writes each transferred block to the file named LocalFilename and returns the number of transferred bytes in LastCallbackState.

If LocalFilename is a string and there are registered callback modules, LocalFilename is tested against the regexps of these and the callback module corresponding to the first match is used, or an error tuple is returned if no matching regexp is found.

write_file(RemoteFilename, LocalFilename, Options)

-spec write_file(RemoteFilename, LocalFilename, Options) -> {ok, LastCallbackState} | {error, Reason}
                    when
                        RemoteFilename :: file:filename(),
                        LocalFilename :: file:filename_all() | binary,
                        Options :: [option()],
                        LastCallbackState :: term(),
                        Reason :: term().

Writes a (virtual) file RemoteFilename to a TFTP server.

If LocalFilename is a binary, tftp_binary is used as callback module. The binary is transferred block by block and the number of transferred bytes is returned in LastCallbackState.

If LocalFilename is a string and there are no registered callback modules, tftp_file is used as callback module. It reads the file named LocalFilename block by block and returns the number of transferred bytes in LastCallbackState.

If LocalFilename is a string and there are registered callback modules, LocalFilename is tested against the regexps of these and the callback module corresponding to the first match is used, or an error tuple is returned if no matching regexp is found.

Server API

change_config(Pid, Options)

Changes configuration a TFTP Server

info(Pid)

Returns information about all TFTP server.

start(Options)

-spec start(Options) -> {ok, Pid} | {error, Reason}
               when Options :: [connection_option()], Pid :: pid(), Reason :: term().

Starts a daemon process listening for UDP packets on a port.

When it receives a request for read or write, it spawns a temporary server process handling the actual transfer of the (virtual) file.

tftp_logger behaviour

Trivial FTP logger.

A tftp_logger callback module is to be implemented as a tftp_logger behavior and export the following functions:

Summary

Callbacks

error_msg(Format, Args)

Logs an error message. See logger:error/2 for details.

info_msg(Format, Args)

Logs an info message. See logger:info/2 for details.

warning_msg(Format, Args)

Logs a warning message. See logger:warning/2 for details.

Callbacks

error_msg(Format, Args)

(since OTP 18.1) (optional)

-callback error_msg(Format :: io:format(), Args :: [term()]) -> ok.

Logs an error message. See logger:error/2 for details.

info_msg(Format, Args)

(since OTP 18.1) (optional)

-callback info_msg(Format :: io:format(), Args :: [term()]) -> ok.

Logs an info message. See logger:info/2 for details.

warning_msg(Format, Args)

(since OTP 18.1) (optional)

-callback warning_msg(Format :: io:format(), Args :: [term()]) -> ok.

Logs a warning message. See logger:warning/2 for details.