-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
93 lines (82 loc) · 2.49 KB
/
Copy pathmain.cpp
File metadata and controls
93 lines (82 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include "bencode.hpp"
#include "bencodeParser.hpp"
#include "torrent.hpp"
#include "tracker.hpp"
#include "peer.hpp"
#include "pieceManager.hpp"
#include "fileWriter.hpp"
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
return 1;
}
std::string filename = argv[1];
std::ifstream file(filename, std::ios::binary);
if (!file)
{
std::cerr << "Error opening file: " << filename << std::endl;
return 1;
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
file.close();
torrent::TorrentMeta torrentFile = parseTorrentMeta(content);
std::vector<Peer> peers = getPeers(torrentFile);
if (peers.empty())
{
std::cerr << "No peers found." << std::endl;
return 1;
}
else
{
std::cout << peers.size() << " peer(s) found!" << std::endl;
}
// for (const auto &peer : peers)
// {
// std::cout << "Peer IP: " << peer.ip << ", Port: " << peer.port << std::endl;
// }
std::vector<PeerConnection> activePeers;
for (const auto &peer : peers)
{
std::cout << "Trying " << peer.ip << ":" << peer.port << std::endl;
auto sockOpt = connectAndHandshake(peer, torrentFile.infoHashRaw);
if (sockOpt.has_value())
{
std::cout << "\033[32mConnected and handshake successful with \033[0m" << peer.ip << std::endl;
PeerConnection pc;
pc.peer = peer;
pc.sockfd = sockOpt.value();
activePeers.push_back(std::move(pc));
}
else
{
std::cerr << "Failed to connect/handshake with " << peer.ip << std::endl;
}
}
if (activePeers.empty())
{
std::cerr << "No active peers after connection attempts." << std::endl;
return 1;
}
std::cout << activePeers.size() << " active peer(s) after connection attempts." << std::endl;
PeerConnection &pc = activePeers[0]; // For simplicity, we use the first active peer
if (!downloadFullFile(pc, torrentFile))
{
std::cerr << "Failed to download the file." << std::endl;
return 1;
}
std::cout << "File downloaded successfully!" << std::endl;
for (const auto &peer : activePeers)
{
close(peer.sockfd);
}
std::cout << "All connections closed." << std::endl;
return 0;
}