Skip to content

Transferring files

Many companies exchange files with a partner through a file server. You upload a report to the partner’s server, or you download the orders the partner put there. Core\FileTransfer does this over three protocols:

  • SFTP sends files over SSH. It is encrypted, and it checks the server’s host key.
  • FTPS is FTP with TLS. It is encrypted, and it checks the server’s certificate.
  • FTP is not encrypted. Novis allows it only for an anonymous sign-in, so no password is sent unencrypted.

Your program uses the same methods with each protocol. The settings in nvs.toml choose the protocol. So the same code also works with a folder on your disk in a test.

A [file_transfer.<name>] block describes one server. You choose the name. This block is named partner:

[file_transfer.partner]
protocol = "sftp"
host = "sftp.example.com" # the port is 22 by default
user = "shop"
key_file = "/run/secrets/partner-key" # a private key in the OpenSSH format
host_key = "SHA256:K5ftMnvMI+j8dOtT7tn5PLOV5+axPc5fyLHBCjL6h3s" # the fingerprint of the server's host key
root = "exchange" # every path starts in this folder on the server
[capabilities.file_transfer]
connect = ["partner"] # the blocks this program may open

The [capabilities.file_transfer] block allows the program to open the block. Without it, Core\FileTransfer::open throws a RuntimeError. Your code gives only the name of the block. So a program cannot connect to another server.

A host key identifies an SSH server. Novis connects only when the server’s key has the fingerprint in host_key. Another machine on the network cannot pretend to be the server. An sftp block needs host_key or known_hosts_file. Without one of them, the configuration check fails and Novis does not start. To find the fingerprints of a server, run this command:

Terminal window
nvs config host-key sftp.example.com

It prints the fingerprint of each host key of the server, and the host_key line for the block. Compare each fingerprint with the one your provider publishes. Here, the provider is your partner, because they run the server. Use the key only when the fingerprints are the same.

  • key_file is the private key the program signs in with. An encrypted key also needs key_passphrase_file.
  • password_file signs in with a password instead. The file contains the password.
  • known_hosts_file is an OpenSSH known_hosts file. You can use it in place of host_key.
  • timeout is how long one operation may wait for the server. The default is 30s.

An FTPS block has protocol = "ftps":

[file_transfer.partner]
protocol = "ftps"
host = "ftp.example.com" # the port is 21 by default
tls = "explicit" # the default
user = "shop"
password_file = "/run/secrets/partner-ftp"
  • tls is explicit or implicit. With explicit, the connection starts without encryption and is encrypted before the sign-in. With implicit, it is encrypted from the first byte, and the default port is 990.
  • tls_ca_file is a PEM file with the certificate of your own certificate authority (the service that signs your server certificates).
  • tls_pin, tls_verify_host = false and tls_verify = false make the certificate check less strict. Each one needs the host in a list under [capabilities.tls]. The keys work as in a mail block, which Sending mail explains.
  • When the TLS connection fails, the error says why and who can fix it. TLS connection errors explains each message.

A block with protocol = "ftp" and no user signs in as anonymous. Use it to download public files. An ftp block with password or password_file is not valid. The configuration check fails, and Novis does not start. Ask your partner for SFTP or FTPS instead.

Read every key in Reference: configuration.

Core\FileTransfer::open connects to the server and signs in. write uploads the content and returns the number of bytes it wrote:

<?nvs
// This program uploads a daily report to the `outbox` folder of a partner's server.
use Core\FileTransfer;
// `open` connects to the server of the block `partner` in `nvs.toml`, and signs in.
var $partner = FileTransfer::open('partner');
// `write` first writes a temporary `.part` file, and then renames it to `sales.csv`.
// The partner sees the whole file or no file. This prints "wrote 21 bytes".
bytes $report = "day,total\n1,120\n2,95\n" as bytes;
echo 'wrote ', $partner->write('outbox/sales.csv', $report), " bytes\n";
// The snippet deletes the report again, so it prints the same text each time.
$partner->remove('outbox/sales.csv');
Output
wrote 21 bytes

Your partner may check the folder at any time. So write first writes a temporary file whose name ends in .part. When the last byte is written, it renames that file. So the partner sees the whole file or no file.

Some servers do not allow a rename. For them, pass false as the third argument, $atomic. Then write writes the file directly.

write takes bytes, an open Core\IO\File, an uploaded file, the request body, or chunks such as the chunks of readStream. A file or chunks are sent in parts, so the whole file is never in memory.

append adds content at the end of a file. You can use it to finish an upload that stopped. metadata($path)->size() returns the number of bytes the server already has. Send the content after those bytes with append.

list returns one Core\FileTransfer\Entry for each file and folder in a folder. readStream reads a file in chunks of at most 64 KiB. This program downloads each new order and then moves it to the folder done:

<?nvs
// This program downloads each new order from the `inbox` folder of a partner's server.
use Core\Arr;
use Core\FileTransfer;
use Core\FileTransfer\Entry;
use Core\IO;
use Core\Path;
use Core\Taint;
var $partner = FileTransfer::open('partner');
// The program saves the orders in the folder `downloads` beside this file.
string $downloads = Path::thisDirectory('downloads');
// `name()` is tainted: the server chose it, so the program checks it before it uses it in a path.
// A name such as `order-1.csv` passes, and `assertTrusted` returns it as a trusted string.
array<string> $orders = [];
foreach ($partner->list('inbox') as Entry $entry) {
if ($entry->isFile() && Path::matches('order-*.csv', $entry->name())) {
$orders[] = Taint::assertTrusted($entry->name(), 'the name matches order-*.csv');
}
}
// The server chooses the order of the list, so the program sorts the names.
foreach (Arr::sort($orders) as string $name) {
// `readStream` gives the file in chunks, and `writeStream` saves each chunk on the local disk.
// The whole file is never in memory at once.
IO::writeStream(Path::join($downloads, $name), $partner->readStream('inbox/' . $name));
// `move` puts the file in the folder `done`, so the next run does not download it again.
$partner->move('inbox/' . $name, 'done/' . $name);
echo 'downloaded ', $name, "\n";
}
// The snippet moves the orders back and deletes the downloads, so it prints the same text each time.
foreach ($orders as string $name) {
$partner->move('done/' . $name, 'inbox/' . $name);
IO::remove(Path::join($downloads, $name));
}
Output
downloaded order-1.csv
downloaded order-2.csv

readBytes returns the whole file as bytes. Use it for a small file. readBytes throws an IOError when the file is larger than the memory the request has left. It throws before it downloads the file.

walk returns every file and folder below a folder, also the ones in sub-folders. It returns a folder first, and then everything in that folder. The entries of each folder are in name order. The connection also has exists, remove, makeDirectory, removeDirectory, setPermissions and setModifiedAt. They work as the methods of the same name in Core\IO.

The server chooses the names of its files. So every string that an Entry returns is tainted. Tainted input explains what that means. A method of the connection does not accept a tainted path. Check the name first, as the program above does with Core\Path::matches. Then Core\Taint::assertTrusted returns it as a trusted string.

Every path is relative to the block’s root. A path that starts with / or contains .. throws a RuntimeError, and nothing is sent to the server.

A test should not change files on your partner’s server. For tests, the block uses a folder on your disk instead of a server. Write directory in the block, and no other key:

[file_transfer.partner]
directory = "partner"
[capabilities.file_transfer]
connect = ["partner"]
[capabilities.fs]
read = ["partner"]
write = ["partner"]

The program needs fs.read for the folder. It also needs fs.write to change a file. The class in this snippet uses only the name of the block. The same code works with a server and with a folder:

<?nvs
// This program has a class that uploads a report, and a test that runs it over a folder on disk.
use Core\FileTransfer;
use Core\Test;
final class Reports
{
// The method takes the name of a `[file_transfer]` block in `nvs.toml`.
// It works the same with a server and with a folder.
public static function send(string $block, string $csv): uint
{
return FileTransfer::open($block)->write('outbox/report.csv', $csv as bytes);
}
}
class ReportsTest
{
#[Test]
public function itUploadsTheReport(): void
{
// In this test, the block `partner` is the folder `partner` beside this file.
uint $sent = Reports::send('partner', "id,total\n1,30\n");
Test::assertEquals($sent, 14);
var $partner = FileTransfer::open('partner');
Test::assertEquals($partner->readBytes('outbox/report.csv') as string, "id,total\n1,30\n");
// The test deletes the report, so the next run of the test gives the same result.
$partner->remove('outbox/report.csv');
}
}
// `nvs run report-test.nvs` prints the line below. It does not run the test.
echo "Run `nvs test report-test.nvs` to run the test.\n";
Output
Run `nvs test report-test.nvs` to run the test.

The examples on this page use the partner folder beside them. Their output comes from its files.

The connection closes when the request or the script ends. close closes it earlier.

A new sign-in takes time. So after a request, Novis keeps the connection open, and a later request can use it. Novis keeps it only when no download or upload is still open on it. Before a later request uses the connection, Novis checks that the connection still works. pool = false in the block opens a new connection for each open.

  • Do keep the password or the key in a file, and name it with password_file or key_file.
  • Do compare the fingerprints of nvs config host-key with the ones your provider publishes.
  • Do grant [capabilities.file_transfer] connect only the blocks the program uses.
  • Do check a name from the server before you use it in a path.
  • Don’t use plain FTP for anything that needs a password. Use SFTP or FTPS.
  • Don’t test against your partner’s server. Use a directory block.

Read every method in the reference of Core\FileTransfer and Core\FileTransfer\Connection.