reference-Custom_Storage.rst
Author: Arvid Norberg, arvid@libtorrent.org

| libtorrent

Author: | Arvid Norberg, arvid@libtorrent.org
Version: | 1.2.9

home

# Custom Storage

Table of contents

- Custom Storage
  - storage_interface
  - default_storage
  - file_pool

libtorrent provides a customization point for storage of data. By default, (`default_storage`) downloaded files are saved to disk according with the general conventions of bittorrent clients, mimicking the original file layout when the torrent was created. The libtorrent user may define a custom storage to store piece data in a different way.

A custom storage implementation must derive from and implement the storage_interface. You must also provide a function that constructs the custom storage object and provide this function to the add_torrent() call via add_torrent_params. Either passed in to the constructor or by setting the add_torrent_params::storage field.

This is an example storage implementation that stores all pieces in a `std::map`, i.e. in RAM. It's not necessarily very useful in practice, but illustrates the basics of implementing a custom storage.

    struct temp_storage : lt::storage_interface
    {
      explicit temp_storage(lt::file_storage const& fs) : lt::storage_interface(fs) {}
      void initialize(lt::storage_error&) override {}
      bool has_any_file(lt::storage_error&) override { return false; }
      void set_file_priority(lt::aux::vector<lt::download_priority_t, lt::file_index_t>&
        , lt::storage_error&) override {}
      int readv(lt::span<lt::iovec_t const> bufs, lt::piece_index_t piece
        , int offset, lt::open_mode_t, lt::storage_error&) override
      {
        auto const i = m_file_data.find(piece);
        if (i == m_file_data.end()) return 0;
        if (int(i->second.size()) <= offset) return 0;
        lt::iovec_t data{ i->second.data() + offset, int(i->second.size() - offset) };
        int ret = 0;
        for (lt::iovec_t const& b : bufs) {
          int const to_copy = std::min(int(b.size()), int(data.size()));
          memcpy(b.data(), data.data(), to_copy);
          data = data.subspan(to_copy);
          ret += to_copy;
          if (data.empty()) break;
        }
        return ret;
      }
      int writev(lt::span<lt::iovec_t const> bufs
        , lt::piece_index_t const piece, int offset, lt::open_mode_t, lt::storage_error&) override
      {
        auto& data = m_file_data[piece];
        int ret = 0;
        for (auto& b : bufs) {
          if (int(data.size()) < offset + b.size()) data.resize(offset + b.size());
          std::memcpy(data.data() + offset, b.data(), b.size());
          offset += int(b.size());
          ret += int(b.size());
        }
        return ret;
      }
      void rename_file(lt::file_index_t, std::string const&, lt::storage_error&) override
      { assert(false); }
      lt::status_t move_storage(std::string const&
        , lt::move_flags_t, lt::storage_error&) override { return lt::status_t::no_error; }
      bool verify_resume_data(lt::add_torrent_params const&
        , lt::aux::vector<std::string, lt::file_index_t> const&
        , lt::storage_error&) override
      { return false; }
      void release_files(lt::storage_error&) override {}
      void delete_files(lt::remove_flags_t, lt::storage_error&) override {}

      std::map<lt::piece_index_t, std::vector<char>> m_file_data;
    };

    lt::storage_interface* temp_storage_constructor(lt::storage_params const& params, lt::file_pool&)
    {
      return new temp_storage(params.files);
    }

[report issue]

## storage_interface

Declared in "libtorrent/storage.hpp"

The storage interface is a pure virtual class that can be implemented to customize how and where data for a torrent is stored. The default storage implementation uses regular files in the filesystem, mapping the files in the torrent in the way one would assume a torrent is saved to disk. Implementing your own storage interface makes it possible to store all data in RAM, or in some optimized order on disk (the order the pieces are received for instance), or saving multi file torrents in a single file in order to be able to take advantage of optimized disk-I/O.

It is also possible to write a thin class that uses the default storage but modifies some particular behavior, for instance encrypting the data before it's written to disk, and decrypting it when it's read again.

The storage interface is based on pieces. Every read and write operation happens in the piece-space. Each piece fits `piece_size` number of bytes. All access is done by writing and reading whole or partial pieces.

libtorrent comes with two built-in storage implementations; `default_storage` and `disabled_storage`. Their constructor functions are called default_storage_constructor() and `disabled_storage_constructor` respectively. The disabled storage does just what it sounds like. It throws away data that's written, and it reads garbage. It's useful mostly for benchmarking and profiling purpose.

    struct storage_interface: std::enable_shared_from_this<storage_interface>, aux::disk_job_fence, aux::storage_piece_set
    {
       explicit storage_interface (file_storage const& fs);
       storage_interface (storage_interface const&) = delete;
       storage_interface& operator= (storage_interface const&) = delete;
       virtual void initialize (storage_error& ec) = 0;
       virtual int writev (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) = 0;
       virtual int readv (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) = 0;
       virtual bool has_any_file (storage_error& ec) = 0;
       virtual void set_file_priority (aux::vector<download_priority_t, file_index_t>& prio
          , storage_error& ec) = 0;
       virtual status_t move_storage (std::string const& save_path
          , move_flags_t flags, storage_error& ec) = 0;
       virtual bool verify_resume_data (add_torrent_params const& rd
          , aux::vector<std::string, file_index_t> const& links
          , storage_error& ec) = 0;
       virtual void release_files (storage_error& ec) = 0;
       virtual void rename_file (file_index_t index, std::string const& new_filename
          , storage_error& ec) = 0;
       virtual void delete_files (remove_flags_t options, storage_error& ec) = 0;
       virtual bool tick ();
       file_storage const& files () const;
       bool set_need_tick ();
       void do_tick ();
       void set_owner (std::shared_ptr<void> const& tor);
       aux::session_settings const& settings () const;
       void set_storage_index (storage_index_t st);
       storage_index_t storage_index () const;
       void inc_refcount ();
       int dec_refcount ();

       aux::session_settings const* m_settings  = nullptr;
    };

[report issue]

### initialize()

    virtual void initialize (storage_error& ec) = 0;

This function is called when the storage on disk is to be initialized. The default storage will create directories and empty files at this point. If `allocate_files` is true, it will also `ftruncate` all files to their target size.

This function may be called multiple time on a single instance. When a torrent is force-rechecked, the storage is re-initialized to trigger the re-check from scratch.

The function is not necessarily called before other member functions. For instance has_any_files() and verify_resume_data() are called early to determine whether we may have to check all files or not. If we're doing a full check of the files every piece will be hashed, causing readv() to be called as well.

Any required internals that need initialization should be done in the constructor. This function is called before the torrent starts to download.

If an error occurs, `storage_error` should be set to reflect it.

[report issue]

### readv() writev()

    virtual int writev (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) = 0;
    virtual int readv (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) = 0;

These functions should read and write the data in or to the given `piece` at the given `offset`. It should read or write `num_bufs` buffers sequentially, where the size of each buffer is specified in the buffer array `bufs`. The iovec_t type has the following members:

    struct iovec_t { void* iov_base; size_t iov_len; };

These functions may be called simultaneously from multiple threads. Make sure they are thread safe. The `file` in libtorrent is thread safe when it can fall back to `pread`, `preadv` or the windows equivalents. On targets where read operations cannot be thread safe (i.e one has to seek first and then read), only one disk thread is used.

The `offset` is aligned to 16 kiB boundaries most of the time, but there are rare exceptions when it's not. Specifically if the read cache is disabled/or full and a peer requests unaligned data. Most clients request aligned data.

The number of bytes read or written should be returned, or -1 on error. If there's an error, the `storage_error` must be filled out to represent the error that occurred.

For possible values of `flags`, see open_mode_t.

[report issue]

### has_any_file()

    virtual bool has_any_file (storage_error& ec) = 0;

This function is called when first checking (or re-checking) the storage for a torrent. It should return true if any of the files that is used in this storage exists on disk. If so, the storage will be checked for existing pieces before starting the download.

If an error occurs, `storage_error` should be set to reflect it.

[report issue]

### set_file_priority()

    virtual void set_file_priority (aux::vector<download_priority_t, file_index_t>& prio
          , storage_error& ec) = 0;

change the priorities of files. This is a fenced job and is guaranteed to be the only running function on this storage when called

[report issue]

### move_storage()

    virtual status_t move_storage (std::string const& save_path
          , move_flags_t flags, storage_error& ec) = 0;

This function should move all the files belonging to the storage to the new save_path. The default storage moves the single file or the directory of the torrent.

Before moving the files, any open file handles may have to be closed, like `release_files()`.

If an error occurs, `storage_error` should be set to reflect it.

[report issue]

### verify_resume_data()

    virtual bool verify_resume_data (add_torrent_params const& rd
          , aux::vector<std::string, file_index_t> const& links
          , storage_error& ec) = 0;

This function should verify the resume data `rd` with the files on disk. If the resume data seems to be up-to-date, return true. If not, set `error` to a description of what mismatched and return false.

The default storage may compare file sizes and time stamps of the files.

If an error occurs, `storage_error` should be set to reflect it.

This function should verify the resume data `rd` with the files on disk. If the resume data seems to be up-to-date, return true. If not, set `error` to a description of what mismatched and return false.

If the `links` pointer is non-empty, it has the same number of elements as there are files. Each element is either empty or contains the absolute path to a file identical to the corresponding file in this torrent. The storage must create hard links (or copy) those files. If any file does not exist or is inaccessible, the disk job must fail.

[report issue]

### release_files()

    virtual void release_files (storage_error& ec) = 0;

This function should release all the file handles that it keeps open to files belonging to this storage. The default implementation just calls file_pool::release_files().

If an error occurs, `storage_error` should be set to reflect it.

[report issue]

### rename_file()

    virtual void rename_file (file_index_t index, std::string const& new_filename
          , storage_error& ec) = 0;

Rename the file with index `file` to name `new_name`.

If an error occurs, `storage_error` should be set to reflect it.

[report issue]

### delete_files()

    virtual void delete_files (remove_flags_t options, storage_error& ec) = 0;

This function should delete some or all of the storage for this torrent. The `options` parameter specifies whether to delete all files or just the partfile. `options` are set to the same value as the options passed to session::remove_torrent().

If an error occurs, `storage_error` should be set to reflect it.

The `disk_buffer_pool` is used to allocate and free disk buffers. It has the following members:

    struct disk_buffer_pool
    {
            char* allocate_buffer(char const* category);
            void free_buffer(char* buf);

            char* allocate_buffers(int blocks, char const* category);
            void free_buffers(char* buf, int blocks);

            int block_size() const { return m_block_size; }

    };

[report issue]

### tick()

    virtual bool tick ();

called periodically (useful for deferred flushing). When returning false, it means no more ticks are necessary. Any disk job submitted will re-enable ticking. The default will always turn ticking back off again.

[report issue]

### settings()

    aux::session_settings const& settings () const;

access global session_settings

[report issue]

m_settings
  initialized in disk_io_thread::perform_async_job

[report issue]

## default_storage

Declared in "libtorrent/storage.hpp"

The default implementation of storage_interface. Behaves as a normal bittorrent client. It is possible to derive from this class in order to override some of its behavior, when implementing a custom storage.

    class default_storage : public storage_interface
    {
       explicit default_storage (storage_params const& params, file_pool&);
       void delete_files (remove_flags_t options, storage_error& ec) override;
       status_t move_storage (std::string const& save_path
          , move_flags_t flags, storage_error& ec) override;
       bool tick () override;
       bool verify_resume_data (add_torrent_params const& rd
          , aux::vector<std::string, file_index_t> const& links
          , storage_error& error) override;
       void release_files (storage_error& ec) override;
       void initialize (storage_error& ec) override;
       void rename_file (file_index_t index, std::string const& new_filename
          , storage_error& ec) override;
       void set_file_priority (aux::vector<download_priority_t, file_index_t>& prio
          , storage_error& ec) override;
       bool has_any_file (storage_error& ec) override;
       int readv (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) override;
       int writev (span<iovec_t const> bufs
          , piece_index_t piece, int offset, open_mode_t flags, storage_error& ec) override;
       file_storage const& files () const;
    };

[report issue]

### default_storage()

    explicit default_storage (storage_params const& params, file_pool&);

constructs the default_storage based on the give file_storage (fs). `mapped` is an optional argument (it may be nullptr). If non-nullptr it represents the file mapping that have been made to the torrent before adding it. That's where files are supposed to be saved and looked for on disk. `save_path` is the root save folder for this torrent. `file_pool` is the cache of file handles that the storage will use. All files it opens will ask the file_pool to open them. `file_prio` is a vector indicating the priority of files on startup. It may be an empty vector. Any file whose index is not represented by the vector (because the vector is too short) are assumed to have priority 1. this is used to treat files with priority 0 slightly differently.

[report issue]

### files()

    file_storage const& files () const;

if the files in this storage are mapped, returns the mapped file_storage, otherwise returns the original file_storage object.

[report issue]

## file_pool

Declared in "libtorrent/file_pool.hpp"

this is an internal cache of open file handles. It's primarily used by storage_interface implementations. It provides semi weak guarantees of not opening more file handles than specified. Given multiple threads, each with the ability to lock a file handle (via smart pointer), there may be windows where more file handles are open.

    struct file_pool : boost::noncopyable
    {
       ~file_pool ();
       explicit file_pool (int size = 40);
       file_handle open_file (storage_index_t st, std::string const& p
          , file_index_t file_index, file_storage const& fs, open_mode_t m
          , error_code& ec);
       void release ();
       void release (storage_index_t st);
       void release (storage_index_t st, file_index_t file_index);
       void resize (int size);
       int size_limit () const;
       void close_oldest ();
    };

[report issue]

### file_pool() ~file_pool()

    ~file_pool ();
    explicit file_pool (int size = 40);

`size` specifies the number of allowed files handles to hold open at any given time.

[report issue]

### open_file()

    file_handle open_file (storage_index_t st, std::string const& p
          , file_index_t file_index, file_storage const& fs, open_mode_t m
          , error_code& ec);

return an open file handle to file at `file_index` in the file_storage `fs` opened at save path `p`. `m` is the file open mode (see file::open_mode_t).

[report issue]

### release()

    void release ();
    void release (storage_index_t st);
    void release (storage_index_t st, file_index_t file_index);

release all files belonging to the specified storage_interface (`st`) the overload that takes `file_index` releases only the file with that index in storage `st`.

[report issue]

### resize()

    void resize (int size);

update the allowed number of open file handles to `size`.

[report issue]

### size_limit()

    int size_limit () const;

returns the current limit of number of allowed open file handles held by the file_pool.

[report issue]

### close_oldest()

    void close_oldest ();

close the file that was opened least recently (i.e. not accessed least recently). The purpose is to make the OS (really just windows) clear and flush its disk cache associated with this file. We don't want any file to stay open for too long, allowing the disk cache to accrue.