Skip to content

Commit be694c8

Browse files
committed
Format with clang-format-22
1 parent 8adc129 commit be694c8

File tree

4 files changed

+71
-53
lines changed

4 files changed

+71
-53
lines changed

CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX "#")
126126
list(FILTER ALL_HEADER_FILES EXCLUDE REGEX "#")
127127
set(ALL_INPUT_FILES ${ALL_SOURCE_FILES} ${ALL_HEADER_FILES})
128128

129-
find_program(CLANG_FORMAT NAMES clang-format-14 clang-format-17)
129+
find_program(CLANG_FORMAT NAMES clang-format-22)
130130
if(CLANG_FORMAT)
131131
add_custom_target(format
132132
COMMENT "Formatting ${ALL_INPUT_FILES}"

src/main.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
#include "logger.hpp"
55
#include "torrent.hpp"
66

7-
#include <asio/io_context.hpp>
87
#include <fmt/format.h>
98
#include <spdlog/common.h>
9+
#include <asio/io_context.hpp>
1010

1111
#include <algorithm>
1212
#include <cstdlib>
@@ -81,7 +81,9 @@ int main(int argc, const char* argv[]) noexcept {
8181
.help("Log level (trace, debug, info, warning, error, critical, off)");
8282
parser.add_option<std::string>("--log-prefix")
8383
.default_value("")
84-
.help("Prefix to add to all log messages (useful when running multiple instances)");
84+
.help(
85+
"Prefix to add to all log messages (useful when running multiple "
86+
"instances)");
8587
parser.add_option<bool>("--dump-torrent")
8688
.help("Dump info about specified .torrent file and exit");
8789
parser.add_option<bool>("--dump-config").help("Dump config to console");
@@ -104,7 +106,8 @@ int main(int argc, const char* argv[]) noexcept {
104106
// Set pattern with prefix for all loggers
105107
// Default spdlog pattern is: [%Y-%m-%d %H:%M:%S.%e] [%n] [%^%l%$] %v
106108
// We'll add the prefix before the message
107-
const auto pattern = "[%Y-%m-%d %H:%M:%S.%e] [%n] [%^%l%$] [" + log_prefix + "] %v";
109+
const auto pattern =
110+
"[%Y-%m-%d %H:%M:%S.%e] [%n] [%^%l%$] [" + log_prefix + "] %v";
108111
zit::logger()->set_pattern(pattern);
109112
zit::logger("file_writer")->set_pattern(pattern);
110113
}

src/messages.cpp

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <cassert>
77
#include <cstddef>
88
#include <cstdint>
9+
#include <cstdlib>
910
#include <cstring>
1011
#include <iomanip>
1112
#include <ios>
@@ -145,9 +146,19 @@ optional<HandshakeMsg> HandshakeMsg::parse(const bytes& msg) {
145146
}
146147

147148
if (sr.begin() != msg.begin()) {
148-
logger()->debug("Found BT start at {}",
149-
std::distance(msg.begin(), sr.begin()));
150-
return HandshakeMsg::parse(bytes{sr.begin(), msg.end()});
149+
const auto pos = std::distance(msg.begin(), sr.begin());
150+
logger()->debug("Found BT start at {}", pos);
151+
// Parse from the actual handshake start, but make sure the consumed
152+
// length accounts for any leading garbage before the handshake.
153+
auto parsed = HandshakeMsg::parse(bytes{sr.begin(), msg.end()});
154+
if (!parsed) {
155+
return {};
156+
}
157+
// Repackage with adjusted consumed to include the offset
158+
return HandshakeMsg(parsed->getReserved(), parsed->getInfoHash(),
159+
parsed->getPeerId(),
160+
parsed->getConsumed() + numeric_cast<size_t>(pos),
161+
parsed->getBitfield());
151162
}
152163

153164
const bytes reserved(&msg.at(20), &msg.at(28));
@@ -156,26 +167,31 @@ optional<HandshakeMsg> HandshakeMsg::parse(const bytes& msg) {
156167

157168
// Handle optional bitfield
158169
if (msg.size() > MIN_BT_MSG_LENGTH) {
159-
if (msg.size() < 73) {
160-
logger()->error("Invalid handshake length: {}", msg.size());
161-
return {};
170+
// If we don't yet have enough bytes to decide on BITFIELD, or if the
171+
// next message isn't a BITFIELD, just consume the handshake (68 bytes)
172+
// and let the caller parse subsequent messages normally.
173+
bool strict_handshake = false;
174+
if (const char* env_p = std::getenv("ZIT_STRICT_HANDSHAKE")) {
175+
strict_handshake = std::string(env_p) == "1";
162176
}
163-
if (to_peer_wire_id(msg.at(72)) != peer_wire_id::BITFIELD) {
164-
logger()->error("Expected bitfield id ({}) but got: {}",
165-
static_cast<pwid_t>(peer_wire_id::BITFIELD),
166-
static_cast<uint8_t>(msg.at(72)));
167-
return {};
177+
178+
if (msg.size() < 73 || (!strict_handshake && to_peer_wire_id(msg.at(72)) !=
179+
peer_wire_id::BITFIELD)) {
180+
logger()->debug(
181+
"Handshake without immediate BITFIELD; consuming 68 bytes");
182+
return make_optional<HandshakeMsg>(reserved, info_hash, peer_id,
183+
MIN_BT_MSG_LENGTH);
168184
}
169-
// 4-byte big endian
185+
// 4-byte big endian length for BITFIELD payload
170186
auto len = from_big_endian<uint32_t>(msg, 68);
171187
auto end = 73 + len - 1;
172188
if (end > msg.size()) {
173-
logger()->debug("Wait for more handshake data...");
189+
logger()->debug("Wait for more handshake+BITFIELD data...");
174190
return make_optional<HandshakeMsg>(reserved, info_hash, peer_id, 0);
175191
}
176192
Bitfield bf(bytes(std::next(msg.begin(), 73), std::next(msg.begin(), end)));
177193
logger()->debug("Handshake: {}", bf);
178-
// Consume the parsed part, the caller have to deal with the rest
194+
// Consume the parsed part, the caller has to deal with the rest
179195
return make_optional<HandshakeMsg>(reserved, info_hash, peer_id, end, bf);
180196
}
181197

src/peer.cpp

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ void PeerConnection::write(const optional<Url>& url, const std::string& msg) {
126126
}
127127
auto self = shared_from_this();
128128
resolver_.async_resolve(
129-
url->host(), url->service(),
130-
[self](auto&& ec, auto&& it) { self->handle_resolve(ec, it); });
129+
url->host(), url->service(),
130+
[self](auto&& ec, auto&& it) { self->handle_resolve(ec, it); });
131131
}
132132
}
133133

@@ -170,30 +170,30 @@ void PeerConnection::send(bool start_read) {
170170

171171
// NOLINTNEXTLINE(misc-include-cleaner)
172172
auto self = shared_from_this();
173-
asio::async_write(
174-
*socket_, asio::buffer(m_msg.c_str(), m_msg.size()),
175-
[self, start_read](auto err, auto len) {
176-
if (self->m_stopped) {
177-
return;
178-
}
179-
if (!err) {
180-
logger()->debug("{}: Data of len {} sent", self->peer_.str(), len);
181-
} else {
182-
logger()->error("{}: Write failed: {}", self->peer_.str(),
183-
err.message());
184-
}
185-
if (start_read) {
186-
self->handle_response({}, 0);
187-
}
188-
if (!self->m_send_queue.empty()) {
189-
self->m_msg = self->m_send_queue.front();
190-
self->m_send_queue.pop_front();
191-
self->send();
192-
} else {
193-
// Indicates that all sending is done
194-
self->m_msg.clear();
195-
}
196-
});
173+
asio::async_write(*socket_, asio::buffer(m_msg.c_str(), m_msg.size()),
174+
[self, start_read](auto err, auto len) {
175+
if (self->m_stopped) {
176+
return;
177+
}
178+
if (!err) {
179+
logger()->debug("{}: Data of len {} sent",
180+
self->peer_.str(), len);
181+
} else {
182+
logger()->error("{}: Write failed: {}",
183+
self->peer_.str(), err.message());
184+
}
185+
if (start_read) {
186+
self->handle_response({}, 0);
187+
}
188+
if (!self->m_send_queue.empty()) {
189+
self->m_msg = self->m_send_queue.front();
190+
self->m_send_queue.pop_front();
191+
self->send();
192+
} else {
193+
// Indicates that all sending is done
194+
self->m_msg.clear();
195+
}
196+
});
197197
}
198198

199199
void PeerConnection::handle_connect(const asio::error_code& err,
@@ -260,14 +260,13 @@ void PeerConnection::handle_response(const asio::error_code& err, std::size_t) {
260260
// bytes at a time
261261
// NOLINTNEXTLINE(misc-include-cleaner)
262262
auto self = shared_from_this();
263-
asio::async_read(
264-
*socket_, response_, asio::transfer_at_least(1),
265-
[self](const auto& ec, auto s) {
266-
if (self->m_stopped) {
267-
return;
268-
}
269-
self->handle_response(ec, s);
270-
});
263+
asio::async_read(*socket_, response_, asio::transfer_at_least(1),
264+
[self](const auto& ec, auto s) {
265+
if (self->m_stopped) {
266+
return;
267+
}
268+
self->handle_response(ec, s);
269+
});
271270
} else if (err != asio::error::eof) {
272271
logger()->error("Response failed: {}", err.message());
273272
} else {
@@ -686,7 +685,7 @@ void Peer::init_io_service(socket_ptr socket) {
686685
m_work = make_unique<asio::io_service::work>(*m_io_service);
687686
try {
688687
m_connection = std::make_shared<PeerConnection>(
689-
*this, *m_io_service, m_torrent.connection_port(), std::move(socket));
688+
*this, *m_io_service, m_torrent.connection_port(), std::move(socket));
690689
} catch (const asio::system_error& err) {
691690
throw_with_nested(
692691
runtime_error("Creating peer connection to " + str() + err.what()));

0 commit comments

Comments
 (0)