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

| libtorrent

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

home

# Session

Table of contents

- Session
  - stats_metric
  - session_handle
  - session_proxy
  - session_params
  - session
  - session_stats_metrics()
  - find_metric_idx()
  - read_session_params()
  - enum metric_type_t

[report issue]

## stats_metric

Declared in "libtorrent/session_stats.hpp"

describes one statistics metric from the session. For more information, see the session statistics section.

    struct stats_metric
    {
       char const* name;
       int value_index;
       metric_type_t type;
    };

[report issue]

name
  the name of the counter or gauge

[report issue]

value_index type
  the index into the session stats array, where the underlying value of this counter or gauge is found. The session stats array is part of the session_stats_alert object.

[report issue]

## session_handle

Declared in "libtorrent/session_handle.hpp"

this class provides a non-owning handle to a session and a subset of the interface of the session class. If the underlying session is destructed any handle to it will no longer be valid. is_valid() will return false and any operation on it will throw a system_error exception, with error code invalid_session_handle.

    struct session_handle
    {
       bool is_valid () const;
       void load_state (bdecode_node const& e, save_state_flags_t flags = save_state_flags_t::all());
       void save_state (entry& e, save_state_flags_t flags = save_state_flags_t::all()) const;
       std::vector<torrent_status> get_torrent_status (
          std::function<bool(torrent_status const&)> const& pred
          , status_flags_t flags = {}) const;
       void refresh_torrent_status (std::vector<torrent_status>* ret
          , status_flags_t flags = {}) const;
       void post_torrent_updates (status_flags_t flags = status_flags_t::all());
       void post_session_stats ();
       void post_dht_stats ();
       std::vector<torrent_handle> get_torrents () const;
       torrent_handle find_torrent (sha1_hash const& info_hash) const;
       void async_add_torrent (add_torrent_params const& params);
       torrent_handle add_torrent (add_torrent_params const& params);
       torrent_handle add_torrent (add_torrent_params&& params);
       torrent_handle add_torrent (add_torrent_params&& params, error_code& ec);
       void async_add_torrent (add_torrent_params&& params);
       torrent_handle add_torrent (add_torrent_params const& params, error_code& ec);
       void resume ();
       bool is_paused () const;
       void pause ();
       void get_cache_info (cache_status* ret, torrent_handle h = torrent_handle(), int flags = 0) const;
       dht::dht_settings get_dht_settings () const;
       bool is_dht_running () const;
       void set_dht_settings (dht::dht_settings const& settings);
       void set_dht_storage (dht::dht_storage_constructor_type sc);
       void add_dht_node (std::pair<std::string, int> const& node);
       void dht_get_item (sha1_hash const& target);
       void dht_get_item (std::array<char, 32> key
          , std::string salt = std::string());
       sha1_hash dht_put_item (entry data);
       void dht_put_item (std::array<char, 32> key
          , std::function<void(entry&, std::array<char, 64>&
          , std::int64_t&, std::string const&)> cb
          , std::string salt = std::string());
       void dht_announce (sha1_hash const& info_hash, int port = 0, dht::announce_flags_t flags = {});
       void dht_get_peers (sha1_hash const& info_hash);
       void dht_live_nodes (sha1_hash const& nid);
       void dht_sample_infohashes (udp::endpoint const& ep, sha1_hash const& target);
       void dht_direct_request (udp::endpoint const& ep, entry const& e, void* userdata = nullptr);
       void add_extension (std::function<std::shared_ptr<torrent_plugin>(
          torrent_handle const&, void*)> ext);
       void add_extension (std::shared_ptr<plugin> ext);
       void set_ip_filter (ip_filter const& f);
       ip_filter get_ip_filter () const;
       void set_port_filter (port_filter const& f);
       unsigned short listen_port () const;
       bool is_listening () const;
       unsigned short ssl_listen_port () const;
       ip_filter get_peer_class_filter () const;
       void set_peer_class_filter (ip_filter const& f);
       void set_peer_class_type_filter (peer_class_type_filter const& f);
       peer_class_type_filter get_peer_class_type_filter () const;
       peer_class_t create_peer_class (char const* name);
       void delete_peer_class (peer_class_t cid);
       void set_peer_class (peer_class_t cid, peer_class_info const& pci);
       peer_class_info get_peer_class (peer_class_t cid) const;
       void remove_torrent (const torrent_handle& h, remove_flags_t options = {});
       void apply_settings (settings_pack const& s);
       settings_pack get_settings () const;
       void apply_settings (settings_pack&& s);
       void pop_alerts (std::vector<alert*>* alerts);
       alert* wait_for_alert (time_duration max_wait);
       void set_alert_notify (std::function<void()> const& fun);
       void delete_port_mapping (port_mapping_t handle);
       std::vector<port_mapping_t> add_port_mapping (portmap_protocol t, int external_port, int local_port);
       void reopen_network_sockets (reopen_network_flags_t options = reopen_map_ports);
       std::shared_ptr<aux::session_impl> native_handle () const;

       static constexpr save_state_flags_t save_settings  = 0_bit;
       static constexpr save_state_flags_t save_dht_settings  = 1_bit;
       static constexpr save_state_flags_t save_dht_state  = 2_bit;
       static constexpr peer_class_t global_peer_class_id {0};
       static constexpr peer_class_t tcp_peer_class_id {1};
       static constexpr peer_class_t local_peer_class_id {2};
       static constexpr remove_flags_t delete_files  = 0_bit;
       static constexpr remove_flags_t delete_partfile  = 1_bit;
       static constexpr session_flags_t add_default_plugins  = 0_bit;
       static constexpr portmap_protocol udp  = portmap_protocol::udp;
       static constexpr portmap_protocol tcp  = portmap_protocol::tcp;
       static constexpr reopen_network_flags_t reopen_map_ports  = 0_bit;
    };

[report issue]

### is_valid()

    bool is_valid () const;

returns true if this handle refers to a valid session object. If the session has been destroyed, all session_handle objects will expire and not be valid.

[report issue]

### save_state() load_state()

    void load_state (bdecode_node const& e, save_state_flags_t flags = save_state_flags_t::all());
    void save_state (entry& e, save_state_flags_t flags = save_state_flags_t::all()) const;

loads and saves all session settings, including dht_settings, encryption settings and proxy settings. `save_state` writes all keys to the `entry` that's passed in, which needs to either not be initialized, or initialized as a dictionary.

`load_state` expects a bdecode_node which can be built from a bencoded buffer with bdecode().

The `flags` argument is used to filter which parts of the session state to save or load. By default, all state is saved/restored (except for the individual torrents).

When saving settings, there are two fields that are not loaded. `peer_fingerprint` and `user_agent`. Those are left as configured by the `session_settings` passed to the session constructor or subsequently set via apply_settings().

[report issue]

### get_torrent_status() refresh_torrent_status()

    std::vector<torrent_status> get_torrent_status (
          std::function<bool(torrent_status const&)> const& pred
          , status_flags_t flags = {}) const;
    void refresh_torrent_status (std::vector<torrent_status>* ret
          , status_flags_t flags = {}) const;

Note

these calls are potentially expensive and won't scale well with lots of torrents. If you're concerned about performance, consider using `post_torrent_updates()` instead.

`get_torrent_status` returns a vector of the torrent_status for every torrent which satisfies `pred`, which is a predicate function which determines if a torrent should be included in the returned set or not. Returning true means it should be included and false means excluded. The `flags` argument is the same as to torrent_handle::status(). Since `pred` is guaranteed to be called for every torrent, it may be used to count the number of torrents of different categories as well.

`refresh_torrent_status` takes a vector of torrent_status structs (for instance the same vector that was returned by get_torrent_status() ) and refreshes the status based on the `handle` member. It is possible to use this function by first setting up a vector of default constructed `torrent_status` objects, only initializing the `handle` member, in order to request the torrent status for multiple torrents in a single call. This can save a significant amount of time if you have a lot of torrents.

Any torrent_status object whose `handle` member is not referring to a valid torrent are ignored.

The intended use of these functions is to start off by calling `get_torrent_status()` to get a list of all torrents that match your criteria. Then call `refresh_torrent_status()` on that list. This will only refresh the status for the torrents in your list, and thus ignore all other torrents you might be running. This may save a significant amount of time, especially if the number of torrents you're interested in is small. In order to keep your list of interested torrents up to date, you can either call `get_torrent_status()` from time to time, to include torrents you might have become interested in since the last time. In order to stop refreshing a certain torrent, simply remove it from the list.

[report issue]

### post_torrent_updates()

    void post_torrent_updates (status_flags_t flags = status_flags_t::all());

This functions instructs the session to post the state_update_alert, containing the status of all torrents whose state changed since the last time this function was called.

Only torrents who has the state subscription flag set will be included. This flag is on by default. See add_torrent_params. the `flags` argument is the same as for torrent_handle::status(). see status_flags_t in torrent_handle.

[report issue]

### post_session_stats()

    void post_session_stats ();

This function will post a session_stats_alert object, containing a snapshot of the performance counters from the internals of libtorrent. To interpret these counters, query the session via session_stats_metrics().

For more information, see the session statistics section.

[report issue]

### post_dht_stats()

    void post_dht_stats ();

This will cause a dht_stats_alert to be posted.

[report issue]

### get_torrents() find_torrent()

    std::vector<torrent_handle> get_torrents () const;
    torrent_handle find_torrent (sha1_hash const& info_hash) const;

`find_torrent()` looks for a torrent with the given info-hash. In case there is such a torrent in the session, a torrent_handle to that torrent is returned. In case the torrent cannot be found, an invalid torrent_handle is returned.

See `torrent_handle::is_valid()` to know if the torrent was found or not.

`get_torrents()` returns a vector of torrent_handles to all the torrents currently in the session.

[report issue]

### add_torrent() async_add_torrent()

    void async_add_torrent (add_torrent_params const& params);
    torrent_handle add_torrent (add_torrent_params const& params);
    torrent_handle add_torrent (add_torrent_params&& params);
    torrent_handle add_torrent (add_torrent_params&& params, error_code& ec);
    void async_add_torrent (add_torrent_params&& params);
    torrent_handle add_torrent (add_torrent_params const& params, error_code& ec);

You add torrents through the add_torrent() function where you give an object with all the parameters. The add_torrent() overloads will block until the torrent has been added (or failed to be added) and returns an error code and a torrent_handle. In order to add torrents more efficiently, consider using async_add_torrent() which returns immediately, without waiting for the torrent to add. Notification of the torrent being added is sent as add_torrent_alert.

The overload that does not take an error_code throws an exception on error and is not available when building without exception support. The torrent_handle returned by add_torrent() can be used to retrieve information about the torrent's progress, its peers etc. It is also used to abort a torrent.

If the torrent you are trying to add already exists in the session (is either queued for checking, being checked or downloading) `add_torrent()` will throw system_error which derives from `std::exception` unless duplicate_is_error is set to false. In that case, add_torrent() will return the handle to the existing torrent.

The add_torrent_params class has a flags field. It can be used to control what state the new torrent will be added in. Common flags to want to control are torrent_flags::paused and torrent_flags::auto_managed. In order to add a magnet link that will just download the metadata, but no payload, set the torrent_flags::upload_mode flag.

[report issue]

### pause() resume() is_paused()

    void resume ();
    bool is_paused () const;
    void pause ();

Pausing the session has the same effect as pausing every torrent in it, except that torrents will not be resumed by the auto-manage mechanism. Resuming will restore the torrents to their previous paused state. i.e. the session pause state is separate from the torrent pause state. A torrent is inactive if it is paused or if the session is paused.

[report issue]

### get_cache_info()

    void get_cache_info (cache_status* ret, torrent_handle h = torrent_handle(), int flags = 0) const;

Fills in the cache_status struct with information about the given torrent. If `flags` is `session::disk_cache_no_pieces` the `cache_status::pieces` field will not be set. This may significantly reduce the cost of this call.

[report issue]

### is_dht_running() get_dht_settings() set_dht_settings()

    dht::dht_settings get_dht_settings () const;
    bool is_dht_running () const;
    void set_dht_settings (dht::dht_settings const& settings);

`set_dht_settings` sets some parameters available to the dht node. See dht_settings for more information.

`is_dht_running()` returns true if the DHT support has been started and false otherwise.

`get_dht_settings()` returns the current settings

[report issue]

### set_dht_storage()

    void set_dht_storage (dht::dht_storage_constructor_type sc);

`set_dht_storage` set a dht custom storage constructor function to be used internally when the dht is created.

Since the dht storage is a critical component for the dht behavior, this function will only be effective the next time the dht is started. If you never touch this feature, a default map-memory based storage is used.

If you want to make sure the dht is initially created with your custom storage, create a session with the setting `settings_pack::enable_dht` to false, set your constructor function and call `apply_settings` with `settings_pack::enable_dht` to true.

[report issue]

### add_dht_node()

    void add_dht_node (std::pair<std::string, int> const& node);

`add_dht_node` takes a host name and port pair. That endpoint will be pinged, and if a valid DHT reply is received, the node will be added to the routing table.

[report issue]

### dht_get_item()

    void dht_get_item (sha1_hash const& target);

query the DHT for an immutable item at the `target` hash. the result is posted as a dht_immutable_item_alert.

[report issue]

### dht_get_item()

    void dht_get_item (std::array<char, 32> key
          , std::string salt = std::string());

query the DHT for a mutable item under the public key `key`. this is an ed25519 key. `salt` is optional and may be left as an empty string if no salt is to be used. if the item is found in the DHT, a dht_mutable_item_alert is posted.

[report issue]

### dht_put_item()

    sha1_hash dht_put_item (entry data);

store the given bencoded data as an immutable item in the DHT. the returned hash is the key that is to be used to look the item up again. It's just the SHA-1 hash of the bencoded form of the structure.

[report issue]

### dht_put_item()

    void dht_put_item (std::array<char, 32> key
          , std::function<void(entry&, std::array<char, 64>&
          , std::int64_t&, std::string const&)> cb
          , std::string salt = std::string());

store a mutable item. The `key` is the public key the blob is to be stored under. The optional `salt` argument is a string that is to be mixed in with the key when determining where in the DHT the value is to be stored. The callback function is called from within the libtorrent network thread once we've found where to store the blob, possibly with the current value stored under the key. The values passed to the callback functions are:

entry& value
  the current value stored under the key (may be empty). Also expected to be set to the value to be stored by the function.
std::array<char,64>& signature
  the signature authenticating the current value. This may be zeros if there is currently no value stored. The function is expected to fill in this buffer with the signature of the new value to store. To generate the signature, you may want to use the `sign_mutable_item` function.
std::int64_t& seq
  current sequence number. May be zero if there is no current value. The function is expected to set this to the new sequence number of the value that is to be stored. Sequence numbers must be monotonically increasing. Attempting to overwrite a value with a lower or equal sequence number will fail, even if the signature is correct.
std::string const& salt
  this is the salt that was used for this put call.

Since the callback function `cb` is called from within libtorrent, it is critical to not perform any blocking operations. Ideally not even locking a mutex. Pass any data required for this function along with the function object's context and make the function entirely self-contained. The only reason data blob's value is computed via a function instead of just passing in the new value is to avoid race conditions. If you want to update the value in the DHT, you must first retrieve it, then modify it, then write it back. The way the DHT works, it is natural to always do a lookup before storing and calling the callback in between is convenient.

[report issue]

### dht_get_peers() dht_announce()

    void dht_announce (sha1_hash const& info_hash, int port = 0, dht::announce_flags_t flags = {});
    void dht_get_peers (sha1_hash const& info_hash);

`dht_get_peers()` will issue a DHT get_peer request to the DHT for the specified info-hash. The response (the peers) will be posted back in a dht_get_peers_reply_alert.

`dht_announce()` will issue a DHT announce request to the DHT to the specified info-hash, advertising the specified port. If the port is left at its default, 0, the port will be implied by the DHT message's source port (which may improve connectivity through a NAT).

Both these functions are exposed for advanced custom use of the DHT. All torrents eligible to be announce to the DHT will be automatically, by libtorrent.

For possible flags, see announce_flags_t.

[report issue]

### dht_live_nodes()

    void dht_live_nodes (sha1_hash const& nid);

Retrieve all the live DHT (identified by `nid`) nodes. All the nodes id and endpoint will be returned in the list of nodes in the alert `dht_live_nodes_alert`. Since this alert is a response to an explicit call, it will always be posted, regardless of the alert mask.

[report issue]

### dht_sample_infohashes()

    void dht_sample_infohashes (udp::endpoint const& ep, sha1_hash const& target);

Query the DHT node specified by `ep` to retrieve a sample of the info-hashes that the node currently have in their storage. The `target` is included for iterative lookups so that indexing nodes can perform a key space traversal with a single RPC per node by adjusting the target value for each RPC. It has no effect on the returned sample value. The result is posted as a `dht_sample_infohashes_alert`.

[report issue]

### dht_direct_request()

    void dht_direct_request (udp::endpoint const& ep, entry const& e, void* userdata = nullptr);

Send an arbitrary DHT request directly to the specified endpoint. This function is intended for use by plugins. When a response is received or the request times out, a dht_direct_response_alert will be posted with the response (if any) and the userdata pointer passed in here. Since this alert is a response to an explicit call, it will always be posted, regardless of the alert mask.

[report issue]

### add_extension()

    void add_extension (std::function<std::shared_ptr<torrent_plugin>(
          torrent_handle const&, void*)> ext);
    void add_extension (std::shared_ptr<plugin> ext);

This function adds an extension to this session. The argument is a function object that is called with a `torrent_handle` and which should return a `std::shared_ptr<torrent_plugin>`. To write custom plugins, see libtorrent plugins. For the typical bittorrent client all of these extensions should be added. The main plugins implemented in libtorrent are:

uTorrent metadata
  Allows peers to download the metadata (.torrent files) from the swarm directly. Makes it possible to join a swarm with just a tracker and info-hash.

    #include <libtorrent/extensions/ut_metadata.hpp>
    ses.add_extension(&lt::create_ut_metadata_plugin);

uTorrent peer exchange
  Exchanges peers between clients.

    #include <libtorrent/extensions/ut_pex.hpp>
    ses.add_extension(&lt::create_ut_pex_plugin);

smart ban plugin
  A plugin that, with a small overhead, can ban peers that sends bad data with very high accuracy. Should eliminate most problems on poisoned torrents.

    #include <libtorrent/extensions/smart_ban.hpp>
    ses.add_extension(&lt::create_smart_ban_plugin);

[report issue]

### get_ip_filter() set_ip_filter()

    void set_ip_filter (ip_filter const& f);
    ip_filter get_ip_filter () const;

Sets a filter that will be used to reject and accept incoming as well as outgoing connections based on their originating ip address. The default filter will allow connections to any ip address. To build a set of rules for which addresses are accepted and not, see ip_filter.

Each time a peer is blocked because of the IP filter, a peer_blocked_alert is generated. `get_ip_filter()` Returns the ip_filter currently in the session. See ip_filter.

[report issue]

### set_port_filter()

    void set_port_filter (port_filter const& f);

apply port_filter `f` to incoming and outgoing peers. a port filter will reject making outgoing peer connections to certain remote ports. The main intention is to be able to avoid triggering certain anti-virus software by connecting to SMTP, FTP ports.

[report issue]

### listen_port() ssl_listen_port() is_listening()

    unsigned short listen_port () const;
    bool is_listening () const;
    unsigned short ssl_listen_port () const;

`is_listening()` will tell you whether or not the session has successfully opened a listening port. If it hasn't, this function will return false, and then you can set a new settings_pack::listen_interfaces to try another interface and port to bind to.

`listen_port()` returns the port we ended up listening on.

[report issue]

### get_peer_class_filter() set_peer_class_filter()

    ip_filter get_peer_class_filter () const;
    void set_peer_class_filter (ip_filter const& f);

Sets the peer class filter for this session. All new peer connections will take this into account and be added to the peer classes specified by this filter, based on the peer's IP address.

The ip-filter essentially maps an IP -> uint32. Each bit in that 32 bit integer represents a peer class. The least significant bit represents class 0, the next bit class 1 and so on.

For more info, see ip_filter.

For example, to make all peers in the range 200.1.1.0 - 200.1.255.255 belong to their own peer class, apply the following filter:

    ip_filter f = ses.get_peer_class_filter();
    peer_class_t my_class = ses.create_peer_class("200.1.x.x IP range");
    f.add_rule(make_address("200.1.1.0"), make_address("200.1.255.255")
            , 1 << static_cast<std::uint32_t>(my_class));
    ses.set_peer_class_filter(f);

This setting only applies to new connections, it won't affect existing peer connections.

This function is limited to only peer class 0-31, since there are only 32 bits in the IP range mapping. Only the set bits matter; no peer class will be removed from a peer as a result of this call, peer classes are only added.

The `peer_class` argument cannot be greater than 31. The bitmasks representing peer classes in the `peer_class_filter` are 32 bits.

The `get_peer_class_filter()` function returns the current filter.

For more information, see peer classes.

[report issue]

### get_peer_class_type_filter() set_peer_class_type_filter()

    void set_peer_class_type_filter (peer_class_type_filter const& f);
    peer_class_type_filter get_peer_class_type_filter () const;

Sets and gets the peer class type filter. This is controls automatic peer class assignments to peers based on what kind of socket it is.

It does not only support assigning peer classes, it also supports removing peer classes based on socket type.

The order of these rules being applied are:

1. peer-class IP filter
2. peer-class type filter, removing classes
3. peer-class type filter, adding classes

For more information, see peer classes.

[report issue]

### create_peer_class()

    peer_class_t create_peer_class (char const* name);

Creates a new peer class (see peer classes) with the given name. The returned integer is the new peer class identifier. Peer classes may have the same name, so each invocation of this function creates a new class and returns a unique identifier.

Identifiers are assigned from low numbers to higher. So if you plan on using certain peer classes in a call to set_peer_class_filter(), make sure to create those early on, to get low identifiers.

For more information on peer classes, see peer classes.

[report issue]

### delete_peer_class()

    void delete_peer_class (peer_class_t cid);

This call dereferences the reference count of the specified peer class. When creating a peer class it's automatically referenced by 1. If you want to recycle a peer class, you may call this function. You may only call this function once per peer class you create. Calling it more than once for the same class will lead to memory corruption.

Since peer classes are reference counted, this function will not remove the peer class if it's still assigned to torrents or peers. It will however remove it once the last peer and torrent drops their references to it.

There is no need to call this function for custom peer classes. All peer classes will be properly destructed when the session object destructs.

For more information on peer classes, see peer classes.

[report issue]

### set_peer_class() get_peer_class()

    void set_peer_class (peer_class_t cid, peer_class_info const& pci);
    peer_class_info get_peer_class (peer_class_t cid) const;

These functions queries information from a peer class and updates the configuration of a peer class, respectively.

`cid` must refer to an existing peer class. If it does not, the return value of `get_peer_class()` is undefined.

`set_peer_class()` sets all the information in the peer_class_info object in the specified peer class. There is no option to only update a single property.

A peer or torrent belonging to more than one class, the highest priority among any of its classes is the one that is taken into account.

For more information, see peer classes.

[report issue]

### remove_torrent()

    void remove_torrent (const torrent_handle& h, remove_flags_t options = {});

`remove_torrent()` will close all peer connections associated with the torrent and tell the tracker that we've stopped participating in the swarm. This operation cannot fail. When it completes, you will receive a torrent_removed_alert.

The optional second argument `options` can be used to delete all the files downloaded by this torrent. To do so, pass in the value `session_handle::delete_files`. The removal of the torrent is asynchronous, there is no guarantee that adding the same torrent immediately after it was removed will not throw a system_error exception. Once the torrent is deleted, a torrent_deleted_alert is posted.

Note that when a queued or downloading torrent is removed, its position in the download queue is vacated and every subsequent torrent in the queue has their queue positions updated. This can potentially cause a large state_update to be posted. When removing all torrents, it is advised to remove them from the back of the queue, to minimize the shifting.

[report issue]

### get_settings() apply_settings()

    void apply_settings (settings_pack const& s);
    settings_pack get_settings () const;
    void apply_settings (settings_pack&& s);

Applies the settings specified by the settings_pack `s`. This is an asynchronous operation that will return immediately and actually apply the settings to the main thread of libtorrent some time later.

[report issue]

### wait_for_alert() set_alert_notify() pop_alerts()

    void pop_alerts (std::vector<alert*>* alerts);
    alert* wait_for_alert (time_duration max_wait);
    void set_alert_notify (std::function<void()> const& fun);

Alerts is the main mechanism for libtorrent to report errors and events. `pop_alerts` fills in the vector passed to it with pointers to new alerts. The session still owns these alerts and they will stay valid until the next time `pop_alerts` is called. You may not delete the alert objects.

It is safe to call `pop_alerts` from multiple different threads, as long as the alerts themselves are not accessed once another thread calls `pop_alerts`. Doing this requires manual synchronization between the popping threads.

`wait_for_alert` will block the current thread for `max_wait` time duration, or until another alert is posted. If an alert is available at the time of the call, it returns immediately. The returned alert pointer is the head of the alert queue. `wait_for_alert` does not pop alerts from the queue, it merely peeks at it. The returned alert will stay valid until `pop_alerts` is called twice. The first time will pop it and the second will free it.

If there is no alert in the queue and no alert arrives within the specified timeout, `wait_for_alert` returns nullptr.

In the python binding, `wait_for_alert` takes the number of milliseconds to wait as an integer.

The alert queue in the session will not grow indefinitely. Make sure to pop periodically to not miss notifications. To control the max number of alerts that's queued by the session, see `settings_pack::alert_queue_size`.

Some alerts are considered so important that they are posted even when the alert queue is full. Some alerts are considered mandatory and cannot be disabled by the `alert_mask`. For instance, save_resume_data_alert and save_resume_data_failed_alert are always posted, regardless of the alert mask.

To control which alerts are posted, set the alert_mask (settings_pack::alert_mask).

If the alert queue fills up to the point where alerts are dropped, this will be indicated by a alerts_dropped_alert, which contains a bitmask of which types of alerts were dropped. Generally it is a good idea to make sure the alert queue is large enough, the alert_mask doesn't have unnecessary categories enabled and to call pop_alert() frequently, to avoid alerts being dropped.

the `set_alert_notify` function lets the client set a function object to be invoked every time the alert queue goes from having 0 alerts to 1 alert. This function is called from within libtorrent, it may be the main thread, or it may be from within a user call. The intention of of the function is that the client wakes up its main thread, to poll for more alerts using `pop_alerts()`. If the notify function fails to do so, it won't be called again, until `pop_alerts` is called for some other reason. For instance, it could signal an eventfd, post a message to an HWND or some other main message pump. The actual retrieval of alerts should not be done in the callback. In fact, the callback should not block. It should not perform any expensive work. It really should just notify the main application thread.

The type of an alert is returned by the polymorphic function `alert::type()` but can also be queries from a concrete type via `T::alert_type`, as a static constant.

[report issue]

### add_port_mapping() delete_port_mapping()

    void delete_port_mapping (port_mapping_t handle);
    std::vector<port_mapping_t> add_port_mapping (portmap_protocol t, int external_port, int local_port);

add_port_mapping adds one or more port forwards on UPnP and/or NAT-PMP, whichever is enabled. A mapping is created for each listen socket in the session. The return values are all handles referring to the port mappings that were just created. Pass them to delete_port_mapping() to remove them.

[report issue]

### reopen_network_sockets()

    void reopen_network_sockets (reopen_network_flags_t options = reopen_map_ports);

Instructs the session to reopen all listen and outgoing sockets.

It's useful in the case your platform doesn't support the built in IP notifier mechanism, or if you have a better more reliable way to detect changes in the IP routing table.

[report issue]

### native_handle()

    std::shared_ptr<aux::session_impl> native_handle () const;

This function is intended only for use by plugins. This type does not have a stable API and should be relied on as little as possible.

[report issue]

save_settings
  saves settings (i.e. the settings_pack)

[report issue]

save_dht_settings
  saves dht_settings

[report issue]

save_dht_state
  saves dht state such as nodes and node-id, possibly accelerating joining the DHT if provided at next session startup.

[report issue]

global_peer_class_id tcp_peer_class_id local_peer_class_id
  built-in peer classes

[report issue]

delete_files
  delete the files belonging to the torrent from disk. including the part-file, if there is one

[report issue]

delete_partfile
  delete just the part-file associated with this torrent

[report issue]

add_default_plugins
  this will add common extensions like ut_pex, ut_metadata, lt_tex smart_ban and possibly others.

[report issue]

udp tcp
  protocols used by add_port_mapping()

[report issue]

reopen_map_ports
  This option indicates if the ports are mapped using natpmp and upnp. If mapping was already made, they are deleted and added again. This only works if natpmp and/or upnp are configured to be enable.

[report issue]

## session_proxy

Declared in "libtorrent/session.hpp"

this is a holder for the internal session implementation object. Once the session destruction is explicitly initiated, this holder is used to synchronize the completion of the shutdown. The lifetime of this object may outlive session, causing the session destructor to not block. The session_proxy destructor will block however, until the underlying session is done shutting down.

    class session_proxy
    {
       session_proxy (session_proxy const&);
       session_proxy& operator= (session_proxy const&);
       ~session_proxy ();
       session_proxy& operator= (session_proxy&&) noexcept;
       session_proxy ();
       session_proxy (session_proxy&&) noexcept;
    };

[report issue]

### ~session_proxy() session_proxy() operator=()

    session_proxy (session_proxy const&);
    session_proxy& operator= (session_proxy const&);
    ~session_proxy ();
    session_proxy& operator= (session_proxy&&) noexcept;
    session_proxy ();
    session_proxy (session_proxy&&) noexcept;

default constructor, does not refer to any session implementation object.

[report issue]

## session_params

Declared in "libtorrent/session.hpp"

The session_params is a parameters pack for configuring the session before it's started.

    struct session_params
    {
       explicit session_params (settings_pack&& sp);
       session_params ();
       explicit session_params (settings_pack const& sp);
       session_params (settings_pack const& sp
          , std::vector<std::shared_ptr<plugin>> exts);
       session_params (settings_pack&& sp
          , std::vector<std::shared_ptr<plugin>> exts);

       settings_pack settings;
       std::vector<std::shared_ptr<plugin>> extensions;
       dht::dht_settings dht_settings;
       dht::dht_state dht_state;
       dht::dht_storage_constructor_type dht_storage_constructor;
    };

[report issue]

### session_params()

    explicit session_params (settings_pack&& sp);
    session_params ();
    explicit session_params (settings_pack const& sp);

This constructor can be used to start with the default plugins (ut_metadata, ut_pex and smart_ban). The default values in the settings is to start the default features like upnp, NAT-PMP, and dht for example.

[report issue]

### session_params()

    session_params (settings_pack const& sp
          , std::vector<std::shared_ptr<plugin>> exts);
    session_params (settings_pack&& sp
          , std::vector<std::shared_ptr<plugin>> exts);

This constructor helps to configure the set of initial plugins to be added to the session before it's started.

[report issue]

## session

Declared in "libtorrent/session.hpp"

The session holds all state that spans multiple torrents. Among other things it runs the network loop and manages all torrents. Once it's created, the session object will spawn the main thread that will do all the work. The main thread will be idle as long it doesn't have any torrents to participate in.

You have some control over session configuration through the `session_handle::apply_settings()` member function. To change one or more configuration options, create a settings_pack. object and fill it with the settings to be set and pass it in to `session::apply_settings()`.

see apply_settings().

    class session : public session_handle
    {
       explicit session (session_params&& params);
       session ();
       explicit session (session_params const& params);
       session (session_params const& params, io_service& ios);
       session (session_params&& params, io_service& ios);
       session (settings_pack&& pack
          , session_flags_t const flags = add_default_plugins);
       session (settings_pack const& pack
          , session_flags_t const flags = add_default_plugins);
       session& operator= (session&&) = default;
       session (session&&) = default;
       session& operator= (session const&) = delete;
       session (session const&) = delete;
       session (settings_pack&& pack
          , io_service& ios
          , session_flags_t const flags = add_default_plugins);
       session (settings_pack const& pack
          , io_service& ios
          , session_flags_t const flags = add_default_plugins);
       ~session ();
       session_proxy abort ();
    };

[report issue]

### session()

    explicit session (session_params&& params);
    session ();
    explicit session (session_params const& params);

Constructs the session objects which acts as the container of torrents. In order to avoid a race condition between starting the session and configuring it, you can pass in a session_params object. Its settings will take effect before the session starts up.

[report issue]

### session()

    session (session_params const& params, io_service& ios);
    session (session_params&& params, io_service& ios);

Overload of the constructor that takes an external io_service to run the session object on. This is primarily useful for tests that may want to run multiple sessions on a single io_service, or low resource systems where additional threads are expensive and sharing an io_service with other events is fine.

Warning

The session object does not cleanly terminate with an external `io_service`. The `io_service::run()` call _must_ have returned before it's safe to destruct the session. Which means you MUST call session::abort() and save the session_proxy first, then destruct the session object, then sync with the io_service, then destruct the session_proxy object.

[report issue]

### session()

    session (settings_pack&& pack
          , session_flags_t const flags = add_default_plugins);
    session (settings_pack const& pack
          , session_flags_t const flags = add_default_plugins);

Constructs the session objects which acts as the container of torrents. It provides configuration options across torrents (such as rate limits, disk cache, ip filter etc.). In order to avoid a race condition between starting the session and configuring it, you can pass in a settings_pack object. Its settings will take effect before the session starts up.

The `flags` parameter can be used to start default features (UPnP & NAT-PMP) and default plugins (ut_metadata, ut_pex and smart_ban). The default is to start those features. If you do not want them to start, pass 0 as the flags parameter.

[report issue]

### session() operator=()

    session& operator= (session&&) = default;
    session (session&&) = default;

movable

[report issue]

### session() operator=()

    session& operator= (session const&) = delete;
    session (session const&) = delete;

non-copyable

[report issue]

### session()

    session (settings_pack&& pack
          , io_service& ios
          , session_flags_t const flags = add_default_plugins);
    session (settings_pack const& pack
          , io_service& ios
          , session_flags_t const flags = add_default_plugins);

overload of the constructor that takes an external io_service to run the session object on. This is primarily useful for tests that may want to run multiple sessions on a single io_service, or low resource systems where additional threads are expensive and sharing an io_service with other events is fine.

Warning

The session object does not cleanly terminate with an external `io_service`. The `io_service::run()` call _must_ have returned before it's safe to destruct the session. Which means you MUST call session::abort() and save the session_proxy first, then destruct the session object, then sync with the io_service, then destruct the session_proxy object.

[report issue]

### ~session()

    ~session ();

The destructor of session will notify all trackers that our torrents have been shut down. If some trackers are down, they will time out. All this before the destructor of session returns. So, it's advised that any kind of interface (such as windows) are closed before destructing the session object. Because it can take a few second for it to finish. The timeout can be set with apply_settings().

[report issue]

### abort()

    session_proxy abort ();

In case you want to destruct the session asynchronously, you can request a session destruction proxy. If you don't do this, the destructor of the session object will block while the trackers are contacted. If you keep one `session_proxy` to the session when destructing it, the destructor will not block, but start to close down the session, the destructor of the proxy will then synchronize the threads. So, the destruction of the session is performed from the `session` destructor call until the `session_proxy` destructor call. The `session_proxy` does not have any operations on it (since the session is being closed down, no operations are allowed on it). The only valid operation is calling the destructor:

    class session_proxy
    {
    public:
            session_proxy();
            ~session_proxy()
    };

[report issue]

## session_stats_metrics()

Declared in "libtorrent/session_stats.hpp"

    std::vector<stats_metric> session_stats_metrics ();

This free function returns the list of available metrics exposed by libtorrent's statistics API. Each metric has a name and a value index. The value index is the index into the array in session_stats_alert where this metric's value can be found when the session stats is sampled (by calling post_session_stats()).

[report issue]

## find_metric_idx()

Declared in "libtorrent/session_stats.hpp"

    int find_metric_idx (string_view name);

given a name of a metric, this function returns the counter index of it, or -1 if it could not be found. The counter index is the index into the values array returned by session_stats_alert.

[report issue]

## read_session_params()

Declared in "libtorrent/session.hpp"

    session_params read_session_params (bdecode_node const& e
       , save_state_flags_t flags = save_state_flags_t::all());

This function helps to construct a `session_params` from a bencoded data generated by `session_handle::save_state`

[report issue]

## enum metric_type_t

Declared in "libtorrent/session_stats.hpp"

name | value | description
--- | --- | ---
counter | 0 |
gauge | 1 |