File indexing completed on 2024-06-02 05:05:27

0001 /*
0002     SPDX-FileCopyrightText: 2005 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 #ifndef BTPACKETREADER_H
0007 #define BTPACKETREADER_H
0008 
0009 #include <QList>
0010 #include <QMutex>
0011 #include <deque>
0012 #include <ktorrent_export.h>
0013 #include <net/trafficshapedsocket.h>
0014 
0015 namespace bt
0016 {
0017 class PeerInterface;
0018 
0019 struct IncomingPacket {
0020     QScopedArrayPointer<Uint8> data;
0021     Uint32 size;
0022     Uint32 read;
0023 
0024     IncomingPacket(Uint32 size);
0025 
0026     typedef QSharedPointer<IncomingPacket> Ptr;
0027 };
0028 
0029 /**
0030  * Chops up the raw byte stream from a socket into bittorrent packets
0031  * @author Joris Guisson
0032  */
0033 class KTORRENT_EXPORT PacketReader : public net::SocketReader
0034 {
0035 public:
0036     PacketReader(Uint32 max_packet_size);
0037     ~PacketReader() override;
0038 
0039     /**
0040      * Push packets to Peer (runs in main thread)
0041      * @param peer The PeerInterface which will handle the packet
0042      */
0043     void update(PeerInterface &peer);
0044 
0045     /// Did an error occur
0046     bool ok() const
0047     {
0048         return !error;
0049     }
0050 
0051     void onDataReady(Uint8 *buf, Uint32 size) override;
0052 
0053 private:
0054     Uint32 newPacket(Uint8 *buf, Uint32 size);
0055     Uint32 readPacket(Uint8 *buf, Uint32 size);
0056     IncomingPacket::Ptr dequeuePacket();
0057 
0058 private:
0059     bool error;
0060 #ifndef DO_NOT_USE_DEQUE
0061     std::deque<IncomingPacket::Ptr> packet_queue;
0062 #else
0063     QList<IncomingPacket::Ptr> packet_queue;
0064 #endif
0065     QMutex mutex;
0066     Uint8 len[4];
0067     int len_received;
0068     Uint32 max_packet_size;
0069 };
0070 
0071 }
0072 
0073 #endif