File indexing completed on 2025-01-05 04:37:21

0001 /*
0002     SPDX-FileCopyrightText: 2012 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #ifndef BT_CONNECTIONLIMIT_H
0008 #define BT_CONNECTIONLIMIT_H
0009 
0010 #include <QMap>
0011 #include <QSharedPointer>
0012 #include <ktorrent_export.h>
0013 #include <util/constants.h>
0014 #include <util/sha1hash.h>
0015 
0016 namespace bt
0017 {
0018 /**
0019  * Maintains the connection limit. It uses a Token for that.
0020  */
0021 class KTORRENT_EXPORT ConnectionLimit
0022 {
0023 public:
0024     ConnectionLimit();
0025     virtual ~ConnectionLimit();
0026 
0027     /// Get the total number of connections currently in use
0028     bt::Uint32 totalConnections() const
0029     {
0030         return global_total;
0031     }
0032 
0033     /**
0034      * Set the connection limits
0035      * @param global_limit Global limit
0036      * @param torrent_limit Per torrent limit
0037      **/
0038     void setLimits(bt::Uint32 global_limit, bt::Uint32 torrent_limit);
0039 
0040     /**
0041      * Token representing the allowance to open a connection.
0042      * When the token is destroyed, it will be automatically released.
0043      */
0044     class Token
0045     {
0046     public:
0047         Token(ConnectionLimit &limit, const bt::SHA1Hash &hash);
0048         ~Token();
0049 
0050         /// Get the info hash
0051         const bt::SHA1Hash &infoHash() const
0052         {
0053             return hash;
0054         }
0055 
0056         typedef QSharedPointer<Token> Ptr;
0057 
0058     private:
0059         ConnectionLimit &limit;
0060         bt::SHA1Hash hash;
0061     };
0062 
0063     /**
0064      * Request a token for a given torrent
0065      * @param hash Info hash of the torrent
0066      * @return ConnectionLimit::Token::Ptr a valid token if a connection can be opened, a 0 pointer if not
0067      **/
0068     Token::Ptr acquire(const SHA1Hash &hash);
0069 
0070 protected:
0071     /**
0072      * Release one Token. Will be done by destructor of Token.
0073      * @param token The Token
0074      **/
0075     void release(const Token &token);
0076 
0077 private:
0078     bt::Uint32 global_limit;
0079     bt::Uint32 global_total;
0080     bt::Uint32 torrent_limit;
0081     QMap<SHA1Hash, bt::Uint32> torrent_totals;
0082 };
0083 
0084 }
0085 
0086 #endif // BT_CONNECTIONLIMIT_H