From deea6fc6a206701e7f724522b61739140d78bbff Mon Sep 17 00:00:00 2001 From: Mike Gelfand Date: Tue, 13 Jun 2017 05:24:09 +0300 Subject: [PATCH] Bring assertions closer to the beginning of blocks --- libtransmission/announcer-udp.c | 8 +- libtransmission/announcer.c | 51 +++---- libtransmission/bandwidth.c | 8 +- libtransmission/bitfield.c | 5 +- libtransmission/blocklist.c | 7 +- libtransmission/cache.c | 8 +- libtransmission/completion.c | 4 +- libtransmission/crypto-utils-cyassl.c | 20 +-- libtransmission/crypto-utils-fallback.c | 6 +- libtransmission/crypto-utils-openssl.c | 26 ++-- libtransmission/crypto-utils-polarssl.c | 20 +-- libtransmission/crypto-utils.c | 12 +- libtransmission/crypto.c | 4 +- libtransmission/error.c | 35 ++--- libtransmission/fdlimit.c | 11 +- libtransmission/file-posix.c | 164 +++++++++------------- libtransmission/file-win32.c | 177 ++++++++++-------------- libtransmission/file.c | 18 ++- libtransmission/handshake.c | 8 +- libtransmission/inout.c | 15 +- libtransmission/libtransmission-test.c | 4 +- libtransmission/magnet.c | 4 +- libtransmission/makemeta.c | 4 +- libtransmission/metainfo.c | 6 +- libtransmission/net.c | 14 +- libtransmission/peer-io.c | 69 +++++---- libtransmission/peer-mgr.c | 139 ++++++++----------- libtransmission/peer-msgs.c | 70 +++++----- libtransmission/platform.c | 1 + libtransmission/ptrarray.c | 7 +- libtransmission/quark.c | 7 +- libtransmission/rename-test.c | 6 +- libtransmission/resume.c | 8 +- libtransmission/rpcimpl.c | 73 +++++----- libtransmission/session.c | 112 +++++++-------- libtransmission/torrent-ctor.c | 12 +- libtransmission/torrent-magnet.c | 17 +-- libtransmission/torrent.c | 163 +++++++++++----------- libtransmission/tr-assert.h | 4 +- libtransmission/tr-dht.c | 7 +- libtransmission/tr-lpd.c | 24 ++-- libtransmission/tr-udp.c | 12 +- libtransmission/utils.c | 28 ++-- libtransmission/variant-json.c | 3 +- libtransmission/variant.c | 24 ++-- libtransmission/verify.c | 8 +- libtransmission/watchdir.c | 7 +- libtransmission/web.c | 2 + 48 files changed, 657 insertions(+), 785 deletions(-) diff --git a/libtransmission/announcer-udp.c b/libtransmission/announcer-udp.c index e41c76929..aebef22ac 100644 --- a/libtransmission/announcer-udp.c +++ b/libtransmission/announcer-udp.c @@ -536,15 +536,15 @@ static void tau_tracker_send_request(struct tau_tracker* tracker, void const* pa static void tau_tracker_send_reqs(struct tau_tracker* tracker) { - tr_ptrArray* reqs; - time_t const now = tr_time(); - TR_ASSERT(tracker->dns_request == NULL); TR_ASSERT(tracker->connecting_at == 0); TR_ASSERT(tracker->addr != NULL); + + time_t const now = tr_time(); + TR_ASSERT(tracker->connection_expiration_time > now); - reqs = &tracker->announces; + tr_ptrArray* reqs = &tracker->announces; for (int i = 0, n = tr_ptrArraySize(reqs); i < n; ++i) { diff --git a/libtransmission/announcer.c b/libtransmission/announcer.c index 193990767..599a07a10 100644 --- a/libtransmission/announcer.c +++ b/libtransmission/announcer.c @@ -162,11 +162,9 @@ static void onUpkeepTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* va void tr_announcerInit(tr_session* session) { - tr_announcer* a; - TR_ASSERT(tr_isSession(session)); - a = tr_new0(tr_announcer, 1); + tr_announcer* a = tr_new0(tr_announcer, 1); a->stops = TR_PTR_ARRAY_INIT; a->key = tr_rand_int(INT_MAX); a->session = session; @@ -716,11 +714,9 @@ static void addTorrentToTier(tr_torrent_tiers* tt, tr_torrent* tor) tr_torrent_tiers* tr_announcerAddTorrent(tr_torrent* tor, tr_tracker_callback callback, void* callbackData) { - tr_torrent_tiers* tiers; - TR_ASSERT(tr_isTorrent(tor)); - tiers = tiersNew(); + tr_torrent_tiers* tiers = tiersNew(); tiers->callback = callback; tiers->callbackData = callbackData; @@ -740,11 +736,11 @@ static bool tierCanManualAnnounce(tr_tier const* tier) bool tr_announcerCanManualAnnounce(tr_torrent const* tor) { - struct tr_torrent_tiers* tt = NULL; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tor->tiers != NULL); + struct tr_torrent_tiers* tt = NULL; + if (tor->isRunning) { tt = tor->tiers; @@ -912,11 +908,11 @@ void tr_announcerChangeMyPort(tr_torrent* tor) void tr_announcerAddBytes(tr_torrent* tor, int type, uint32_t byteCount) { - struct tr_torrent_tiers* tt = tor->tiers; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(type == TR_ANN_UP || type == TR_ANN_DOWN || type == TR_ANN_CORRUPT); + struct tr_torrent_tiers* tt = tor->tiers; + for (int i = 0; i < tt->tier_count; ++i) { tt->tiers[i].byteCounts[type] += byteCount; @@ -1270,19 +1266,16 @@ static void announce_request_delegate(tr_announcer* announcer, tr_announce_reque static void tierAnnounce(tr_announcer* announcer, tr_tier* tier) { - tr_announce_event announce_event; - tr_announce_request* req; - struct announce_data* data; - tr_torrent* tor = tier->tor; - time_t const now = tr_time(); - TR_ASSERT(!tier->isAnnouncing); TR_ASSERT(tier->announce_event_count > 0); - announce_event = tier_announce_event_pull(tier); - req = announce_request_new(announcer, tor, tier, announce_event); + time_t const now = tr_time(); - data = tr_new0(struct announce_data, 1); + tr_torrent* tor = tier->tor; + tr_announce_event announce_event = tier_announce_event_pull(tier); + tr_announce_request* req = announce_request_new(announcer, tor, tier, announce_event); + + struct announce_data* data = tr_new0(struct announce_data, 1); data->session = announcer->session; data->tierId = tier->key; data->isRunningOnSuccess = tor->isRunning; @@ -1659,14 +1652,13 @@ static void onUpkeepTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* va tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerCount) { - int out = 0; - tr_tracker_stat* ret; - struct tr_torrent_tiers* tt; - time_t const now = tr_time(); - TR_ASSERT(tr_isTorrent(torrent)); - tt = torrent->tiers; + time_t const now = tr_time(); + + int out = 0; + tr_tracker_stat* ret; + struct tr_torrent_tiers* tt = torrent->tiers; /* alloc the stats */ *setmeTrackerCount = tt->tracker_count; @@ -1783,12 +1775,12 @@ void tr_announcerStatsFree(tr_tracker_stat* trackers, int trackerCount UNUSED) static void copy_tier_attributes_impl(struct tr_tier* tgt, int trackerIndex, tr_tier const* src) { - tr_tier const keep = *tgt; - /* sanity clause */ TR_ASSERT(trackerIndex < tgt->tracker_count); TR_ASSERT(tr_strcmp0(tgt->trackers[trackerIndex].announce, src->currentTracker->announce) == 0); + tr_tier const keep = *tgt; + /* bitwise copy will handle most of tr_tier's fields... */ *tgt = *src; @@ -1826,12 +1818,13 @@ static void copy_tier_attributes(struct tr_torrent_tiers* tt, tr_tier const* src void tr_announcerResetTorrent(tr_announcer* announcer UNUSED, tr_torrent* tor) { + TR_ASSERT(tor->tiers != NULL); + time_t const now = tr_time(); + struct tr_torrent_tiers* tt = tor->tiers; tr_torrent_tiers old = *tt; - TR_ASSERT(tt != NULL); - /* remove the old tiers / trackers */ tt->tiers = NULL; tt->trackers = NULL; diff --git a/libtransmission/bandwidth.c b/libtransmission/bandwidth.c index 8e17d9607..ce797bb78 100644 --- a/libtransmission/bandwidth.c +++ b/libtransmission/bandwidth.c @@ -152,11 +152,11 @@ void tr_bandwidthSetParent(tr_bandwidth* b, tr_bandwidth* parent) static void allocateBandwidth(tr_bandwidth* b, tr_priority_t parent_priority, tr_direction dir, unsigned int period_msec, tr_ptrArray* peer_pool) { - tr_priority_t const priority = MAX(parent_priority, b->priority); - TR_ASSERT(tr_isBandwidth(b)); TR_ASSERT(tr_isDirection(dir)); + tr_priority_t const priority = MAX(parent_priority, b->priority); + /* set the available bandwidth */ if (b->band[dir].isLimited) { @@ -372,12 +372,10 @@ unsigned int tr_bandwidthGetPieceSpeed_Bps(tr_bandwidth const* b, uint64_t const void tr_bandwidthUsed(tr_bandwidth* b, tr_direction dir, size_t byteCount, bool isPieceData, uint64_t now) { - struct tr_band* band; - TR_ASSERT(tr_isBandwidth(b)); TR_ASSERT(tr_isDirection(dir)); - band = &b->band[dir]; + struct tr_band* band = &b->band[dir]; if (band->isLimited && isPieceData) { diff --git a/libtransmission/bitfield.c b/libtransmission/bitfield.c index 916cd641e..da9dae3dc 100644 --- a/libtransmission/bitfield.c +++ b/libtransmission/bitfield.c @@ -197,11 +197,11 @@ static void set_all_true(uint8_t* array, size_t bit_count) void* tr_bitfieldGetRaw(tr_bitfield const* b, size_t* byte_count) { + TR_ASSERT(b->bit_count > 0); + size_t const n = get_bytes_needed(b->bit_count); uint8_t* bits = tr_new0(uint8_t, n); - TR_ASSERT(b->bit_count > 0); - if (b->alloc_count != 0) { TR_ASSERT(b->alloc_count <= n); @@ -366,6 +366,7 @@ void tr_bitfieldSetRaw(tr_bitfield* b, void const* bits, size_t byte_count, bool { /* ensure the excess bits are set to '0' */ int const excess_bit_count = byte_count * 8 - b->bit_count; + TR_ASSERT(excess_bit_count >= 0); TR_ASSERT(excess_bit_count <= 7); diff --git a/libtransmission/blocklist.c b/libtransmission/blocklist.c index de0a35670..434c999db 100644 --- a/libtransmission/blocklist.c +++ b/libtransmission/blocklist.c @@ -190,11 +190,11 @@ void tr_blocklistFileSetEnabled(tr_blocklistFile* b, bool isEnabled) bool tr_blocklistFileHasAddress(tr_blocklistFile* b, tr_address const* addr) { + TR_ASSERT(tr_address_is_valid(addr)); + uint32_t needle; struct tr_ipv4_range const* range; - TR_ASSERT(tr_address_is_valid(addr)); - if (!b->isEnabled || addr->type == TR_AF_INET6) { return false; @@ -407,8 +407,7 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename) #ifdef TR_ENABLE_ASSERTS - /* sanity checks: make sure the rules are sorted - * in ascending order and don't overlap */ + /* sanity checks: make sure the rules are sorted in ascending order and don't overlap */ { for (size_t i = 0; i < ranges_count; ++i) { diff --git a/libtransmission/cache.c b/libtransmission/cache.c index 2a9649a3e..ab921637b 100644 --- a/libtransmission/cache.c +++ b/libtransmission/cache.c @@ -279,6 +279,7 @@ tr_cache* tr_cacheNew(int64_t max_bytes) void tr_cacheFree(tr_cache* cache) { TR_ASSERT(tr_ptrArrayEmpty(&cache->blocks)); + tr_ptrArrayDestruct(&cache->blocks, NULL); tr_free(cache); } @@ -319,10 +320,10 @@ static struct cache_block* findBlock(tr_cache* cache, tr_torrent* torrent, tr_pi int tr_cacheWriteBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t length, struct evbuffer* writeme) { - struct cache_block* cb = findBlock(cache, torrent, piece, offset); - TR_ASSERT(tr_amInEventThread(torrent->session)); + struct cache_block* cb = findBlock(cache, torrent, piece, offset); + if (cb == NULL) { cb = tr_new(struct cache_block, 1); @@ -335,9 +336,10 @@ int tr_cacheWriteBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t pi tr_ptrArrayInsertSorted(&cache->blocks, cb, cache_block_compare); } + TR_ASSERT(cb->length == length); + cb->time = tr_time(); - TR_ASSERT(cb->length == length); evbuffer_drain(cb->evbuf, evbuffer_get_length(cb->evbuf)); evbuffer_remove_buffer(writeme, cb->evbuf, cb->length); diff --git a/libtransmission/completion.c b/libtransmission/completion.c index 217fd3ca8..367cf1236 100644 --- a/libtransmission/completion.c +++ b/libtransmission/completion.c @@ -302,12 +302,12 @@ bool tr_cpFileIsComplete(tr_completion const* cp, tr_file_index_t i) void* tr_cpCreatePieceBitfield(tr_completion const* cp, size_t* byte_count) { + TR_ASSERT(tr_torrentHasMetadata(cp->tor)); + void* ret; tr_piece_index_t n; tr_bitfield pieces; - TR_ASSERT(tr_torrentHasMetadata(cp->tor)); - n = cp->tor->info.pieceCount; tr_bitfieldConstruct(&pieces, n); diff --git a/libtransmission/crypto-utils-cyassl.c b/libtransmission/crypto-utils-cyassl.c index 64386834e..b8d7c2d33 100644 --- a/libtransmission/crypto-utils-cyassl.c +++ b/libtransmission/crypto-utils-cyassl.c @@ -204,11 +204,11 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, size_t generator_num_length) { - struct tr_dh_ctx* handle = tr_new0(struct tr_dh_ctx, 1); - TR_ASSERT(prime_num != NULL); TR_ASSERT(generator_num != NULL); + struct tr_dh_ctx* handle = tr_new0(struct tr_dh_ctx, 1); + API(InitDhKey)(&handle->dh); if (!check_result(API(DhSetKey)(&handle->dh, prime_num, prime_num_length, generator_num, generator_num_length))) @@ -238,14 +238,14 @@ void tr_dh_free(tr_dh_ctx_t raw_handle) bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length UNUSED, uint8_t* public_key, size_t* public_key_length) { + TR_ASSERT(raw_handle != NULL); + TR_ASSERT(public_key != NULL); + struct tr_dh_ctx* handle = raw_handle; word32 my_private_key_length; word32 my_public_key_length; tr_lock* rng_lock = get_rng_lock(); - TR_ASSERT(handle != NULL); - TR_ASSERT(public_key != NULL); - if (handle->private_key == NULL) { handle->private_key = tr_malloc(handle->key_length); @@ -276,13 +276,13 @@ bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length UNUSED, ui tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t raw_handle, uint8_t const* other_public_key, size_t other_public_key_length) { + TR_ASSERT(raw_handle != NULL); + TR_ASSERT(other_public_key != NULL); + struct tr_dh_ctx* handle = raw_handle; struct tr_dh_secret* ret; word32 my_secret_key_length; - TR_ASSERT(handle != NULL); - TR_ASSERT(other_public_key != NULL); - ret = tr_dh_secret_new(handle->key_length); if (check_result(API(DhAgree)(&handle->dh, ret->key, &my_secret_key_length, handle->private_key, handle->private_key_length, @@ -305,11 +305,11 @@ tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t raw_handle, uint8_t const* other_public_k bool tr_rand_buffer(void* buffer, size_t length) { + TR_ASSERT(buffer != NULL); + bool ret; tr_lock* rng_lock = get_rng_lock(); - TR_ASSERT(buffer != NULL); - tr_lockLock(rng_lock); ret = check_result(API(RNG_GenerateBlock)(get_rng(), buffer, length)); tr_lockUnlock(rng_lock); diff --git a/libtransmission/crypto-utils-fallback.c b/libtransmission/crypto-utils-fallback.c index e430ce9c6..f9dc97cde 100644 --- a/libtransmission/crypto-utils-fallback.c +++ b/libtransmission/crypto-utils-fallback.c @@ -45,11 +45,11 @@ static void tr_dh_secret_align(struct tr_dh_secret* handle, size_t current_key_l bool tr_dh_secret_derive(tr_dh_secret_t raw_handle, void const* prepend_data, size_t prepend_data_size, void const* append_data, size_t append_data_size, uint8_t* hash) { - struct tr_dh_secret* handle = raw_handle; - - TR_ASSERT(handle != NULL); + TR_ASSERT(raw_handle != NULL); TR_ASSERT(hash != NULL); + struct tr_dh_secret* handle = raw_handle; + return tr_sha1(hash, prepend_data == NULL ? "" : prepend_data, prepend_data == NULL ? 0 : (int)prepend_data_size, handle->key, (int)handle->key_length, append_data, append_data == NULL ? 0 : (int)append_data_size, NULL); } diff --git a/libtransmission/crypto-utils-openssl.c b/libtransmission/crypto-utils-openssl.c index 59fcb211b..2c6147e24 100644 --- a/libtransmission/crypto-utils-openssl.c +++ b/libtransmission/crypto-utils-openssl.c @@ -133,10 +133,10 @@ bool tr_sha1_final(tr_sha1_ctx_t handle, uint8_t* hash) if (hash != NULL) { - unsigned int hash_length; - TR_ASSERT(handle != NULL); + unsigned int hash_length; + ret = check_result(EVP_DigestFinal_ex(handle, hash, &hash_length)); TR_ASSERT(!ret || hash_length == SHA_DIGEST_LENGTH); @@ -218,8 +218,6 @@ void tr_rc4_set_key(tr_rc4_ctx_t handle, uint8_t const* key, size_t key_length) void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t length) { - int output_length; - TR_ASSERT(handle != NULL); if (length == 0) @@ -230,6 +228,8 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t TR_ASSERT(input != NULL); TR_ASSERT(output != NULL); + int output_length; + check_result(EVP_CipherUpdate(handle, output, &output_length, input, length)); } @@ -299,13 +299,13 @@ static inline void DH_get0_key(DH const* dh, BIGNUM const** pub_key, BIGNUM cons tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, size_t generator_num_length) { + TR_ASSERT(prime_num != NULL); + TR_ASSERT(generator_num != NULL); + DH* handle = DH_new(); BIGNUM* p; BIGNUM* g; - TR_ASSERT(prime_num != NULL); - TR_ASSERT(generator_num != NULL); - p = BN_bin2bn(prime_num, prime_num_length, NULL); g = BN_bin2bn(generator_num, generator_num_length, NULL); @@ -332,14 +332,14 @@ void tr_dh_free(tr_dh_ctx_t handle) bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length, uint8_t* public_key, size_t* public_key_length) { + TR_ASSERT(raw_handle != NULL); + TR_ASSERT(public_key != NULL); + DH* handle = raw_handle; int dh_size; int my_public_key_length; BIGNUM const* my_public_key; - TR_ASSERT(handle != NULL); - TR_ASSERT(public_key != NULL); - DH_set_length(handle, private_key_length * 8); if (!check_result(DH_generate_key(handle))) @@ -364,14 +364,14 @@ bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length, uint8_t* tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t handle, uint8_t const* other_public_key, size_t other_public_key_length) { + TR_ASSERT(handle != NULL); + TR_ASSERT(other_public_key != NULL); + struct tr_dh_secret* ret; int dh_size; int secret_key_length; BIGNUM* other_key; - TR_ASSERT(handle != NULL); - TR_ASSERT(other_public_key != NULL); - if (!check_pointer(other_key = BN_bin2bn(other_public_key, other_public_key_length, NULL))) { return NULL; diff --git a/libtransmission/crypto-utils-polarssl.c b/libtransmission/crypto-utils-polarssl.c index dad5ff7b2..cdc801fa9 100644 --- a/libtransmission/crypto-utils-polarssl.c +++ b/libtransmission/crypto-utils-polarssl.c @@ -228,11 +228,11 @@ void tr_rc4_process(tr_rc4_ctx_t handle, void const* input, void* output, size_t tr_dh_ctx_t tr_dh_new(uint8_t const* prime_num, size_t prime_num_length, uint8_t const* generator_num, size_t generator_num_length) { - API(dhm_context)* handle = tr_new0(API(dhm_context), 1); - TR_ASSERT(prime_num != NULL); TR_ASSERT(generator_num != NULL); + API(dhm_context)* handle = tr_new0(API(dhm_context), 1); + #if API_VERSION_NUMBER >= 0x01030800 API(dhm_init)(handle); #endif @@ -261,11 +261,11 @@ void tr_dh_free(tr_dh_ctx_t handle) bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length, uint8_t* public_key, size_t* public_key_length) { - API(dhm_context)* handle = raw_handle; - - TR_ASSERT(handle != NULL); + TR_ASSERT(raw_handle != NULL); TR_ASSERT(public_key != NULL); + API(dhm_context)* handle = raw_handle; + if (public_key_length != NULL) { *public_key_length = handle->len; @@ -276,13 +276,13 @@ bool tr_dh_make_key(tr_dh_ctx_t raw_handle, size_t private_key_length, uint8_t* tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t raw_handle, uint8_t const* other_public_key, size_t other_public_key_length) { + TR_ASSERT(raw_handle != NULL); + TR_ASSERT(other_public_key != NULL); + API(dhm_context)* handle = raw_handle; struct tr_dh_secret* ret; size_t secret_key_length; - TR_ASSERT(handle != NULL); - TR_ASSERT(other_public_key != NULL); - if (!check_result(API(dhm_read_public)(handle, other_public_key, other_public_key_length))) { return NULL; @@ -318,11 +318,11 @@ tr_dh_secret_t tr_dh_agree(tr_dh_ctx_t raw_handle, uint8_t const* other_public_k bool tr_rand_buffer(void* buffer, size_t length) { + TR_ASSERT(buffer != NULL); + bool ret; tr_lock* rng_lock = get_rng_lock(); - TR_ASSERT(buffer != NULL); - tr_lockLock(rng_lock); ret = check_result(API(ctr_drbg_random)(get_rng(), buffer, length)); tr_lockUnlock(rng_lock); diff --git a/libtransmission/crypto-utils.c b/libtransmission/crypto-utils.c index 453d6865a..3410a8a8c 100644 --- a/libtransmission/crypto-utils.c +++ b/libtransmission/crypto-utils.c @@ -87,10 +87,10 @@ bool tr_sha1(uint8_t* hash, void const* data1, int data1_length, ...) int tr_rand_int(int upper_bound) { - int noise; - TR_ASSERT(upper_bound > 0); + int noise; + while (tr_rand_buffer(&noise, sizeof(noise))) { noise = abs(noise) % upper_bound; @@ -108,10 +108,10 @@ int tr_rand_int(int upper_bound) int tr_rand_int_weak(int upper_bound) { - static bool init = false; - TR_ASSERT(upper_bound > 0); + static bool init = false; + if (!init) { srand(tr_time_msec()); @@ -127,6 +127,8 @@ int tr_rand_int_weak(int upper_bound) char* tr_ssha1(char const* plain_text) { + TR_ASSERT(plain_text != NULL); + enum { saltval_len = 8, @@ -139,8 +141,6 @@ char* tr_ssha1(char const* plain_text) "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "./"; - TR_ASSERT(plain_text != NULL); - unsigned char salt[saltval_len]; uint8_t sha[SHA_DIGEST_LENGTH]; char buf[2 * SHA_DIGEST_LENGTH + saltval_len + 2]; diff --git a/libtransmission/crypto.c b/libtransmission/crypto.c index 8cfe3d904..e64b998df 100644 --- a/libtransmission/crypto.c +++ b/libtransmission/crypto.c @@ -92,8 +92,6 @@ uint8_t const* tr_cryptoGetMyPublicKey(tr_crypto const* crypto, int* setme_len) static void initRC4(tr_crypto* crypto, tr_rc4_ctx_t* setme, char const* key) { - uint8_t buf[SHA_DIGEST_LENGTH]; - TR_ASSERT(crypto->torrentHashIsSet); if (*setme == NULL) @@ -101,6 +99,8 @@ static void initRC4(tr_crypto* crypto, tr_rc4_ctx_t* setme, char const* key) *setme = tr_rc4_new(); } + uint8_t buf[SHA_DIGEST_LENGTH]; + if (tr_cryptoSecretKeySha1(crypto, key, 4, crypto->torrentHash, SHA_DIGEST_LENGTH, buf)) { tr_rc4_set_key(*setme, buf, SHA_DIGEST_LENGTH); diff --git a/libtransmission/error.c b/libtransmission/error.c index c8e6869e0..5770a8ddc 100644 --- a/libtransmission/error.c +++ b/libtransmission/error.c @@ -13,11 +13,11 @@ tr_error* tr_error_new(int code, char const* message_format, ...) { + TR_ASSERT(message_format != NULL); + tr_error* error; va_list args; - TR_ASSERT(message_format != NULL); - va_start(args, message_format); error = tr_error_new_valist(code, message_format, args); va_end(args); @@ -27,11 +27,9 @@ tr_error* tr_error_new(int code, char const* message_format, ...) tr_error* tr_error_new_literal(int code, char const* message) { - tr_error* error; - TR_ASSERT(message != NULL); - error = tr_new(tr_error, 1); + tr_error* error = tr_new(tr_error, 1); error->code = code; error->message = tr_strdup(message); @@ -40,11 +38,9 @@ tr_error* tr_error_new_literal(int code, char const* message) tr_error* tr_error_new_valist(int code, char const* message_format, va_list args) { - tr_error* error; - TR_ASSERT(message_format != NULL); - error = tr_new(tr_error, 1); + tr_error* error = tr_new(tr_error, 1); error->code = code; error->message = tr_strdup_vprintf(message_format, args); @@ -64,7 +60,7 @@ void tr_error_free(tr_error* error) void tr_error_set(tr_error** error, int code, char const* message_format, ...) { - va_list args; + TR_ASSERT(message_format != NULL); if (error == NULL) { @@ -72,7 +68,8 @@ void tr_error_set(tr_error** error, int code, char const* message_format, ...) } TR_ASSERT(*error == NULL); - TR_ASSERT(message_format != NULL); + + va_list args; va_start(args, message_format); *error = tr_error_new_valist(code, message_format, args); @@ -81,13 +78,14 @@ void tr_error_set(tr_error** error, int code, char const* message_format, ...) void tr_error_set_literal(tr_error** error, int code, char const* message) { + TR_ASSERT(message != NULL); + if (error == NULL) { return; } TR_ASSERT(*error == NULL); - TR_ASSERT(message != NULL); *error = tr_error_new_literal(code, message); } @@ -124,16 +122,13 @@ void tr_error_clear(tr_error** error) static void error_prefix_valist(tr_error** error, char const* prefix_format, va_list args) { - char* prefix; - char* new_message; - TR_ASSERT(error != NULL); TR_ASSERT(*error != NULL); TR_ASSERT(prefix_format != NULL); - prefix = tr_strdup_vprintf(prefix_format, args); + char* prefix = tr_strdup_vprintf(prefix_format, args); - new_message = tr_strdup_printf("%s%s", prefix, (*error)->message); + char* new_message = tr_strdup_printf("%s%s", prefix, (*error)->message); tr_free((*error)->message); (*error)->message = new_message; @@ -142,8 +137,6 @@ static void error_prefix_valist(tr_error** error, char const* prefix_format, va_ void tr_error_prefix(tr_error** error, char const* prefix_format, ...) { - va_list args; - TR_ASSERT(prefix_format != NULL); if (error == NULL || *error == NULL) @@ -151,6 +144,8 @@ void tr_error_prefix(tr_error** error, char const* prefix_format, ...) return; } + va_list args; + va_start(args, prefix_format); error_prefix_valist(error, prefix_format, args); va_end(args); @@ -158,8 +153,6 @@ void tr_error_prefix(tr_error** error, char const* prefix_format, ...) void tr_error_propagate_prefixed(tr_error** new_error, tr_error** old_error, char const* prefix_format, ...) { - va_list args; - TR_ASSERT(prefix_format != NULL); tr_error_propagate(new_error, old_error); @@ -169,6 +162,8 @@ void tr_error_propagate_prefixed(tr_error** new_error, tr_error** old_error, cha return; } + va_list args; + va_start(args, prefix_format); error_prefix_valist(new_error, prefix_format, args); va_end(args); diff --git a/libtransmission/fdlimit.c b/libtransmission/fdlimit.c index 8e070a6a9..f3005cea1 100644 --- a/libtransmission/fdlimit.c +++ b/libtransmission/fdlimit.c @@ -528,9 +528,10 @@ tr_sys_file_t tr_fdFileCheckout(tr_session* session, int torrent_id, tr_file_ind tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type) { + TR_ASSERT(tr_isSession(session)); + tr_socket_t s = TR_BAD_SOCKET; struct tr_fdInfo* gFd; - TR_ASSERT(tr_isSession(session)); ensureSessionFdInfoExists(session); gFd = session->fdInfo; @@ -585,15 +586,15 @@ tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type) tr_socket_t tr_fdSocketAccept(tr_session* s, tr_socket_t sockfd, tr_address* addr, tr_port* port) { + TR_ASSERT(tr_isSession(s)); + TR_ASSERT(addr != NULL); + TR_ASSERT(port != NULL); + tr_socket_t fd; socklen_t len; struct tr_fdInfo* gFd; struct sockaddr_storage sock; - TR_ASSERT(tr_isSession(s)); - TR_ASSERT(addr != NULL); - TR_ASSERT(port != NULL); - ensureSessionFdInfoExists(s); gFd = s->fdInfo; diff --git a/libtransmission/file-posix.c b/libtransmission/file-posix.c index f49132608..43e04fdc1 100644 --- a/libtransmission/file-posix.c +++ b/libtransmission/file-posix.c @@ -219,11 +219,9 @@ static bool create_path(char const* path_in, int permissions, tr_error** error) bool tr_sys_path_exists(char const* path, tr_error** error) { - bool ret; - TR_ASSERT(path != NULL); - ret = access(path, F_OK) != -1; + bool ret = access(path, F_OK) != -1; if (!ret) { @@ -235,12 +233,12 @@ bool tr_sys_path_exists(char const* path, tr_error** error) bool tr_sys_path_get_info(char const* path, int flags, tr_sys_path_info* info, tr_error** error) { - bool ret; - struct stat sb; - TR_ASSERT(path != NULL); TR_ASSERT(info != NULL); + bool ret; + struct stat sb; + if ((flags & TR_SYS_PATH_NO_FOLLOW) == 0) { ret = stat(path, &sb) != -1; @@ -271,13 +269,13 @@ bool tr_sys_path_is_relative(char const* path) bool tr_sys_path_is_same(char const* path1, char const* path2, tr_error** error) { + TR_ASSERT(path1 != NULL); + TR_ASSERT(path2 != NULL); + bool ret = false; struct stat sb1; struct stat sb2; - TR_ASSERT(path1 != NULL); - TR_ASSERT(path2 != NULL); - if (stat(path1, &sb1) != -1 && stat(path2, &sb2) != -1) { ret = sb1.st_dev == sb2.st_dev && sb1.st_ino == sb2.st_ino; @@ -292,11 +290,11 @@ bool tr_sys_path_is_same(char const* path1, char const* path2, tr_error** error) char* tr_sys_path_resolve(char const* path, tr_error** error) { + TR_ASSERT(path != NULL); + char* ret = NULL; char* tmp = NULL; - TR_ASSERT(path != NULL); - #if defined(HAVE_CANONICALIZE_FILE_NAME) ret = canonicalize_file_name(path); @@ -338,11 +336,11 @@ char* tr_sys_path_resolve(char const* path, tr_error** error) char* tr_sys_path_basename(char const* path, tr_error** error) { + TR_ASSERT(path != NULL); + char* ret = NULL; char* tmp; - TR_ASSERT(path != NULL); - tmp = tr_strdup(path); ret = basename(tmp); @@ -362,13 +360,10 @@ char* tr_sys_path_basename(char const* path, tr_error** error) char* tr_sys_path_dirname(char const* path, tr_error** error) { - char* ret = NULL; - char* tmp; - TR_ASSERT(path != NULL); - tmp = tr_strdup(path); - ret = dirname(tmp); + char* tmp = tr_strdup(path); + char* ret = dirname(tmp); if (ret != NULL) { @@ -386,12 +381,10 @@ char* tr_sys_path_dirname(char const* path, tr_error** error) bool tr_sys_path_rename(char const* src_path, char const* dst_path, tr_error** error) { - bool ret; - TR_ASSERT(src_path != NULL); TR_ASSERT(dst_path != NULL); - ret = rename(src_path, dst_path) != -1; + bool ret = rename(src_path, dst_path) != -1; if (!ret) { @@ -403,11 +396,9 @@ bool tr_sys_path_rename(char const* src_path, char const* dst_path, tr_error** e bool tr_sys_path_remove(char const* path, tr_error** error) { - bool ret; - TR_ASSERT(path != NULL); - ret = remove(path) != -1; + bool ret = remove(path) != -1; if (!ret) { @@ -445,12 +436,12 @@ tr_sys_file_t tr_sys_file_get_std(tr_std_sys_file_t std_file, tr_error** error) tr_sys_file_t tr_sys_file_open(char const* path, int flags, int permissions, tr_error** error) { - tr_sys_file_t ret; - int native_flags = 0; - TR_ASSERT(path != NULL); TR_ASSERT((flags & (TR_SYS_FILE_READ | TR_SYS_FILE_WRITE)) != 0); + tr_sys_file_t ret; + int native_flags = 0; + if ((flags & (TR_SYS_FILE_READ | TR_SYS_FILE_WRITE)) == (TR_SYS_FILE_READ | TR_SYS_FILE_WRITE)) { native_flags |= O_RDWR; @@ -491,11 +482,9 @@ tr_sys_file_t tr_sys_file_open(char const* path, int flags, int permissions, tr_ tr_sys_file_t tr_sys_file_open_temp(char* path_template, tr_error** error) { - tr_sys_file_t ret; - TR_ASSERT(path_template != NULL); - ret = mkstemp(path_template); + tr_sys_file_t ret = mkstemp(path_template); if (ret == TR_BAD_SYS_FILE) { @@ -509,11 +498,9 @@ tr_sys_file_t tr_sys_file_open_temp(char* path_template, tr_error** error) bool tr_sys_file_close(tr_sys_file_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - ret = close(handle) != -1; + bool ret = close(handle) != -1; if (!ret) { @@ -525,13 +512,11 @@ bool tr_sys_file_close(tr_sys_file_t handle, tr_error** error) bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, tr_error** error) { - bool ret; - struct stat sb; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(info != NULL); - ret = fstat(handle, &sb) != -1; + struct stat sb; + bool ret = fstat(handle, &sb) != -1; if (ret) { @@ -547,18 +532,18 @@ bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, tr_error bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t origin, uint64_t* new_offset, tr_error** error) { - bool ret = false; - off_t my_new_offset; - TR_STATIC_ASSERT(TR_SEEK_SET == SEEK_SET, "values should match"); TR_STATIC_ASSERT(TR_SEEK_CUR == SEEK_CUR, "values should match"); TR_STATIC_ASSERT(TR_SEEK_END == SEEK_END, "values should match"); - TR_STATIC_ASSERT(sizeof(*new_offset) >= sizeof(my_new_offset), ""); - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(origin == TR_SEEK_SET || origin == TR_SEEK_CUR || origin == TR_SEEK_END); + bool ret = false; + off_t my_new_offset; + + TR_STATIC_ASSERT(sizeof(*new_offset) >= sizeof(my_new_offset), ""); + my_new_offset = lseek(handle, offset, origin); if (my_new_offset != -1) @@ -580,14 +565,14 @@ bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t ori bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t* bytes_read, tr_error** error) { + TR_ASSERT(handle != TR_BAD_SYS_FILE); + TR_ASSERT(buffer != NULL || size == 0); + bool ret = false; ssize_t my_bytes_read; TR_STATIC_ASSERT(sizeof(*bytes_read) >= sizeof(my_bytes_read), ""); - TR_ASSERT(handle != TR_BAD_SYS_FILE); - TR_ASSERT(buffer != NULL || size == 0); - my_bytes_read = read(handle, buffer, size); if (my_bytes_read != -1) @@ -610,16 +595,16 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_read, tr_error** error) { - bool ret = false; - ssize_t my_bytes_read; - - TR_STATIC_ASSERT(sizeof(*bytes_read) >= sizeof(my_bytes_read), ""); - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); /* seek requires signed offset, so it should be in mod range */ TR_ASSERT(offset < UINT64_MAX / 2); + bool ret = false; + ssize_t my_bytes_read; + + TR_STATIC_ASSERT(sizeof(*bytes_read) >= sizeof(my_bytes_read), ""); + #ifdef HAVE_PREAD my_bytes_read = pread(handle, buffer, size, offset); @@ -656,14 +641,14 @@ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t* bytes_written, tr_error** error) { + TR_ASSERT(handle != TR_BAD_SYS_FILE); + TR_ASSERT(buffer != NULL || size == 0); + bool ret = false; ssize_t my_bytes_written; TR_STATIC_ASSERT(sizeof(*bytes_written) >= sizeof(my_bytes_written), ""); - TR_ASSERT(handle != TR_BAD_SYS_FILE); - TR_ASSERT(buffer != NULL || size == 0); - my_bytes_written = write(handle, buffer, size); if (my_bytes_written != -1) @@ -686,16 +671,16 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_written, tr_error** error) { - bool ret = false; - ssize_t my_bytes_written; - - TR_STATIC_ASSERT(sizeof(*bytes_written) >= sizeof(my_bytes_written), ""); - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); /* seek requires signed offset, so it should be in mod range */ TR_ASSERT(offset < UINT64_MAX / 2); + bool ret = false; + ssize_t my_bytes_written; + + TR_STATIC_ASSERT(sizeof(*bytes_written) >= sizeof(my_bytes_written), ""); + #ifdef HAVE_PWRITE my_bytes_written = pwrite(handle, buffer, size, offset); @@ -732,11 +717,9 @@ bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t siz bool tr_sys_file_flush(tr_sys_file_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - ret = fsync(handle) != -1; + bool ret = fsync(handle) != -1; if (!ret) { @@ -748,11 +731,9 @@ bool tr_sys_file_flush(tr_sys_file_t handle, tr_error** error) bool tr_sys_file_truncate(tr_sys_file_t handle, uint64_t size, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - ret = ftruncate(handle, size) != -1; + bool ret = ftruncate(handle, size) != -1; if (!ret) { @@ -764,16 +745,14 @@ bool tr_sys_file_truncate(tr_sys_file_t handle, uint64_t size, tr_error** error) bool tr_sys_file_prefetch(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr_error** error) { + TR_ASSERT(handle != TR_BAD_SYS_FILE); + TR_ASSERT(size > 0); + bool ret = false; #if defined(HAVE_POSIX_FADVISE) - int code; - - TR_ASSERT(handle != TR_BAD_SYS_FILE); - TR_ASSERT(size > 0); - - code = posix_fadvise(handle, offset, size, POSIX_FADV_WILLNEED); + int code = posix_fadvise(handle, offset, size, POSIX_FADV_WILLNEED); if (code == 0) { @@ -787,10 +766,6 @@ bool tr_sys_file_prefetch(tr_sys_file_t handle, uint64_t offset, uint64_t size, #elif defined(__APPLE__) struct radvisory radv; - - TR_ASSERT(handle != TR_BAD_SYS_FILE); - TR_ASSERT(size > 0); - radv.ra_offset = offset; radv.ra_count = size; @@ -808,10 +783,10 @@ bool tr_sys_file_prefetch(tr_sys_file_t handle, uint64_t offset, uint64_t size, bool tr_sys_file_preallocate(tr_sys_file_t handle, uint64_t size, int flags, tr_error** error) { - bool ret = false; - TR_ASSERT(handle != TR_BAD_SYS_FILE); + bool ret = false; + errno = 0; #ifdef HAVE_FALLOCATE64 @@ -912,12 +887,10 @@ out: void* tr_sys_file_map_for_reading(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr_error** error) { - void* ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(size > 0); - ret = mmap(NULL, size, PROT_READ, MAP_SHARED, handle, offset); + void* ret = mmap(NULL, size, PROT_READ, MAP_SHARED, handle, offset); if (ret == MAP_FAILED) { @@ -930,12 +903,10 @@ void* tr_sys_file_map_for_reading(tr_sys_file_t handle, uint64_t offset, uint64_ bool tr_sys_file_unmap(void const* address, uint64_t size, tr_error** error) { - bool ret; - TR_ASSERT(address != NULL); TR_ASSERT(size > 0); - ret = munmap((void*)address, size) != -1; + bool ret = munmap((void*)address, size) != -1; if (!ret) { @@ -947,14 +918,14 @@ bool tr_sys_file_unmap(void const* address, uint64_t size, tr_error** error) bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) { - bool ret; - int native_operation = 0; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT((operation & ~(TR_SYS_FILE_LOCK_SH | TR_SYS_FILE_LOCK_EX | TR_SYS_FILE_LOCK_NB | TR_SYS_FILE_LOCK_UN)) == 0); TR_ASSERT(!!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + !!(operation & TR_SYS_FILE_LOCK_UN) == 1); + bool ret; + int native_operation = 0; + if ((operation & TR_SYS_FILE_LOCK_SH) != 0) { native_operation |= LOCK_SH; @@ -1028,11 +999,11 @@ char* tr_sys_dir_get_current(tr_error** error) bool tr_sys_dir_create(char const* path, int flags, int permissions, tr_error** error) { + TR_ASSERT(path != NULL); + bool ret; tr_error* my_error = NULL; - TR_ASSERT(path != NULL); - if ((flags & TR_SYS_DIR_CREATE_PARENTS) != 0) { #ifdef HAVE_MKDIRP @@ -1078,10 +1049,10 @@ bool tr_sys_dir_create(char const* path, int flags, int permissions, tr_error** bool tr_sys_dir_create_temp(char* path_template, tr_error** error) { - bool ret; - TR_ASSERT(path_template != NULL); + bool ret; + #ifdef HAVE_MKDTEMP ret = mkdtemp(path_template) != NULL; @@ -1102,8 +1073,6 @@ bool tr_sys_dir_create_temp(char* path_template, tr_error** error) tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) { - tr_sys_dir_t ret; - #ifndef __clang__ /* Clang gives "static_assert expression is not an integral constant expression" error */ TR_STATIC_ASSERT(TR_BAD_SYS_DIR == NULL, "values should match"); @@ -1111,7 +1080,7 @@ tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) TR_ASSERT(path != NULL); - ret = opendir(path); + tr_sys_dir_t ret = opendir(path); if (ret == TR_BAD_SYS_DIR) { @@ -1123,13 +1092,12 @@ tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) { - char const* ret = NULL; - struct dirent* entry; - TR_ASSERT(handle != TR_BAD_SYS_DIR); + char const* ret = NULL; + errno = 0; - entry = readdir(handle); + struct dirent* entry = readdir(handle); if (entry != NULL) { @@ -1145,11 +1113,9 @@ char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) bool tr_sys_dir_close(tr_sys_dir_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_DIR); - ret = closedir(handle) != -1; + bool ret = closedir(handle) != -1; if (!ret) { diff --git a/libtransmission/file-win32.c b/libtransmission/file-win32.c index 921b4aaca..de0ef95d5 100644 --- a/libtransmission/file-win32.c +++ b/libtransmission/file-win32.c @@ -66,10 +66,9 @@ static void set_system_error_if_file_found(tr_error** error, DWORD code) static time_t filetime_to_unix_time(FILETIME const* t) { - uint64_t tmp = 0; - TR_ASSERT(t != NULL); + uint64_t tmp = 0; tmp |= t->dwHighDateTime; tmp <<= 32; tmp |= t->dwLowDateTime; @@ -204,12 +203,10 @@ static wchar_t* path_to_native_path(char const* path) static tr_sys_file_t open_file(char const* path, DWORD access, DWORD disposition, DWORD flags, tr_error** error) { - tr_sys_file_t ret = TR_BAD_SYS_FILE; - wchar_t* wide_path; - TR_ASSERT(path != NULL); - wide_path = path_to_native_path(path); + tr_sys_file_t ret = TR_BAD_SYS_FILE; + wchar_t* wide_path = path_to_native_path(path); if (wide_path != NULL) { @@ -229,15 +226,13 @@ static tr_sys_file_t open_file(char const* path, DWORD access, DWORD disposition static bool create_dir(char const* path, int flags, int permissions, bool okay_if_exists, tr_error** error) { - bool ret; - wchar_t* wide_path; - DWORD error_code = ERROR_SUCCESS; - TR_ASSERT(path != NULL); (void)permissions; - wide_path = path_to_native_path(path); + bool ret; + DWORD error_code = ERROR_SUCCESS; + wchar_t* wide_path = path_to_native_path(path); if ((flags & TR_SYS_DIR_CREATE_PARENTS) != 0) { @@ -278,18 +273,16 @@ static bool create_dir(char const* path, int flags, int permissions, bool okay_i static void create_temp_path(char* path_template, void (* callback)(char const* path, void* param, tr_error** error), void* callback_param, tr_error** error) { - char* path; - size_t path_size; - tr_error* my_error = NULL; - TR_ASSERT(path_template != NULL); TR_ASSERT(callback != NULL); - path = tr_strdup(path_template); - path_size = strlen(path); + char* path = tr_strdup(path_template); + size_t path_size = strlen(path); TR_ASSERT(path_size > 0); + tr_error* my_error = NULL; + for (int attempt = 0; attempt < 100; ++attempt) { size_t i = path_size; @@ -327,13 +320,11 @@ static void create_temp_path(char* path_template, void (* callback)(char const* bool tr_sys_path_exists(char const* path, tr_error** error) { - bool ret = false; - wchar_t* wide_path; - HANDLE handle = INVALID_HANDLE_VALUE; - TR_ASSERT(path != NULL); - wide_path = path_to_native_path(path); + bool ret = false; + HANDLE handle = INVALID_HANDLE_VALUE; + wchar_t* wide_path = path_to_native_path(path); if (wide_path != NULL) { @@ -370,13 +361,11 @@ bool tr_sys_path_exists(char const* path, tr_error** error) bool tr_sys_path_get_info(char const* path, int flags, tr_sys_path_info* info, tr_error** error) { - bool ret = false; - wchar_t* wide_path; - TR_ASSERT(path != NULL); TR_ASSERT(info != NULL); - wide_path = path_to_native_path(path); + bool ret = false; + wchar_t* wide_path = path_to_native_path(path); if ((flags & TR_SYS_PATH_NO_FOLLOW) == 0) { @@ -450,6 +439,9 @@ bool tr_sys_path_is_relative(char const* path) bool tr_sys_path_is_same(char const* path1, char const* path2, tr_error** error) { + TR_ASSERT(path1 != NULL); + TR_ASSERT(path2 != NULL); + bool ret = false; wchar_t* wide_path1 = NULL; wchar_t* wide_path2 = NULL; @@ -457,9 +449,6 @@ bool tr_sys_path_is_same(char const* path1, char const* path2, tr_error** error) HANDLE handle2 = INVALID_HANDLE_VALUE; BY_HANDLE_FILE_INFORMATION fi1, fi2; - TR_ASSERT(path1 != NULL); - TR_ASSERT(path2 != NULL); - wide_path1 = path_to_native_path(path1); if (wide_path1 == NULL) @@ -515,14 +504,14 @@ cleanup: char* tr_sys_path_resolve(char const* path, tr_error** error) { + TR_ASSERT(path != NULL); + char* ret = NULL; wchar_t* wide_path; wchar_t* wide_ret = NULL; HANDLE handle = INVALID_HANDLE_VALUE; DWORD wide_ret_size; - TR_ASSERT(path != NULL); - wide_path = path_to_native_path(path); if (wide_path == NULL) @@ -677,15 +666,12 @@ char* tr_sys_path_dirname(char const* path, tr_error** error) bool tr_sys_path_rename(char const* src_path, char const* dst_path, tr_error** error) { - bool ret = false; - wchar_t* wide_src_path; - wchar_t* wide_dst_path; - TR_ASSERT(src_path != NULL); TR_ASSERT(dst_path != NULL); - wide_src_path = path_to_native_path(src_path); - wide_dst_path = path_to_native_path(dst_path); + bool ret = false; + wchar_t* wide_src_path = path_to_native_path(src_path); + wchar_t* wide_dst_path = path_to_native_path(dst_path); if (wide_src_path != NULL && wide_dst_path != NULL) { @@ -724,12 +710,10 @@ bool tr_sys_path_rename(char const* src_path, char const* dst_path, tr_error** e bool tr_sys_path_remove(char const* path, tr_error** error) { - bool ret = false; - wchar_t* wide_path; - TR_ASSERT(path != NULL); - wide_path = path_to_native_path(path); + bool ret = false; + wchar_t* wide_path = path_to_native_path(path); if (wide_path != NULL) { @@ -796,17 +780,17 @@ tr_sys_file_t tr_sys_file_get_std(tr_std_sys_file_t std_file, tr_error** error) tr_sys_file_t tr_sys_file_open(char const* path, int flags, int permissions, tr_error** error) { + TR_ASSERT(path != NULL); + TR_ASSERT((flags & (TR_SYS_FILE_READ | TR_SYS_FILE_WRITE)) != 0); + + (void)permissions; + tr_sys_file_t ret; DWORD native_access = 0; DWORD native_disposition = OPEN_EXISTING; DWORD native_flags = FILE_ATTRIBUTE_NORMAL; bool success; - TR_ASSERT(path != NULL); - TR_ASSERT((flags & (TR_SYS_FILE_READ | TR_SYS_FILE_WRITE)) != 0); - - (void)permissions; - if ((flags & TR_SYS_FILE_READ) != 0) { native_access |= GENERIC_READ; @@ -869,10 +853,10 @@ static void file_open_temp_callback(char const* path, void* param, tr_error** er tr_sys_file_t tr_sys_file_open_temp(char* path_template, tr_error** error) { - tr_sys_file_t ret = TR_BAD_SYS_FILE; - TR_ASSERT(path_template != NULL); + tr_sys_file_t ret = TR_BAD_SYS_FILE; + create_temp_path(path_template, file_open_temp_callback, &ret, error); return ret; @@ -880,11 +864,9 @@ tr_sys_file_t tr_sys_file_open_temp(char* path_template, tr_error** error) bool tr_sys_file_close(tr_sys_file_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - ret = CloseHandle(handle); + bool ret = CloseHandle(handle); if (!ret) { @@ -896,13 +878,11 @@ bool tr_sys_file_close(tr_sys_file_t handle, tr_error** error) bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, tr_error** error) { - bool ret; - BY_HANDLE_FILE_INFORMATION attributes; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(info != NULL); - ret = GetFileInformationByHandle(handle, &attributes); + BY_HANDLE_FILE_INFORMATION attributes; + bool ret = GetFileInformationByHandle(handle, &attributes); if (ret) { @@ -919,9 +899,6 @@ bool tr_sys_file_get_info(tr_sys_file_t handle, tr_sys_path_info* info, tr_error bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t origin, uint64_t* new_offset, tr_error** error) { - bool ret = false; - LARGE_INTEGER native_offset, new_native_pointer; - TR_STATIC_ASSERT(TR_SEEK_SET == FILE_BEGIN, "values should match"); TR_STATIC_ASSERT(TR_SEEK_CUR == FILE_CURRENT, "values should match"); TR_STATIC_ASSERT(TR_SEEK_END == FILE_END, "values should match"); @@ -929,6 +906,10 @@ bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t ori TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(origin == TR_SEEK_SET || origin == TR_SEEK_CUR || origin == TR_SEEK_END); + bool ret = false; + LARGE_INTEGER native_offset; + LARGE_INTEGER new_native_pointer; + native_offset.QuadPart = offset; if (SetFilePointerEx(handle, native_offset, &new_native_pointer, origin)) @@ -950,9 +931,6 @@ bool tr_sys_file_seek(tr_sys_file_t handle, int64_t offset, tr_seek_origin_t ori bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t* bytes_read, tr_error** error) { - bool ret = false; - DWORD my_bytes_read; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); @@ -962,6 +940,9 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ return false; } + bool ret = false; + DWORD my_bytes_read; + if (ReadFile(handle, buffer, (DWORD)size, &my_bytes_read, NULL)) { if (bytes_read != NULL) @@ -982,10 +963,6 @@ bool tr_sys_file_read(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_read, tr_error** error) { - bool ret = false; - OVERLAPPED overlapped; - DWORD my_bytes_read; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); @@ -995,6 +972,10 @@ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint return false; } + bool ret = false; + OVERLAPPED overlapped; + DWORD my_bytes_read; + overlapped.Offset = (DWORD)offset; offset >>= 32; overlapped.OffsetHigh = (DWORD)offset; @@ -1019,9 +1000,6 @@ bool tr_sys_file_read_at(tr_sys_file_t handle, void* buffer, uint64_t size, uint bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t* bytes_written, tr_error** error) { - bool ret = false; - DWORD my_bytes_written; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); @@ -1031,6 +1009,9 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, return false; } + bool ret = false; + DWORD my_bytes_written; + if (WriteFile(handle, buffer, (DWORD)size, &my_bytes_written, NULL)) { if (bytes_written != NULL) @@ -1051,10 +1032,6 @@ bool tr_sys_file_write(tr_sys_file_t handle, void const* buffer, uint64_t size, bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t size, uint64_t offset, uint64_t* bytes_written, tr_error** error) { - bool ret = false; - OVERLAPPED overlapped; - DWORD my_bytes_written; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL || size == 0); @@ -1064,6 +1041,10 @@ bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t siz return false; } + bool ret = false; + OVERLAPPED overlapped; + DWORD my_bytes_written; + overlapped.Offset = (DWORD)offset; offset >>= 32; overlapped.OffsetHigh = (DWORD)offset; @@ -1088,11 +1069,9 @@ bool tr_sys_file_write_at(tr_sys_file_t handle, void const* buffer, uint64_t siz bool tr_sys_file_flush(tr_sys_file_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - ret = FlushFileBuffers(handle); + bool ret = FlushFileBuffers(handle); if (!ret) { @@ -1104,14 +1083,12 @@ bool tr_sys_file_flush(tr_sys_file_t handle, tr_error** error) bool tr_sys_file_truncate(tr_sys_file_t handle, uint64_t size, tr_error** error) { - bool ret = false; - FILE_END_OF_FILE_INFO info; - TR_ASSERT(handle != TR_BAD_SYS_FILE); + FILE_END_OF_FILE_INFO info; info.EndOfFile.QuadPart = size; - ret = SetFileInformationByHandle(handle, FileEndOfFileInfo, &info, sizeof(info)); + bool ret = SetFileInformationByHandle(handle, FileEndOfFileInfo, &info, sizeof(info)); if (!ret) { @@ -1123,8 +1100,6 @@ bool tr_sys_file_truncate(tr_sys_file_t handle, uint64_t size, tr_error** error) bool tr_sys_file_prefetch(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr_error** error) { - bool ret = false; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(size > 0); @@ -1133,6 +1108,8 @@ bool tr_sys_file_prefetch(tr_sys_file_t handle, uint64_t offset, uint64_t size, (void)size; (void)error; + bool ret = false; + /* ??? */ return ret; @@ -1158,9 +1135,6 @@ bool tr_sys_file_preallocate(tr_sys_file_t handle, uint64_t size, int flags, tr_ void* tr_sys_file_map_for_reading(tr_sys_file_t handle, uint64_t offset, uint64_t size, tr_error** error) { - void* ret = NULL; - HANDLE mappingHandle; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(size > 0); @@ -1170,7 +1144,8 @@ void* tr_sys_file_map_for_reading(tr_sys_file_t handle, uint64_t offset, uint64_ return false; } - mappingHandle = CreateFileMappingW(handle, NULL, PAGE_READONLY, 0, 0, NULL); + void* ret = NULL; + HANDLE mappingHandle = CreateFileMappingW(handle, NULL, PAGE_READONLY, 0, 0, NULL); if (mappingHandle != NULL) { @@ -1193,14 +1168,12 @@ void* tr_sys_file_map_for_reading(tr_sys_file_t handle, uint64_t offset, uint64_ bool tr_sys_file_unmap(void const* address, uint64_t size, tr_error** error) { - bool ret; - TR_ASSERT(address != NULL); TR_ASSERT(size > 0); (void)size; - ret = UnmapViewOfFile(address); + bool ret = UnmapViewOfFile(address); if (!ret) { @@ -1212,14 +1185,14 @@ bool tr_sys_file_unmap(void const* address, uint64_t size, tr_error** error) bool tr_sys_file_lock(tr_sys_file_t handle, int operation, tr_error** error) { - bool ret; - OVERLAPPED overlapped = { .Pointer = 0, .hEvent = NULL }; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT((operation & ~(TR_SYS_FILE_LOCK_SH | TR_SYS_FILE_LOCK_EX | TR_SYS_FILE_LOCK_NB | TR_SYS_FILE_LOCK_UN)) == 0); TR_ASSERT(!!(operation & TR_SYS_FILE_LOCK_SH) + !!(operation & TR_SYS_FILE_LOCK_EX) + !!(operation & TR_SYS_FILE_LOCK_UN) == 1); + bool ret; + OVERLAPPED overlapped = { .Pointer = 0, .hEvent = NULL }; + if ((operation & TR_SYS_FILE_LOCK_UN) == 0) { DWORD native_flags = 0; @@ -1293,10 +1266,10 @@ static void dir_create_temp_callback(char const* path, void* param, tr_error** e bool tr_sys_dir_create_temp(char* path_template, tr_error** error) { - bool ret = false; - TR_ASSERT(path_template != NULL); + bool ret = false; + create_temp_path(path_template, dir_create_temp_callback, &ret, error); return ret; @@ -1304,9 +1277,6 @@ bool tr_sys_dir_create_temp(char* path_template, tr_error** error) tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) { - tr_sys_dir_t ret; - int pattern_size; - #ifndef __clang__ /* Clang gives "static_assert expression is not an integral constant expression" error */ TR_STATIC_ASSERT(TR_BAD_SYS_DIR == NULL, "values should match"); @@ -1314,7 +1284,9 @@ tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) TR_ASSERT(path != NULL); - ret = tr_new(struct tr_sys_dir_win32, 1); + tr_sys_dir_t ret = tr_new(struct tr_sys_dir_win32, 1); + + int pattern_size; ret->pattern = path_to_native_path_ex(path, 2, &pattern_size); if (ret->pattern != NULL) @@ -1340,11 +1312,10 @@ tr_sys_dir_t tr_sys_dir_open(char const* path, tr_error** error) char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) { - char* ret; - DWORD error_code = ERROR_SUCCESS; - TR_ASSERT(handle != TR_BAD_SYS_DIR); + DWORD error_code = ERROR_SUCCESS; + if (handle->find_handle == INVALID_HANDLE_VALUE) { handle->find_handle = FindFirstFileW(handle->pattern, &handle->find_data); @@ -1368,7 +1339,7 @@ char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) return NULL; } - ret = tr_win32_native_to_utf8(handle->find_data.cFileName, -1); + char* ret = tr_win32_native_to_utf8(handle->find_data.cFileName, -1); if (ret != NULL) { @@ -1385,11 +1356,9 @@ char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) bool tr_sys_dir_close(tr_sys_dir_t handle, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_DIR); - ret = FindClose(handle->find_handle); + bool ret = FindClose(handle->find_handle); if (!ret) { diff --git a/libtransmission/file.c b/libtransmission/file.c index 97a5cfe13..a2da678df 100644 --- a/libtransmission/file.c +++ b/libtransmission/file.c @@ -16,14 +16,14 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_size, tr_error** error) { - bool ret = false; - size_t offset = 0; - uint64_t bytes_read; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL); TR_ASSERT(buffer_size > 0); + bool ret = false; + size_t offset = 0; + uint64_t bytes_read; + while (buffer_size > 0) { ret = tr_sys_file_read(handle, buffer + offset, MIN(buffer_size, 1024u), &bytes_read, error); @@ -75,12 +75,10 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_siz bool tr_sys_file_write_line(tr_sys_file_t handle, char const* buffer, tr_error** error) { - bool ret; - TR_ASSERT(handle != TR_BAD_SYS_FILE); TR_ASSERT(buffer != NULL); - ret = tr_sys_file_write(handle, buffer, strlen(buffer), NULL, error); + bool ret = tr_sys_file_write(handle, buffer, strlen(buffer), NULL, error); if (ret) { @@ -92,13 +90,13 @@ bool tr_sys_file_write_line(tr_sys_file_t handle, char const* buffer, tr_error** bool tr_sys_file_write_fmt(tr_sys_file_t handle, char const* format, tr_error** error, ...) { + TR_ASSERT(handle != TR_BAD_SYS_FILE); + TR_ASSERT(format != NULL); + bool ret = false; char* buffer; va_list args; - TR_ASSERT(handle != TR_BAD_SYS_FILE); - TR_ASSERT(format != NULL); - va_start(args, error); buffer = tr_strdup_vprintf(format, args); va_end(args); diff --git a/libtransmission/handshake.c b/libtransmission/handshake.c index 19ed2df8d..737b23633 100644 --- a/libtransmission/handshake.c +++ b/libtransmission/handshake.c @@ -1014,13 +1014,13 @@ static ReadState readPayloadStream(tr_handshake* handshake, struct evbuffer* inb static ReadState canRead(struct tr_peerIo* io, void* arg, size_t* piece) { + TR_ASSERT(tr_isPeerIo(io)); + ReadState ret; tr_handshake* handshake = arg; struct evbuffer* inbuf = tr_peerIoGetReadBuffer(io); bool readyForMore = true; - TR_ASSERT(tr_isPeerIo(io)); - /* no piece data in handshake */ *piece = 0; @@ -1261,12 +1261,10 @@ struct tr_peerIo* tr_handshakeGetIO(tr_handshake* handshake) struct tr_peerIo* tr_handshakeStealIO(tr_handshake* handshake) { - struct tr_peerIo* io; - TR_ASSERT(handshake != NULL); TR_ASSERT(handshake->io != NULL); - io = handshake->io; + struct tr_peerIo* io = handshake->io; handshake->io = NULL; return io; } diff --git a/libtransmission/inout.c b/libtransmission/inout.c index bd01dc7ef..c392a685e 100644 --- a/libtransmission/inout.c +++ b/libtransmission/inout.c @@ -166,13 +166,13 @@ static int compareOffsetToFile(void const* a, void const* b) void tr_ioFindFileLocation(tr_torrent const* tor, tr_piece_index_t pieceIndex, uint32_t pieceOffset, tr_file_index_t* fileIndex, uint64_t* fileOffset) { - uint64_t const offset = tr_pieceOffset(tor, pieceIndex, pieceOffset, 0); - tr_file const* file; - TR_ASSERT(tr_isTorrent(tor)); + + uint64_t const offset = tr_pieceOffset(tor, pieceIndex, pieceOffset, 0); + TR_ASSERT(offset < tor->info.totalSize); - file = bsearch(&offset, tor->info.files, tor->info.fileCount, sizeof(tr_file), compareOffsetToFile); + tr_file const* file = bsearch(&offset, tor->info.files, tor->info.fileCount, sizeof(tr_file), compareOffsetToFile); TR_ASSERT(file != NULL); @@ -243,6 +243,10 @@ int tr_ioWrite(tr_torrent* tor, tr_piece_index_t pieceIndex, uint32_t begin, uin static bool recalculateHash(tr_torrent* tor, tr_piece_index_t pieceIndex, uint8_t* setme) { + TR_ASSERT(tor != NULL); + TR_ASSERT(pieceIndex < tor->info.pieceCount); + TR_ASSERT(setme != NULL); + size_t bytesLeft; uint32_t offset = 0; bool success = true; @@ -250,11 +254,8 @@ static bool recalculateHash(tr_torrent* tor, tr_piece_index_t pieceIndex, uint8_ void* buffer = tr_valloc(buflen); tr_sha1_ctx_t sha; - TR_ASSERT(tor != NULL); - TR_ASSERT(pieceIndex < tor->info.pieceCount); TR_ASSERT(buffer != NULL); TR_ASSERT(buflen > 0); - TR_ASSERT(setme != NULL); sha = tr_sha1_init(); bytesLeft = tr_torPieceCountBytes(tor, pieceIndex); diff --git a/libtransmission/libtransmission-test.c b/libtransmission/libtransmission-test.c index 13d15d1d0..dbca07aad 100644 --- a/libtransmission/libtransmission-test.c +++ b/libtransmission/libtransmission-test.c @@ -499,11 +499,11 @@ static void onVerifyDone(tr_torrent* tor UNUSED, bool aborted UNUSED, void* done void libttest_blockingTorrentVerify(tr_torrent* tor) { - bool done = false; - TR_ASSERT(tor->session != NULL); TR_ASSERT(!tr_amInEventThread(tor->session)); + bool done = false; + tr_torrentVerify(tor, onVerifyDone, &done); while (!done) diff --git a/libtransmission/magnet.c b/libtransmission/magnet.c index 1197d537d..5196a2c4a 100644 --- a/libtransmission/magnet.c +++ b/libtransmission/magnet.c @@ -42,12 +42,12 @@ static int const base32LookupLen = TR_N_ELEMENTS(base32Lookup); static void base32_to_sha1(uint8_t* out, char const* in, size_t const inlen) { + TR_ASSERT(inlen == 32); + size_t const outlen = 20; memset(out, 0, 20); - TR_ASSERT(inlen == 32); - for (size_t i = 0, index = 0, offset = 0; i < inlen; ++i) { int digit; diff --git a/libtransmission/makemeta.c b/libtransmission/makemeta.c index b62e936a1..86e09cebe 100644 --- a/libtransmission/makemeta.c +++ b/libtransmission/makemeta.c @@ -274,12 +274,12 @@ static uint8_t* getHashInfo(tr_metainfo_builder* b) while (totalRemain) { + TR_ASSERT(b->pieceIndex < b->pieceCount); + uint8_t* bufptr = buf; uint32_t const thisPieceSize = (uint32_t)MIN(b->pieceSize, totalRemain); uint64_t leftInPiece = thisPieceSize; - TR_ASSERT(b->pieceIndex < b->pieceCount); - while (leftInPiece != 0) { uint64_t const n_this_pass = MIN(b->files[fileIndex].size - off, leftInPiece); diff --git a/libtransmission/metainfo.c b/libtransmission/metainfo.c index ea3e63575..d7da9f564 100644 --- a/libtransmission/metainfo.c +++ b/libtransmission/metainfo.c @@ -73,14 +73,14 @@ static bool path_component_is_suspicious(char const* component) static bool getfile(char** setme, char const* root, tr_variant* path, struct evbuffer* buf) { + /* root's already been checked by caller */ + TR_ASSERT(!path_component_is_suspicious(root)); + bool success = false; size_t root_len = 0; *setme = NULL; - /* root's already been checked by caller */ - TR_ASSERT(!path_component_is_suspicious(root)); - if (tr_variantIsList(path)) { success = true; diff --git a/libtransmission/net.c b/libtransmission/net.c index f108abc88..0708127b0 100644 --- a/libtransmission/net.c +++ b/libtransmission/net.c @@ -233,6 +233,8 @@ static socklen_t setup_sockaddr(tr_address const* addr, tr_port port, struct soc tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr_port port, bool clientIsSeed) { + TR_ASSERT(tr_address_is_valid(addr)); + static int const domains[NUM_TR_AF_INET_TYPES] = { AF_INET, AF_INET6 }; tr_socket_t s; struct sockaddr_storage sock; @@ -242,8 +244,6 @@ tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr struct sockaddr_storage source_sock; char err_buf[512]; - TR_ASSERT(tr_address_is_valid(addr)); - if (!tr_address_is_valid_for_peers(addr, port)) { return TR_BAD_SOCKET; /* -EINVAL */ @@ -278,7 +278,7 @@ tr_socket_t tr_netOpenPeerSocket(tr_session* session, tr_address const* addr, tr /* set source address */ source_addr = tr_sessionGetPublicAddress(session, addr->type, NULL); - TR_ASSERT(source_addr); + TR_ASSERT(source_addr != NULL); sourcelen = setup_sockaddr(source_addr, 0, &source_sock); if (bind(s, (struct sockaddr*)&source_sock, sourcelen) == -1) @@ -330,14 +330,14 @@ struct UTPSocket* tr_netOpenPeerUTPSocket(tr_session* session, tr_address const* static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool suppressMsgs, int* errOut) { + TR_ASSERT(tr_address_is_valid(addr)); + static int const domains[NUM_TR_AF_INET_TYPES] = { AF_INET, AF_INET6 }; struct sockaddr_storage sock; tr_socket_t fd; int addrlen; int optval; - TR_ASSERT(tr_address_is_valid(addr)); - fd = socket(domains[addr->type], SOCK_STREAM, 0); if (fd == TR_BAD_SOCKET) @@ -684,10 +684,10 @@ static bool isIPv6LinkLocalAddress(tr_address const* addr) and is covered under the same license as third-party/dht/dht.c. */ static bool isMartianAddr(struct tr_address const* a) { - static unsigned char const zeroes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - TR_ASSERT(tr_address_is_valid(a)); + static unsigned char const zeroes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + switch (a->type) { case TR_AF_INET: diff --git a/libtransmission/peer-io.c b/libtransmission/peer-io.c index 26cf390ef..5e165384e 100644 --- a/libtransmission/peer-io.c +++ b/libtransmission/peer-io.c @@ -256,9 +256,13 @@ static void canReadWrapper(tr_peerIo* io) static void event_read_cb(evutil_socket_t fd, short event UNUSED, void* vio) { + tr_peerIo* io = vio; + + TR_ASSERT(tr_isPeerIo(io)); + TR_ASSERT(io->socket != TR_BAD_SOCKET); + int res; int e; - tr_peerIo* io = vio; /* Limit the input buffer to 256K, so it doesn't grow too large */ unsigned int howmuch; @@ -266,9 +270,6 @@ static void event_read_cb(evutil_socket_t fd, short event UNUSED, void* vio) tr_direction const dir = TR_DOWN; unsigned int const max = 256 * 1024; - TR_ASSERT(tr_isPeerIo(io)); - TR_ASSERT(io->socket != TR_BAD_SOCKET); - io->pendingEvents &= ~EV_READ; curlen = evbuffer_get_length(io->inbuf); @@ -341,17 +342,18 @@ static int tr_evbuffer_write(tr_peerIo* io, int fd, size_t howmuch) static void event_write_cb(evutil_socket_t fd, short event UNUSED, void* vio) { - int res = 0; - int e; - short what = BEV_EVENT_WRITING; tr_peerIo* io = vio; - size_t howmuch; - tr_direction const dir = TR_UP; - char errstr[1024]; TR_ASSERT(tr_isPeerIo(io)); TR_ASSERT(io->socket != TR_BAD_SOCKET); + int res = 0; + int e; + short what = BEV_EVENT_WRITING; + size_t howmuch; + tr_direction const dir = TR_UP; + char errstr[1024]; + io->pendingEvents &= ~EV_WRITE; dbgmsg(io, "libevent says this peer is ready to write"); @@ -435,11 +437,11 @@ static void maybeSetCongestionAlgorithm(tr_socket_t socket, char const* algorith static void utp_on_read(void* closure, unsigned char const* buf, size_t buflen) { - int rc; tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); - rc = evbuffer_add(io->inbuf, buf, buflen); + int rc = evbuffer_add(io->inbuf, buf, buflen); dbgmsg(io, "utp_on_read got %zu bytes", buflen); if (rc < 0) @@ -454,11 +456,11 @@ static void utp_on_read(void* closure, unsigned char const* buf, size_t buflen) static void utp_on_write(void* closure, unsigned char* buf, size_t buflen) { - int rc; tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); - rc = evbuffer_remove(io->outbuf, buf, buflen); + int rc = evbuffer_remove(io->outbuf, buf, buflen); dbgmsg(io, "utp_on_write sending %zu bytes... evbuffer_remove returned %d", buflen, rc); TR_ASSERT(rc == (int)buflen); /* if this fails, we've corrupted our bookkeeping somewhere */ @@ -472,11 +474,11 @@ static void utp_on_write(void* closure, unsigned char* buf, size_t buflen) static size_t utp_get_rb_size(void* closure) { - size_t bytes; tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); - bytes = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, UTP_READ_BUFFER_SIZE); + size_t bytes = tr_bandwidthClamp(&io->bandwidth, TR_DOWN, UTP_READ_BUFFER_SIZE); dbgmsg(io, "utp_get_rb_size is saying it's ready to read %zu bytes", bytes); return UTP_READ_BUFFER_SIZE - bytes; @@ -497,6 +499,7 @@ static void utp_on_writable(tr_peerIo* io) static void utp_on_state_change(void* closure, int state) { tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); if (state == UTP_STATE_CONNECT) @@ -534,6 +537,7 @@ static void utp_on_state_change(void* closure, int state) static void utp_on_error(void* closure, int errcode) { tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); dbgmsg(io, "utp_on_error -- errcode is %d", errcode); @@ -548,6 +552,7 @@ static void utp_on_error(void* closure, int errcode) static void utp_on_overhead(void* closure, uint8_t /* bool */ send, size_t count, int type UNUSED) { tr_peerIo* io = closure; + TR_ASSERT(tr_isPeerIo(io)); dbgmsg(io, "utp_on_overhead -- count is %zu", count); @@ -615,8 +620,6 @@ static struct UTPFunctionTable dummy_utp_function_table = static tr_peerIo* tr_peerIoNew(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, uint8_t const* torrentHash, bool isIncoming, bool isSeed, tr_socket_t socket, struct UTPSocket* utp_socket) { - tr_peerIo* io; - TR_ASSERT(session != NULL); TR_ASSERT(session->events != NULL); TR_ASSERT(tr_amInEventThread(session)); @@ -631,7 +634,7 @@ static tr_peerIo* tr_peerIoNew(tr_session* session, tr_bandwidth* parent, tr_add maybeSetCongestionAlgorithm(socket, session->peer_congestion_algorithm); } - io = tr_new0(tr_peerIo, 1); + tr_peerIo* io = tr_new0(tr_peerIo, 1); io->magicNumber = PEER_IO_MAGIC_NUMBER; io->refCount = 1; tr_cryptoConstruct(&io->crypto, torrentHash, isIncoming); @@ -688,13 +691,13 @@ tr_peerIo* tr_peerIoNewIncoming(tr_session* session, tr_bandwidth* parent, tr_ad tr_peerIo* tr_peerIoNewOutgoing(tr_session* session, tr_bandwidth* parent, tr_address const* addr, tr_port port, uint8_t const* torrentHash, bool isSeed, bool utp) { - tr_socket_t fd = TR_BAD_SOCKET; - struct UTPSocket* utp_socket = NULL; - TR_ASSERT(session != NULL); TR_ASSERT(tr_address_is_valid(addr)); TR_ASSERT(torrentHash != NULL); + tr_socket_t fd = TR_BAD_SOCKET; + struct UTPSocket* utp_socket = NULL; + if (utp) { utp_socket = tr_netOpenPeerUTPSocket(session, addr, port, isSeed); @@ -794,13 +797,13 @@ static void event_disable(struct tr_peerIo* io, short event) void tr_peerIoSetEnabled(tr_peerIo* io, tr_direction dir, bool isEnabled) { - short const event = dir == TR_UP ? EV_WRITE : EV_READ; - TR_ASSERT(tr_isPeerIo(io)); TR_ASSERT(tr_isDirection(dir)); TR_ASSERT(tr_amInEventThread(io->session)); TR_ASSERT(io->session->events != NULL); + short const event = dir == TR_UP ? EV_WRITE : EV_READ; + if (isEnabled) { event_enable(io, event); @@ -947,15 +950,12 @@ void tr_peerIoClear(tr_peerIo* io) int tr_peerIoReconnect(tr_peerIo* io) { - short int pendingEvents; - tr_session* session; - TR_ASSERT(tr_isPeerIo(io)); TR_ASSERT(!tr_peerIoIsIncoming(io)); - session = tr_peerIoGetSession(io); + tr_session* session = tr_peerIoGetSession(io); - pendingEvents = io->pendingEvents; + short int pendingEvents = io->pendingEvents; event_disable(io, EV_READ | EV_WRITE); io_close_socket(io); @@ -1177,14 +1177,13 @@ static inline void maybeDecryptBuffer(tr_peerIo* io, struct evbuffer* buf, size_ void tr_peerIoReadBytesToBuf(tr_peerIo* io, struct evbuffer* inbuf, struct evbuffer* outbuf, size_t byteCount) { - struct evbuffer* tmp; - size_t const old_length = evbuffer_get_length(outbuf); - TR_ASSERT(tr_isPeerIo(io)); TR_ASSERT(evbuffer_get_length(inbuf) >= byteCount); + size_t const old_length = evbuffer_get_length(outbuf); + /* append it to outbuf */ - tmp = evbuffer_new(); + struct evbuffer* tmp = evbuffer_new(); evbuffer_remove_buffer(inbuf, tmp, byteCount); evbuffer_add_buffer(outbuf, tmp); evbuffer_free(tmp); @@ -1345,11 +1344,11 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch) int tr_peerIoFlush(tr_peerIo* io, tr_direction dir, size_t limit) { - int bytesUsed = 0; - TR_ASSERT(tr_isPeerIo(io)); TR_ASSERT(tr_isDirection(dir)); + int bytesUsed = 0; + if (dir == TR_DOWN) { bytesUsed = tr_peerIoTryRead(io, limit); diff --git a/libtransmission/peer-mgr.c b/libtransmission/peer-mgr.c index 3333d7f88..ef350dfa3 100644 --- a/libtransmission/peer-mgr.c +++ b/libtransmission/peer-mgr.c @@ -413,11 +413,11 @@ static void replicationFree(tr_swarm* s) static void replicationNew(tr_swarm* s) { + TR_ASSERT(!replicationExists(s)); + tr_piece_index_t const piece_count = s->tor->info.pieceCount; int const n = tr_ptrArraySize(&s->peers); - TR_ASSERT(!replicationExists(s)); - s->pieceReplicationSize = piece_count; s->pieceReplication = tr_new0(uint16_t, piece_count); @@ -1247,12 +1247,11 @@ static void tr_incrReplicationOfPiece(tr_swarm* s, size_t const index) */ static void tr_incrReplicationFromBitfield(tr_swarm* s, tr_bitfield const* b) { - uint16_t* rep = s->pieceReplication; - size_t const n = s->tor->info.pieceCount; - TR_ASSERT(replicationExists(s)); - for (size_t i = 0; i < n; ++i) + uint16_t* rep = s->pieceReplication; + + for (size_t i = 0, n = s->tor->info.pieceCount; i < n; ++i) { if (tr_bitfieldHas(b, i)) { @@ -1326,13 +1325,13 @@ void tr_peerMgrRebuildRequests(tr_torrent* tor) void tr_peerMgrGetNextRequests(tr_torrent* tor, tr_peer* peer, int numwant, tr_block_index_t* setme, int* numgot, bool get_intervals) { - tr_swarm* s; - tr_bitfield const* const have = &peer->have; - /* sanity clause */ TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(numwant > 0); + tr_swarm* s; + tr_bitfield const* const have = &peer->have; + /* walk through the pieces and find blocks that should be requested */ s = tor->swarm; @@ -1733,12 +1732,12 @@ void tr_peerMgrPieceCompleted(tr_torrent* tor, tr_piece_index_t p) static void peerCallbackFunc(tr_peer* peer, tr_peer_event const* e, void* vs) { + TR_ASSERT(peer != NULL); + tr_swarm* s = vs; swarmLock(s); - TR_ASSERT(peer != NULL); - switch (e->eventType) { case TR_PEER_PEER_GOT_PIECE_DATA: @@ -1917,12 +1916,10 @@ static int getDefaultShelfLife(uint8_t from) static void ensureAtomExists(tr_swarm* s, tr_address const* addr, tr_port const port, uint8_t const flags, int8_t const seedProbability, uint8_t const from) { - struct peer_atom* a; - TR_ASSERT(tr_address_is_valid(addr)); TR_ASSERT(from < TR_PEER_FROM__MAX); - a = getExistingAtom(s, addr); + struct peer_atom* a = getExistingAtom(s, addr); if (a == NULL) { @@ -1968,17 +1965,13 @@ static int getPeerCount(tr_swarm const* s) static void createBitTorrentPeer(tr_torrent* tor, struct tr_peerIo* io, struct peer_atom* atom, tr_quark client) { - tr_peer* peer; - tr_peerMsgs* msgs; - tr_swarm* swarm; - TR_ASSERT(atom != NULL); TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tor->swarm != NULL); - swarm = tor->swarm; + tr_swarm* swarm = tor->swarm; - peer = (tr_peer*)tr_peerMsgsNew(tor, io, peerCallbackFunc, swarm); + tr_peer* peer = (tr_peer*)tr_peerMsgsNew(tor, io, peerCallbackFunc, swarm); peer->atom = atom; peer->client = client; atom->peer = peer; @@ -1990,7 +1983,7 @@ static void createBitTorrentPeer(tr_torrent* tor, struct tr_peerIo* io, struct p TR_ASSERT(swarm->stats.peerCount == tr_ptrArraySize(&swarm->peers)); TR_ASSERT(swarm->stats.peerFromCount[atom->fromFirst] <= swarm->stats.peerCount); - msgs = PEER_MSGS(peer); + tr_peerMsgs* msgs = PEER_MSGS(peer); tr_peerMsgsUpdateActive(msgs, TR_UP); tr_peerMsgsUpdateActive(msgs, TR_DOWN); } @@ -1999,16 +1992,14 @@ static void createBitTorrentPeer(tr_torrent* tor, struct tr_peerIo* io, struct p static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readAnythingFromPeer, bool isConnected, uint8_t const* peer_id, void* vmanager) { + TR_ASSERT(io != NULL); + bool ok = isConnected; bool success = false; tr_port port; tr_address const* addr; tr_peerMgr* manager = vmanager; - tr_swarm* s; - - TR_ASSERT(io != NULL); - - s = tr_peerIoHasTorrentHash(io) ? getExistingSwarm(manager, tr_peerIoGetTorrentHash(io)) : NULL; + tr_swarm* s = tr_peerIoHasTorrentHash(io) ? getExistingSwarm(manager, tr_peerIoGetTorrentHash(io)) : NULL; if (tr_peerIoIsIncoming(io)) { @@ -2120,12 +2111,11 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA void tr_peerMgrAddIncoming(tr_peerMgr* manager, tr_address* addr, tr_port port, tr_socket_t socket, struct UTPSocket* utp_socket) { - tr_session* session; + TR_ASSERT(tr_isSession(manager->session)); managerLock(manager); - TR_ASSERT(tr_isSession(manager->session)); - session = manager->session; + tr_session* session = manager->session; if (tr_sessionIsAddressBlocked(session, addr)) { @@ -2294,13 +2284,14 @@ void tr_peerMgrGotBadPiece(tr_torrent* tor, tr_piece_index_t pieceIndex) int tr_pexCompare(void const* va, void const* vb) { - int i; tr_pex const* a = va; tr_pex const* b = vb; TR_ASSERT(tr_isPex(a)); TR_ASSERT(tr_isPex(b)); + int i; + if ((i = tr_address_compare(&a->addr, &b->addr)) != 0) { return i; @@ -2368,6 +2359,11 @@ static bool isAtomInteresting(tr_torrent const* tor, struct peer_atom* atom) int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t list_mode, int maxCount) { + TR_ASSERT(tr_isTorrent(tor)); + TR_ASSERT(setme_pex != NULL); + TR_ASSERT(af == TR_AF_INET || af == TR_AF_INET6); + TR_ASSERT(list_mode == TR_PEERS_CONNECTED || list_mode == TR_PEERS_INTERESTING); + int n; int count = 0; int atomCount = 0; @@ -2376,11 +2372,6 @@ int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t tr_pex* pex; tr_pex* walk; - TR_ASSERT(tr_isTorrent(tor)); - TR_ASSERT(setme_pex != NULL); - TR_ASSERT(af == TR_AF_INET || af == TR_AF_INET6); - TR_ASSERT(list_mode == TR_PEERS_CONNECTED || list_mode == TR_PEERS_INTERESTING); - managerLock(s->manager); /** @@ -2429,6 +2420,7 @@ int tr_peerMgrGetPeers(tr_torrent* tor, tr_pex** setme_pex, uint8_t af, uint8_t if (atom->addr.type == af) { TR_ASSERT(tr_address_is_valid(&atom->addr)); + walk->addr = atom->addr; walk->port = atom->port; walk->flags = atom->flags; @@ -2485,12 +2477,11 @@ static void ensureMgrTimersExist(struct tr_peerMgr* m) void tr_peerMgrStartTorrent(tr_torrent* tor) { - tr_swarm* s; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_torrentIsLocked(tor)); - s = tor->swarm; + tr_swarm* s = tor->swarm; + ensureMgrTimersExist(s->manager); s->isRunning = true; @@ -2696,9 +2687,6 @@ bool tr_peerIsSeed(tr_peer const* peer) /* count how many bytes we want that connected peers have */ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) { - uint64_t desiredAvailable; - tr_swarm const* s; - TR_ASSERT(tr_isTorrent(tor)); /* common shortcuts... */ @@ -2708,7 +2696,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) return 0; } - s = tor->swarm; + tr_swarm const* s = tor->swarm; if (s == NULL || !s->isRunning) { @@ -2741,7 +2729,7 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) /* do it the hard way */ - desiredAvailable = 0; + uint64_t desiredAvailable = 0; for (size_t i = 0, n = MIN(tor->info.pieceCount, s->pieceReplicationSize); i < n; ++i) { @@ -2757,20 +2745,18 @@ uint64_t tr_peerMgrGetDesiredAvailable(tr_torrent const* tor) double* tr_peerMgrWebSpeeds_KBps(tr_torrent const* tor) { - tr_swarm* s; - unsigned int n; - double* ret = NULL; - uint64_t const now = tr_time_msec(); - TR_ASSERT(tr_isTorrent(tor)); - s = tor->swarm; - n = tr_ptrArraySize(&s->webseeds); - ret = tr_new0(double, n); + uint64_t const now = tr_time_msec(); + tr_swarm* s = tor->swarm; TR_ASSERT(s->manager != NULL); + + unsigned int n = tr_ptrArraySize(&s->webseeds); TR_ASSERT(n == tor->info.webseedCount); + double* ret = tr_new0(double, n); + for (unsigned int i = 0; i < n; ++i) { unsigned int Bps = 0; @@ -2790,20 +2776,16 @@ double* tr_peerMgrWebSpeeds_KBps(tr_torrent const* tor) struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) { - int size = 0; - tr_peer_stat* ret; - tr_swarm const* s; - tr_peer** peers; - time_t const now = tr_time(); - uint64_t const now_msec = tr_time_msec(); - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tor->swarm->manager != NULL); - s = tor->swarm; - peers = (tr_peer**)tr_ptrArrayBase(&s->peers); - size = tr_ptrArraySize(&s->peers); - ret = tr_new0(tr_peer_stat, size); + time_t const now = tr_time(); + uint64_t const now_msec = tr_time_msec(); + + tr_swarm const* s = tor->swarm; + tr_peer** peers = (tr_peer**)tr_ptrArrayBase(&s->peers); + int size = tr_ptrArraySize(&s->peers); + tr_peer_stat* ret = tr_new0(tr_peer_stat, size); for (int i = 0; i < size; ++i) { @@ -2912,12 +2894,12 @@ struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) void tr_peerMgrClearInterest(tr_torrent* tor) { - tr_swarm* s = tor->swarm; - int const peerCount = tr_ptrArraySize(&s->peers); - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_torrentIsLocked(tor)); + tr_swarm* s = tor->swarm; + int const peerCount = tr_ptrArraySize(&s->peers); + for (int i = 0; i < peerCount; ++i) { tr_peerMsgsSetInterested(tr_ptrArrayNth(&s->peers, i), false); @@ -3233,6 +3215,8 @@ static inline bool isBandwidthMaxedOut(tr_bandwidth const* b, uint64_t const now static void rechokeUploads(tr_swarm* s, uint64_t const now) { + TR_ASSERT(swarmIsLocked(s)); + int const peerCount = tr_ptrArraySize(&s->peers); tr_peer** peers = (tr_peer**)tr_ptrArrayBase(&s->peers); struct ChokeData* choke = tr_new0(struct ChokeData, peerCount); @@ -3240,8 +3224,6 @@ static void rechokeUploads(tr_swarm* s, uint64_t const now) bool const chokeAll = !tr_torrentIsPieceTransferAllowed(s->tor, TR_CLIENT_TO_PEER); bool const isMaxedOut = isBandwidthMaxedOut(&s->tor->bandwidth, now, TR_UP); - TR_ASSERT(swarmIsLocked(s)); - /* an optimistic unchoke peer's "optimistic" * state lasts for N calls to rechokeUploads(). */ if (s->optimisticUnchokeTimeScaler > 0) @@ -3437,13 +3419,13 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC static tr_peer** getPeersToClose(tr_swarm* s, time_t const now_sec, int* setmeSize) { + TR_ASSERT(swarmIsLocked(s)); + int peerCount; int outsize = 0; struct tr_peer** ret = NULL; tr_peer** peers = (tr_peer**)tr_ptrArrayPeek(&s->peers, &peerCount); - TR_ASSERT(swarmIsLocked(s)); - for (int i = 0; i < peerCount; ++i) { if (shouldPeerBeClosed(s, peers[i], peerCount, now_sec)) @@ -3523,9 +3505,9 @@ static int getReconnectIntervalSecs(struct peer_atom const* atom, time_t const n static void removePeer(tr_swarm* s, tr_peer* peer) { - struct peer_atom* atom = peer->atom; - TR_ASSERT(swarmIsLocked(s)); + + struct peer_atom* atom = peer->atom; TR_ASSERT(atom != NULL); atom->time = tr_time(); @@ -3547,12 +3529,10 @@ static void removePeer(tr_swarm* s, tr_peer* peer) static void closePeer(tr_swarm* s, tr_peer* peer) { - struct peer_atom* atom; - TR_ASSERT(s != NULL); TR_ASSERT(peer != NULL); - atom = peer->atom; + struct peer_atom* atom = peer->atom; /* if we transferred piece data, then they might be good peers, so reset their `numFails' weight to zero. otherwise we connected @@ -3925,25 +3905,24 @@ static int compareAtomPtrsByAddress(void const* va, void const* vb) /* best come first, worst go last */ static int compareAtomPtrsByShelfDate(void const* va, void const* vb) { - time_t atime; - time_t btime; struct peer_atom const* a = *(struct peer_atom const* const*)va; struct peer_atom const* b = *(struct peer_atom const* const*)vb; - int const data_time_cutoff_secs = 60 * 60; - time_t const tr_now = tr_time(); TR_ASSERT(tr_isAtom(a)); TR_ASSERT(tr_isAtom(b)); + int const data_time_cutoff_secs = 60 * 60; + time_t const tr_now = tr_time(); + /* primary key: the last piece data time *if* it was within the last hour */ - atime = a->piece_data_time; + time_t atime = a->piece_data_time; if (atime + data_time_cutoff_secs < tr_now) { atime = 0; } - btime = b->piece_data_time; + time_t btime = b->piece_data_time; if (btime + data_time_cutoff_secs < tr_now) { diff --git a/libtransmission/peer-msgs.c b/libtransmission/peer-msgs.c index 84e30e4af..d347de134 100644 --- a/libtransmission/peer-msgs.c +++ b/libtransmission/peer-msgs.c @@ -316,10 +316,10 @@ static void dbgOutMessageLen(tr_peerMsgs* msgs) static void protocolSendReject(tr_peerMsgs* msgs, struct peer_request const* req) { - struct evbuffer* out = msgs->outMessages; - TR_ASSERT(tr_peerIoSupportsFEXT(msgs->io)); + struct evbuffer* out = msgs->outMessages; + evbuffer_add_uint32(out, sizeof(uint8_t) + 3 * sizeof(uint32_t)); evbuffer_add_uint8(out, BT_FEXT_REJECT); evbuffer_add_uint32(out, req->index); @@ -387,11 +387,11 @@ static void protocolSendHave(tr_peerMsgs* msgs, uint32_t index) static void protocolSendAllowedFast(tr_peerMsgs* msgs, uint32_t pieceIndex) { + TR_ASSERT(tr_peerIoSupportsFEXT(msgs->io)); + tr_peerIo* io = msgs->io; struct evbuffer* out = msgs->outMessages; - TR_ASSERT(tr_peerIoSupportsFEXT(msgs->io)); - evbuffer_add_uint32(io, out, sizeof(uint8_t) + sizeof(uint32_t)); evbuffer_add_uint8(io, out, BT_FEXT_ALLOWED_FAST); evbuffer_add_uint32(io, out, pieceIndex); @@ -416,10 +416,10 @@ static void protocolSendChoke(tr_peerMsgs* msgs, int choke) static void protocolSendHaveAll(tr_peerMsgs* msgs) { - struct evbuffer* out = msgs->outMessages; - TR_ASSERT(tr_peerIoSupportsFEXT(msgs->io)); + struct evbuffer* out = msgs->outMessages; + evbuffer_add_uint32(out, sizeof(uint8_t)); evbuffer_add_uint8(out, BT_FEXT_HAVE_ALL); @@ -430,10 +430,10 @@ static void protocolSendHaveAll(tr_peerMsgs* msgs) static void protocolSendHaveNone(tr_peerMsgs* msgs) { - struct evbuffer* out = msgs->outMessages; - TR_ASSERT(tr_peerIoSupportsFEXT(msgs->io)); + struct evbuffer* out = msgs->outMessages; + evbuffer_add_uint32(out, sizeof(uint8_t)); evbuffer_add_uint8(out, BT_FEXT_HAVE_NONE); @@ -569,8 +569,6 @@ static void fireClientGotHave(tr_peerMsgs* msgs, tr_piece_index_t index) size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSize, size_t pieceCount, uint8_t const* infohash, tr_address const* addr) { - size_t setSize = 0; - TR_ASSERT(setmePieces != NULL); TR_ASSERT(desiredSetSize <= pieceCount); TR_ASSERT(desiredSetSize != 0); @@ -578,6 +576,8 @@ size_t tr_generateAllowedSet(tr_piece_index_t* setmePieces, size_t desiredSetSiz TR_ASSERT(infohash != NULL); TR_ASSERT(addr != NULL); + size_t setSize = 0; + if (addr->type == TR_AF_INET) { uint8_t w[SHA_DIGEST_LENGTH + 4]; @@ -650,11 +650,11 @@ static void updateFastSet(tr_peerMsgs* msgs UNUSED) static bool tr_peerMsgsCalculateActive(tr_peerMsgs const* msgs, tr_direction direction) { - bool is_active; - TR_ASSERT(tr_isPeerMsgs(msgs)); TR_ASSERT(tr_isDirection(direction)); + bool is_active; + if (direction == TR_CLIENT_TO_PEER) { is_active = tr_peerMsgsIsPeerInterested(msgs) && !tr_peerMsgsIsPeerChoked(msgs); @@ -688,12 +688,10 @@ static bool tr_peerMsgsCalculateActive(tr_peerMsgs const* msgs, tr_direction dir bool tr_peerMsgsIsActive(tr_peerMsgs const* msgs, tr_direction direction) { - bool is_active; - TR_ASSERT(tr_isPeerMsgs(msgs)); TR_ASSERT(tr_isDirection(direction)); - is_active = msgs->is_active[direction]; + bool is_active = msgs->is_active[direction]; TR_ASSERT(is_active == tr_peerMsgsCalculateActive(msgs, direction)); @@ -725,10 +723,10 @@ void tr_peerMsgsUpdateActive(tr_peerMsgs* msgs, tr_direction direction) static void sendInterest(tr_peerMsgs* msgs, bool b) { - struct evbuffer* out = msgs->outMessages; - TR_ASSERT(msgs != NULL); + struct evbuffer* out = msgs->outMessages; + msgs->client_is_interested = b; dbgmsg(msgs, "Sending %s", b ? "Interested" : "Not Interested"); evbuffer_add_uint32(out, sizeof(uint8_t)); @@ -797,11 +795,11 @@ static void cancelAllRequestsToClient(tr_peerMsgs* msgs) void tr_peerMsgsSetChoke(tr_peerMsgs* msgs, bool peer_is_choked) { + TR_ASSERT(msgs != NULL); + time_t const now = tr_time(); time_t const fibrillationTime = now - MIN_CHOKE_PERIOD_SEC; - TR_ASSERT(msgs != NULL); - if (msgs->chokeChangedAt > fibrillationTime) { dbgmsg(msgs, "Not changing choke to %d to avoid fibrillation", peer_is_choked); @@ -1224,10 +1222,10 @@ static void sendPex(tr_peerMsgs* msgs); static void parseLtep(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbuf) { - uint8_t ltep_msgid; - TR_ASSERT(msglen > 0); + uint8_t ltep_msgid; + tr_peerIoReadUint8(msgs->io, inbuf, <ep_msgid); msglen--; @@ -1439,11 +1437,12 @@ static int clientGotBlock(tr_peerMsgs* msgs, struct evbuffer* block, struct peer static int readBtPiece(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen, size_t* setme_piece_bytes_read) { - struct peer_request* req = &msgs->incoming.blockReq; - TR_ASSERT(evbuffer_get_length(inbuf) >= inlen); + dbgmsg(msgs, "In readBtPiece"); + struct peer_request* req = &msgs->incoming.blockReq; + if (req->length == 0) { if (inlen < 8) @@ -1502,14 +1501,15 @@ static void updateDesiredRequestCount(tr_peerMsgs* msgs); static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen) { - uint32_t ui32; - uint32_t msglen = msgs->incoming.length; uint8_t const id = msgs->incoming.id; #ifdef TR_ENABLE_ASSERTS size_t const startBufLen = evbuffer_get_length(inbuf); #endif bool const fext = tr_peerIoSupportsFEXT(msgs->io); + uint32_t ui32; + uint32_t msglen = msgs->incoming.length; + TR_ASSERT(msglen > 0); --msglen; /* id length */ @@ -1752,13 +1752,13 @@ static int readBtMessage(tr_peerMsgs* msgs, struct evbuffer* inbuf, size_t inlen /* returns 0 on success, or an errno on failure */ static int clientGotBlock(tr_peerMsgs* msgs, struct evbuffer* data, struct peer_request const* req) { + TR_ASSERT(msgs != NULL); + TR_ASSERT(req != NULL); + int err; tr_torrent* tor = msgs->torrent; tr_block_index_t const block = _tr_block(tor, req->index, req->offset); - TR_ASSERT(msgs != NULL); - TR_ASSERT(req != NULL); - if (!requestIsValid(msgs, req)) { dbgmsg(msgs, "dropping invalid block %u:%u->%u", req->index, req->offset, req->length); @@ -1961,13 +1961,13 @@ static void updateBlockRequests(tr_peerMsgs* msgs) if (tr_torrentIsPieceTransferAllowed(msgs->torrent, TR_PEER_TO_CLIENT) && msgs->desiredRequestCount > 0 && msgs->peer.pendingReqsToPeer <= msgs->desiredRequestCount * 0.66) { + TR_ASSERT(tr_peerMsgsIsClientInterested(msgs)); + TR_ASSERT(!tr_peerMsgsIsClientChoked(msgs)); + int n; tr_block_index_t* blocks; int const numwant = msgs->desiredRequestCount - msgs->peer.pendingReqsToPeer; - TR_ASSERT(tr_peerMsgsIsClientInterested(msgs)); - TR_ASSERT(!tr_peerMsgsIsClientChoked(msgs)); - blocks = tr_new(tr_block_index_t, numwant); tr_peerMgrGetNextRequests(msgs->torrent, &msgs->peer, numwant, blocks, &n, false); @@ -2215,12 +2215,12 @@ static void gotError(tr_peerIo* io UNUSED, short what, void* vmsgs) static void sendBitfield(tr_peerMsgs* msgs) { + TR_ASSERT(tr_torrentHasMetadata(msgs->torrent)); + void* bytes; size_t byte_count = 0; struct evbuffer* out = msgs->outMessages; - TR_ASSERT(tr_torrentHasMetadata(msgs->torrent)); - bytes = tr_torrentCreatePieceBitfield(msgs->torrent, &byte_count); evbuffer_add_uint32(out, sizeof(uint8_t) + byte_count); evbuffer_add_uint8(out, BT_BITFIELD); @@ -2689,11 +2689,9 @@ tr_peerMsgs* tr_peerMsgsCast(void* vm) tr_peerMsgs* tr_peerMsgsNew(struct tr_torrent* torrent, struct tr_peerIo* io, tr_peer_callback callback, void* callbackData) { - tr_peerMsgs* m; - TR_ASSERT(io != NULL); - m = tr_new0(tr_peerMsgs, 1); + tr_peerMsgs* m = tr_new0(tr_peerMsgs, 1); tr_peerConstruct(&m->peer, torrent); m->peer.funcs = &my_funcs; diff --git a/libtransmission/platform.c b/libtransmission/platform.c index 76ec41f7f..4a8de7c4f 100644 --- a/libtransmission/platform.c +++ b/libtransmission/platform.c @@ -193,6 +193,7 @@ void tr_lockLock(tr_lock* l) TR_ASSERT(l->depth >= 0); TR_ASSERT(l->depth == 0 || tr_areThreadsEqual(l->lockThread, tr_getCurrentThread())); + l->lockThread = tr_getCurrentThread(); ++l->depth; } diff --git a/libtransmission/ptrarray.c b/libtransmission/ptrarray.c index 24d91912a..84eb01279 100644 --- a/libtransmission/ptrarray.c +++ b/libtransmission/ptrarray.c @@ -228,19 +228,20 @@ static void* tr_ptrArrayRemoveSortedValue(tr_ptrArray* t, void const* ptr, int ( tr_ptrArrayErase(t, pos, pos + 1); } - TR_ASSERT((ret == NULL) || (compare(ret, ptr) == 0)); + TR_ASSERT(ret == NULL || compare(ret, ptr) == 0); return ret; } void tr_ptrArrayRemoveSortedPointer(tr_ptrArray* t, void const* ptr, int (* compare)(void const*, void const*)) { + void* removed = tr_ptrArrayRemoveSortedValue(t, ptr, compare); + #ifndef TR_ENABLE_ASSERTS - tr_ptrArrayRemoveSortedValue(t, ptr, compare); + (void)removed; #else - void* removed = tr_ptrArrayRemoveSortedValue(t, ptr, compare); TR_ASSERT(removed != NULL); TR_ASSERT(removed == ptr); TR_ASSERT(tr_ptrArrayFindSorted(t, ptr, compare) == NULL); diff --git a/libtransmission/quark.c b/libtransmission/quark.c index d079996fd..861050057 100644 --- a/libtransmission/quark.c +++ b/libtransmission/quark.c @@ -422,13 +422,14 @@ static tr_ptrArray my_runtime = TR_PTR_ARRAY_INIT_STATIC; bool tr_quark_lookup(void const* str, size_t len, tr_quark* setme) { - struct tr_key_struct tmp; - struct tr_key_struct* match; static size_t const n_static = TR_N_ELEMENTS(my_static); - bool success = false; TR_ASSERT(n_static == TR_N_KEYS); + struct tr_key_struct tmp; + struct tr_key_struct* match; + bool success = false; + tmp.str = str; tmp.len = len; diff --git a/libtransmission/rename-test.c b/libtransmission/rename-test.c index d84d37e8d..44dd98e50 100644 --- a/libtransmission/rename-test.c +++ b/libtransmission/rename-test.c @@ -49,12 +49,10 @@ static bool testFileExistsAndConsistsOfThisString(tr_torrent const* tor, tr_file if (path != NULL) { - uint8_t* contents; - size_t contents_len; - TR_ASSERT(tr_sys_path_exists(path, NULL)); - contents = tr_loadFile(path, &contents_len, NULL); + size_t contents_len; + uint8_t* contents = tr_loadFile(path, &contents_len, NULL); success = contents != NULL && str_len == contents_len && memcmp(contents, str, contents_len) == 0; diff --git a/libtransmission/resume.c b/libtransmission/resume.c index ca94e4e38..82b1f8f07 100644 --- a/libtransmission/resume.c +++ b/libtransmission/resume.c @@ -750,6 +750,8 @@ void tr_torrentSaveResume(tr_torrent* tor) static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad) { + TR_ASSERT(tr_isTorrent(tor)); + size_t len; int64_t i; char const* str; @@ -760,8 +762,6 @@ static uint64_t loadFromFile(tr_torrent* tor, uint64_t fieldsToLoad) bool const wasDirty = tor->isDirty; tr_error* error = NULL; - TR_ASSERT(tr_isTorrent(tor)); - filename = getResumeFilename(tor); if (!tr_variantFromFile(&top, TR_VARIANT_FMT_BENC, filename, &error)) @@ -977,10 +977,10 @@ static uint64_t useFallbackFields(tr_torrent* tor, uint64_t fields, tr_ctor cons uint64_t tr_torrentLoadResume(tr_torrent* tor, uint64_t fieldsToLoad, tr_ctor const* ctor) { - uint64_t ret = 0; - TR_ASSERT(tr_isTorrent(tor)); + uint64_t ret = 0; + ret |= useManditoryFields(tor, fieldsToLoad, ctor); fieldsToLoad &= ~ret; ret |= loadFromFile(tor, fieldsToLoad); diff --git a/libtransmission/rpcimpl.c b/libtransmission/rpcimpl.c index 709c04e60..480d138c3 100644 --- a/libtransmission/rpcimpl.c +++ b/libtransmission/rpcimpl.c @@ -248,12 +248,11 @@ static int compareTorrentByQueuePosition(void const* va, void const* vb) static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); + qsort(torrents, torrentCount, sizeof(tr_torrent*), compareTorrentByQueuePosition); for (int i = 0; i < torrentCount; ++i) @@ -274,12 +273,11 @@ static char const* torrentStart(tr_session* session, tr_variant* args_in, tr_var static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); + qsort(torrents, torrentCount, sizeof(tr_torrent*), compareTorrentByQueuePosition); for (int i = 0; i < torrentCount; ++i) @@ -300,12 +298,10 @@ static char const* torrentStartNow(tr_session* session, tr_variant* args_in, tr_ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); for (int i = 0; i < torrentCount; ++i) { @@ -325,21 +321,19 @@ static char const* torrentStop(tr_session* session, tr_variant* args_in, tr_vari static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_rpc_callback_type type; - bool deleteFlag; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); + bool deleteFlag; + if (!tr_variantDictFindBool(args_in, TR_KEY_delete_local_data, &deleteFlag)) { deleteFlag = false; } - type = deleteFlag ? TR_RPC_TORRENT_TRASHING : TR_RPC_TORRENT_REMOVING; + tr_rpc_callback_type type = deleteFlag ? TR_RPC_TORRENT_TRASHING : TR_RPC_TORRENT_REMOVING; - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); for (int i = 0; i < torrentCount; ++i) { @@ -359,12 +353,10 @@ static char const* torrentRemove(tr_session* session, tr_variant* args_in, tr_va static char const* torrentReannounce(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); for (int i = 0; i < torrentCount; ++i) { @@ -384,12 +376,10 @@ static char const* torrentReannounce(tr_session* session, tr_variant* args_in, t static char const* torrentVerify(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); for (int i = 0; i < torrentCount; ++i) { @@ -887,6 +877,8 @@ static void addInfo(tr_torrent* tor, tr_variant* d, tr_variant* fields) static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_variant* args_out, struct tr_rpc_idle_data* idle_data UNUSED) { + TR_ASSERT(idle_data == NULL); + int torrentCount; tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); tr_variant* list = tr_variantDictAddList(args_out, TR_KEY_torrents, torrentCount); @@ -894,8 +886,6 @@ static char const* torrentGet(tr_session* session, tr_variant* args_in, tr_varia char const* strVal; char const* errmsg = NULL; - TR_ASSERT(idle_data == NULL); - if (tr_variantDictFindStr(args_in, TR_KEY_ids, &strVal, NULL) && strcmp(strVal, "recently-active") == 0) { int n = 0; @@ -1224,13 +1214,12 @@ static char const* removeTrackers(tr_torrent* tor, tr_variant* ids) static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - int torrentCount; - tr_torrent** torrents; - char const* errmsg = NULL; - TR_ASSERT(idle_data == NULL); - torrents = getTorrents(session, args_in, &torrentCount); + int torrentCount; + tr_torrent** torrents = getTorrents(session, args_in, &torrentCount); + + char const* errmsg = NULL; for (int i = 0; i < torrentCount; ++i) { @@ -1356,10 +1345,10 @@ static char const* torrentSet(tr_session* session, tr_variant* args_in, tr_varia static char const* torrentSetLocation(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data UNUSED) { - char const* location = NULL; - TR_ASSERT(idle_data == NULL); + char const* location = NULL; + if (!tr_variantDictFindStr(args_in, TR_KEY_location, &location, NULL)) { return "no location"; @@ -1711,11 +1700,11 @@ static tr_file_index_t* fileListFromList(tr_variant* list, tr_file_index_t* setm static char const* torrentAdd(tr_session* session, tr_variant* args_in, tr_variant* args_out UNUSED, struct tr_rpc_idle_data* idle_data) { + TR_ASSERT(idle_data != NULL); + char const* filename = NULL; char const* metainfo_base64 = NULL; - TR_ASSERT(idle_data != NULL); - tr_variantDictFindStr(args_in, TR_KEY_filename, &filename, NULL); tr_variantDictFindStr(args_in, TR_KEY_metainfo, &metainfo_base64, NULL); @@ -2103,6 +2092,8 @@ static char const* sessionSet(tr_session* session, tr_variant* args_in, tr_varia static char const* sessionStats(tr_session* session, tr_variant* args_in UNUSED, tr_variant* args_out, struct tr_rpc_idle_data* idle_data UNUSED) { + TR_ASSERT(idle_data == NULL); + int running = 0; int total = 0; tr_variant* d; @@ -2110,8 +2101,6 @@ static char const* sessionStats(tr_session* session, tr_variant* args_in UNUSED, tr_session_stats cumulativeStats = { 0.0f, 0, 0, 0, 0, 0 }; tr_torrent* tor = NULL; - TR_ASSERT(idle_data == NULL); - while ((tor = tr_torrentNext(session, tor)) != NULL) { ++total; @@ -2376,10 +2365,10 @@ static void addSessionField(tr_session* s, tr_variant* d, tr_quark key) static char const* sessionGet(tr_session* s, tr_variant* args_in, tr_variant* args_out, struct tr_rpc_idle_data* idle_data UNUSED) { - tr_variant* fields; - TR_ASSERT(idle_data == NULL); + tr_variant* fields; + if (tr_variantDictFindList(args_in, TR_KEY_fields, &fields)) { size_t const field_count = tr_variantListSize(fields); diff --git a/libtransmission/session.c b/libtransmission/session.c index 2d487e4d5..e9a5f6d0f 100644 --- a/libtransmission/session.c +++ b/libtransmission/session.c @@ -468,14 +468,14 @@ void tr_sessionGetSettings(tr_session* s, tr_variant* d) bool tr_sessionLoadSettings(tr_variant* dict, char const* configDir, char const* appName) { + TR_ASSERT(tr_variantIsDict(dict)); + char* filename; tr_variant oldDict; tr_variant fileSettings; bool success; tr_error* error = NULL; - TR_ASSERT(tr_variantIsDict(dict)); - /* initializing the defaults: caller may have passed in some app-level defaults. * preserve those and use the session defaults to fill in any missing gaps. */ oldDict = *dict; @@ -512,11 +512,11 @@ bool tr_sessionLoadSettings(tr_variant* dict, char const* configDir, char const* void tr_sessionSaveSettings(tr_session* session, char const* configDir, tr_variant const* clientSettings) { + TR_ASSERT(tr_variantIsDict(clientSettings)); + tr_variant settings; char* filename = tr_buildPath(configDir, "settings.json", NULL); - TR_ASSERT(tr_variantIsDict(clientSettings)); - tr_variantInitDict(&settings, 0); /* the existing file settings are the fallback values */ @@ -596,12 +596,12 @@ struct init_data tr_session* tr_sessionInit(char const* configDir, bool messageQueuingEnabled, tr_variant* clientSettings) { + TR_ASSERT(tr_variantIsDict(clientSettings)); + int64_t i; tr_session* session; struct init_data data; - TR_ASSERT(tr_variantIsDict(clientSettings)); - tr_timeUpdate(time(NULL)); /* initialize the bare skeleton of the session object */ @@ -646,17 +646,18 @@ static void turtleCheckClock(tr_session* s, struct tr_turtle_info* t); static void onNowTimer(evutil_socket_t foo UNUSED, short bar UNUSED, void* vsession) { + tr_session* session = vsession; + + TR_ASSERT(tr_isSession(session)); + TR_ASSERT(session->nowTimer != NULL); + int usec; int const min = 100; int const max = 999999; struct timeval tv; tr_torrent* tor = NULL; - tr_session* session = vsession; time_t const now = time(NULL); - TR_ASSERT(tr_isSession(session)); - TR_ASSERT(session->nowTimer != NULL); - /** *** tr_session things to do once per second **/ @@ -711,7 +712,6 @@ static void loadBlocklists(tr_session* session); static void tr_sessionInitImpl(void* vdata) { - tr_variant settings; struct init_data* data = vdata; tr_variant* clientSettings = data->clientSettings; tr_session* session = data->session; @@ -721,6 +721,8 @@ static void tr_sessionInitImpl(void* vdata) dbgmsg("tr_sessionInit: the session's top-level bandwidth object is %p", (void*)&session->bandwidth); + tr_variant settings; + tr_variantInitDict(&settings, 0); tr_sessionGetDefaultSettings(&settings); tr_variantMergeDicts(&settings, clientSettings); @@ -785,20 +787,21 @@ static void setPeerPort(tr_session* session, tr_port port); static void sessionSetImpl(void* vdata) { + struct init_data* data = vdata; + tr_session* session = data->session; + tr_variant* settings = data->clientSettings; + + TR_ASSERT(tr_isSession(session)); + TR_ASSERT(tr_variantIsDict(settings)); + TR_ASSERT(tr_amInEventThread(session)); + int64_t i; double d; bool boolVal; char const* str; struct tr_bindinfo b; - struct init_data* data = vdata; - tr_session* session = data->session; - tr_variant* settings = data->clientSettings; struct tr_turtle_info* turtle = &session->turtle; - TR_ASSERT(tr_isSession(session)); - TR_ASSERT(tr_variantIsDict(settings)); - TR_ASSERT(tr_amInEventThread(session)); - if (tr_variantDictFindInt(settings, TR_KEY_message_level, &i)) { tr_logSetLevel(i); @@ -1150,10 +1153,10 @@ void tr_sessionSet(tr_session* session, tr_variant* settings) void tr_sessionSetDownloadDir(tr_session* session, char const* dir) { - struct tr_device_info* info = NULL; - TR_ASSERT(tr_isSession(session)); + struct tr_device_info* info = NULL; + if (dir != NULL) { info = tr_device_info_create(dir); @@ -1165,10 +1168,10 @@ void tr_sessionSetDownloadDir(tr_session* session, char const* dir) char const* tr_sessionGetDownloadDir(tr_session const* session) { - char const* dir = NULL; - TR_ASSERT(tr_isSession(session)); + char const* dir = NULL; + if (session != NULL && session->downloadDir != NULL) { dir = session->downloadDir->path; @@ -1277,10 +1280,10 @@ bool tr_sessionIsLocked(tr_session const* session) static void peerPortChanged(void* session) { - tr_torrent* tor = NULL; - TR_ASSERT(tr_isSession(session)); + tr_torrent* tor = NULL; + close_incoming_peer_port(session); open_incoming_peer_port(session); tr_sharedPortChanged(session); @@ -1491,13 +1494,14 @@ static void turtleUpdateTable(struct tr_turtle_info* t) static void altSpeedToggled(void* vsession) { tr_session* session = vsession; - struct tr_turtle_info* t = &session->turtle; TR_ASSERT(tr_isSession(session)); updateBandwidth(session, TR_UP); updateBandwidth(session, TR_DOWN); + struct tr_turtle_info* t = &session->turtle; + if (t->callback != NULL) { (*t->callback)(session, t->isEnabled, t->changedByUser, t->callbackUserData); @@ -1545,15 +1549,11 @@ static inline tr_auto_switch_state_t autoSwitchState(bool enabled) static void turtleCheckClock(tr_session* s, struct tr_turtle_info* t) { - bool enabled; - bool alreadySwitched; - tr_auto_switch_state_t newAutoTurtleState; - TR_ASSERT(t->isClockEnabled); - enabled = getInTurtleTime(t); - newAutoTurtleState = autoSwitchState(enabled); - alreadySwitched = t->autoTurtleState == newAutoTurtleState; + bool enabled = getInTurtleTime(t); + tr_auto_switch_state_t newAutoTurtleState = autoSwitchState(enabled); + bool alreadySwitched = t->autoTurtleState == newAutoTurtleState; if (!alreadySwitched) { @@ -1684,10 +1684,10 @@ static void userPokedTheClock(tr_session* s, struct tr_turtle_info* t) void tr_sessionUseAltSpeedTime(tr_session* s, bool b) { - struct tr_turtle_info* t = &s->turtle; - TR_ASSERT(tr_isSession(s)); + struct tr_turtle_info* t = &s->turtle; + if (t->isClockEnabled != b) { t->isClockEnabled = b; @@ -1875,18 +1875,14 @@ int tr_sessionCountTorrents(tr_session const* session) tr_torrent** tr_sessionGetTorrents(tr_session* session, int* setme_n) { - int n; - tr_torrent** torrents; - tr_torrent* tor; - TR_ASSERT(tr_isSession(session)); TR_ASSERT(setme_n != NULL); - n = tr_sessionCountTorrents(session); + int n = tr_sessionCountTorrents(session); *setme_n = n; - torrents = tr_new(tr_torrent*, n); - tor = NULL; + tr_torrent** torrents = tr_new(tr_torrent*, n); + tr_torrent* tor = NULL; for (int i = 0; i < n; ++i) { @@ -2032,10 +2028,10 @@ static int deadlineReached(time_t const deadline) void tr_sessionClose(tr_session* session) { - time_t const deadline = time(NULL) + SHUTDOWN_MAX_SECONDS; - TR_ASSERT(tr_isSession(session)); + time_t const deadline = time(NULL) + SHUTDOWN_MAX_SECONDS; + dbgmsg("shutting down transmission session %p... now is %zu, deadline is %zu", (void*)session, (size_t)time(NULL), (size_t)deadline); @@ -2120,16 +2116,17 @@ struct sessionLoadTorrentsData static void sessionLoadTorrents(void* vdata) { + struct sessionLoadTorrentsData* data = vdata; + + TR_ASSERT(tr_isSession(data->session)); + int i; int n = 0; tr_sys_path_info info; tr_sys_dir_t odir = NULL; tr_list* list = NULL; - struct sessionLoadTorrentsData* data = vdata; char const* dirname = tr_getTorrentDir(data->session); - TR_ASSERT(tr_isSession(data->session)); - tr_ctorSetSave(data->ctor, false); /* since we already have them */ if (tr_sys_path_get_info(dirname, 0, &info, NULL) && info.type == TR_SYS_PATH_IS_DIRECTORY && @@ -2236,6 +2233,7 @@ bool tr_sessionIsDHTEnabled(tr_session const* session) static void toggleDHTImpl(void* data) { tr_session* session = data; + TR_ASSERT(tr_isSession(session)); tr_udpUninit(session); @@ -2299,6 +2297,7 @@ void tr_sessionSetUTPEnabled(tr_session* session, bool enabled) static void toggleLPDImpl(void* data) { tr_session* session = data; + TR_ASSERT(tr_isSession(session)); if (session->isLPDEnabled) @@ -2530,10 +2529,10 @@ void tr_sessionReloadBlocklists(tr_session* session) int tr_blocklistGetRuleCount(tr_session const* session) { - int n = 0; - TR_ASSERT(tr_isSession(session)); + int n = 0; + for (tr_list* l = session->blocklists; l != NULL; l = l->next) { n += tr_blocklistFileGetRuleCount(l->data); @@ -2631,6 +2630,8 @@ char const* tr_blocklistGetURL(tr_session const* session) static void metainfoLookupInit(tr_session* session) { + TR_ASSERT(tr_isSession(session)); + tr_sys_path_info info; char const* dirname = tr_getTorrentDir(session); tr_sys_dir_t odir; @@ -2638,8 +2639,6 @@ static void metainfoLookupInit(tr_session* session) tr_variant* lookup; int n = 0; - TR_ASSERT(tr_isSession(session)); - /* walk through the directory and find the mappings */ lookup = tr_new0(tr_variant, 1); tr_variantInitDict(lookup, 0); @@ -2966,19 +2965,14 @@ static int compareTorrentAndPositions(void const* va, void const* vb) void tr_sessionGetNextQueuedTorrents(tr_session* session, tr_direction direction, size_t num_wanted, tr_ptrArray* setme) { - size_t n; - tr_torrent* tor; - struct TorrentAndPosition* candidates; - size_t num_candidates; - TR_ASSERT(tr_isSession(session)); TR_ASSERT(tr_isDirection(direction)); /* build an array of the candidates */ - n = tr_sessionCountTorrents(session); - candidates = tr_new(struct TorrentAndPosition, n); - num_candidates = 0; - tor = NULL; + size_t n = tr_sessionCountTorrents(session); + struct TorrentAndPosition* candidates = tr_new(struct TorrentAndPosition, n); + size_t num_candidates = 0; + tr_torrent* tor = NULL; while ((tor = tr_torrentNext(session, tor)) != NULL) { diff --git a/libtransmission/torrent-ctor.c b/libtransmission/torrent-ctor.c index 63694228a..6e56f4879 100644 --- a/libtransmission/torrent-ctor.c +++ b/libtransmission/torrent-ctor.c @@ -310,36 +310,30 @@ bool tr_ctorGetSave(tr_ctor const* ctor) void tr_ctorSetPaused(tr_ctor* ctor, tr_ctorMode mode, bool isPaused) { - struct optional_args* args; - TR_ASSERT(ctor != NULL); TR_ASSERT(mode == TR_FALLBACK || mode == TR_FORCE); - args = &ctor->optionalArgs[mode]; + struct optional_args* args = &ctor->optionalArgs[mode]; args->isSet_paused = true; args->isPaused = isPaused; } void tr_ctorSetPeerLimit(tr_ctor* ctor, tr_ctorMode mode, uint16_t peerLimit) { - struct optional_args* args; - TR_ASSERT(ctor != NULL); TR_ASSERT(mode == TR_FALLBACK || mode == TR_FORCE); - args = &ctor->optionalArgs[mode]; + struct optional_args* args = &ctor->optionalArgs[mode]; args->isSet_connected = true; args->peerLimit = peerLimit; } void tr_ctorSetDownloadDir(tr_ctor* ctor, tr_ctorMode mode, char const* directory) { - struct optional_args* args; - TR_ASSERT(ctor != NULL); TR_ASSERT(mode == TR_FALLBACK || mode == TR_FORCE); - args = &ctor->optionalArgs[mode]; + struct optional_args* args = &ctor->optionalArgs[mode]; tr_free(args->downloadDir); args->downloadDir = NULL; args->isSet_downloadDir = false; diff --git a/libtransmission/torrent-magnet.c b/libtransmission/torrent-magnet.c index b9fa34159..8edd40489 100644 --- a/libtransmission/torrent-magnet.c +++ b/libtransmission/torrent-magnet.c @@ -156,12 +156,12 @@ static void ensureInfoDictOffsetIsCached(tr_torrent* tor) void* tr_torrentGetMetadataPiece(tr_torrent* tor, int piece, size_t* len) { - char* ret = NULL; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(piece >= 0); TR_ASSERT(len != NULL); + char* ret = NULL; + if (tr_torrentHasMetadata(tor)) { tr_sys_file_t fd; @@ -207,9 +207,6 @@ void* tr_torrentGetMetadataPiece(tr_torrent* tor, int piece, size_t* len) void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, int len) { - struct tr_incomplete_metadata* m; - int const offset = piece * METADATA_PIECE_SIZE; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(data != NULL); TR_ASSERT(len >= 0); @@ -217,7 +214,7 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in dbgmsg(tor, "got metadata piece %d of %d bytes", piece, len); /* are we set up to download metadata? */ - m = tor->incompleteMetadata; + struct tr_incomplete_metadata* m = tor->incompleteMetadata; if (m == NULL) { @@ -235,6 +232,8 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in return; } + int const offset = piece * METADATA_PIECE_SIZE; + TR_ASSERT(offset <= m->metadata_size); if (len == 0 || len > m->metadata_size - offset) @@ -361,12 +360,10 @@ void tr_torrentSetMetadataPiece(tr_torrent* tor, int piece, void const* data, in bool tr_torrentGetNextMetadataRequest(tr_torrent* tor, time_t now, int* setme_piece) { - bool have_request = false; - struct tr_incomplete_metadata* m; - TR_ASSERT(tr_isTorrent(tor)); - m = tor->incompleteMetadata; + bool have_request = false; + struct tr_incomplete_metadata* m = tor->incompleteMetadata; if (m != NULL && m->piecesNeededCount > 0 && m->piecesNeeded[0].requestedAt + MIN_REPEAT_INTERVAL_SECS < now) { diff --git a/libtransmission/torrent.c b/libtransmission/torrent.c index 4281efa2d..da62b8b7f 100644 --- a/libtransmission/torrent.c +++ b/libtransmission/torrent.c @@ -151,12 +151,11 @@ tr_torrent* tr_torrentFindFromObfuscatedHash(tr_session* session, uint8_t const* bool tr_torrentIsPieceTransferAllowed(tr_torrent const* tor, tr_direction direction) { - bool allowed = true; - unsigned int limit; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_isDirection(direction)); + bool allowed = true; + if (tr_torrentUsesSpeedLimit(tor, direction)) { if (tr_torrentGetSpeedLimit_Bps(tor, direction) <= 0) @@ -167,6 +166,8 @@ bool tr_torrentIsPieceTransferAllowed(tr_torrent const* tor, tr_direction direct if (tr_torrentUsesSessionLimits(tor)) { + unsigned int limit; + if (tr_sessionGetActiveSpeedLimit_Bps(tor->session, direction, &limit)) { if (limit <= 0) @@ -289,10 +290,10 @@ bool tr_torrentUsesSpeedLimit(tr_torrent const* tor, tr_direction dir) void tr_torrentUseSessionLimits(tr_torrent* tor, bool doUse) { - bool changed; - TR_ASSERT(tr_isTorrent(tor)); + bool changed; + changed = tr_bandwidthHonorParentLimits(&tor->bandwidth, TR_UP, doUse); changed |= tr_bandwidthHonorParentLimits(&tor->bandwidth, TR_DOWN, doUse); @@ -354,10 +355,10 @@ double tr_torrentGetRatioLimit(tr_torrent const* tor) bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio) { - bool isLimited; - TR_ASSERT(tr_isTorrent(tor)); + bool isLimited; + switch (tr_torrentGetRatioMode(tor)) { case TR_RATIOLIMIT_SINGLE: @@ -392,11 +393,11 @@ bool tr_torrentGetSeedRatio(tr_torrent const* tor, double* ratio) * it applies if the torrent's a seed AND it has a seed ratio set */ static bool tr_torrentGetSeedRatioBytes(tr_torrent const* tor, uint64_t* setmeLeft, uint64_t* setmeGoal) { + TR_ASSERT(tr_isTorrent(tor)); + double seedRatio; bool seedRatioApplies = false; - TR_ASSERT(tr_isTorrent(tor)); - if (tr_torrentGetSeedRatio(tor, &seedRatio)) { uint64_t const u = tor->uploadedCur + tor->uploadedPrev; @@ -558,10 +559,10 @@ void tr_torrentCheckSeedLimit(tr_torrent* tor) void tr_torrentSetLocalError(tr_torrent* tor, char const* fmt, ...) { - va_list ap; - TR_ASSERT(tr_isTorrent(tor)); + va_list ap; + va_start(ap, fmt); tor->error = TR_STAT_LOCAL_ERROR; tor->errorTracker[0] = '\0'; @@ -641,12 +642,10 @@ static void onTrackerResponse(tr_torrent* tor, tr_tracker_event const* event, vo static tr_piece_index_t getBytePiece(tr_info const* info, uint64_t byteOffset) { - tr_piece_index_t piece; - TR_ASSERT(info != NULL); TR_ASSERT(info->pieceSize != 0); - piece = byteOffset / info->pieceSize; + tr_piece_index_t piece = byteOffset / info->pieceSize; /* handle 0-byte files at the end of a torrent */ if (byteOffset == info->totalSize) @@ -659,16 +658,13 @@ static tr_piece_index_t getBytePiece(tr_info const* info, uint64_t byteOffset) static void initFilePieces(tr_info* info, tr_file_index_t fileIndex) { - tr_file* file; - uint64_t firstByte; - uint64_t lastByte; - TR_ASSERT(info != NULL); TR_ASSERT(fileIndex < info->fileCount); - file = &info->files[fileIndex]; - firstByte = file->offset; - lastByte = firstByte + (file->length ? file->length - 1 : 0); + tr_file* file = &info->files[fileIndex]; + uint64_t firstByte = file->offset; + uint64_t lastByte = firstByte + (file->length != 0 ? file->length - 1 : 0); + file->firstPiece = getBytePiece(info, firstByte); file->lastPiece = getBytePiece(info, lastByte); } @@ -767,6 +763,7 @@ static void tr_torrentInitFilePieces(tr_torrent* tor) for (tr_piece_index_t p = 0; p < inf->pieceCount; ++p) { tr_file_index_t f = firstFiles[p]; + TR_ASSERT(inf->files[f].firstPiece <= p); TR_ASSERT(inf->files[f].lastPiece >= p); @@ -865,10 +862,12 @@ static void torrentInitFromInfo(tr_torrent* tor) t *= info->pieceSize; t += tor->lastPieceSize; TR_ASSERT(t == info->totalSize); + t = tor->blockCount - 1; t *= tor->blockSize; t += tor->lastBlockSize; TR_ASSERT(t == info->totalSize); + t = info->pieceCount - 1; t *= tor->blockCountInPiece; t += tor->blockCountInLastPiece; @@ -921,17 +920,18 @@ static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor) static void torrentInit(tr_torrent* tor, tr_ctor const* ctor) { - bool doStart; - uint64_t loaded; - char const* dir; - bool isNewTorrent; tr_session* session = tr_ctorGetSession(ctor); - static int nextUniqueId = 1; TR_ASSERT(session != NULL); tr_sessionLock(session); + bool doStart; + uint64_t loaded; + char const* dir; + bool isNewTorrent; + static int nextUniqueId = 1; + tor->session = session; tor->uniqueId = nextUniqueId++; tor->magicNumber = TORRENT_MAGIC_NUMBER; @@ -1128,15 +1128,15 @@ tr_parse_result tr_torrentParse(tr_ctor const* ctor, tr_info* setmeInfo) tr_torrent* tr_torrentNew(tr_ctor const* ctor, int* setme_error, int* setme_duplicate_id) { + TR_ASSERT(ctor != NULL); + TR_ASSERT(tr_isSession(tr_ctorGetSession(ctor))); + size_t len; bool hasInfo; tr_info tmpInfo; tr_parse_result r; tr_torrent* tor = NULL; - TR_ASSERT(ctor != NULL); - TR_ASSERT(tr_isSession(tr_ctorGetSession(ctor))); - r = torrentParseImpl(ctor, &tmpInfo, &hasInfo, &len, setme_duplicate_id); if (r == TR_PARSE_OK) @@ -1334,18 +1334,19 @@ static double getVerifyProgress(tr_torrent const* tor) tr_stat const* tr_torrentStat(tr_torrent* tor) { + TR_ASSERT(tr_isTorrent(tor)); + + uint64_t const now = tr_time_msec(); + tr_stat* s; uint64_t seedRatioBytesLeft; uint64_t seedRatioBytesGoal; bool seedRatioApplies; uint16_t seedIdleMinutes; - uint64_t const now = tr_time_msec(); unsigned int pieceUploadSpeed_Bps; unsigned int pieceDownloadSpeed_Bps; struct tr_swarm_stats swarm_stats; - TR_ASSERT(tr_isTorrent(tor)); - tor->lastStatTime = tr_time(); if (tor->swarm != NULL) @@ -1558,13 +1559,13 @@ static uint64_t countFileBytesCompleted(tr_torrent const* tor, tr_file_index_t i tr_file_stat* tr_torrentFiles(tr_torrent const* tor, tr_file_index_t* fileCount) { + TR_ASSERT(tr_isTorrent(tor)); + tr_file_index_t const n = tor->info.fileCount; tr_file_stat* files = tr_new0(tr_file_stat, n); tr_file_stat* walk = files; bool const isSeed = tor->completeness == TR_SEED; - TR_ASSERT(tr_isTorrent(tor)); - for (tr_file_index_t i = 0; i < n; ++i, ++walk) { uint64_t const b = isSeed ? tor->info.files[i].length : countFileBytesCompleted(tor, i); @@ -1676,12 +1677,12 @@ static bool queueIsSequenced(tr_session*); static void freeTorrent(tr_torrent* tor) { + TR_ASSERT(!tor->isRunning); + tr_session* session = tor->session; tr_info* inf = &tor->info; time_t const now = tr_time(); - TR_ASSERT(!tor->isRunning); - tr_sessionLock(session); tr_peerMgrRemoveTorrent(tor); @@ -1744,7 +1745,6 @@ static void torrentSetQueued(tr_torrent* tor, bool queued); static void torrentStartImpl(void* vtor) { - time_t now; tr_torrent* tor = vtor; TR_ASSERT(tr_isTorrent(tor)); @@ -1754,10 +1754,12 @@ static void torrentStartImpl(void* vtor) tr_torrentRecheckCompleteness(tor); torrentSetQueued(tor, false); - now = tr_time(); + time_t const now = tr_time(); + tor->isRunning = true; tor->completeness = tr_cpGetStatus(&tor->completion); - tor->startDate = tor->anyDate = now; + tor->startDate = now; + tor->anyDate = now; tr_torrentClearError(tor); tor->finishedSeedingByIdle = false; @@ -1921,6 +1923,7 @@ cleanup: static void onVerifyDone(tr_torrent* tor, bool aborted, void* vdata) { struct verify_data* data = vdata; + TR_ASSERT(data->tor == tor); if (tor->isDeleting) @@ -1997,10 +2000,11 @@ void tr_torrentSave(tr_torrent* tor) static void stopTorrent(void* vtor) { tr_torrent* tor = vtor; - tr_logAddTorInfo(tor, "%s", "Pausing"); TR_ASSERT(tr_isTorrent(tor)); + tr_logAddTorInfo(tor, "%s", "Pausing"); + tr_torrentLock(tor); tr_verifyRemove(tor); @@ -2047,12 +2051,11 @@ void tr_torrentStop(tr_torrent* tor) static void closeTorrent(void* vtor) { - tr_variant* d; tr_torrent* tor = vtor; TR_ASSERT(tr_isTorrent(tor)); - d = tr_variantListAddDict(&tor->session->removedTorrents, 2); + tr_variant* d = tr_variantListAddDict(&tor->session->removedTorrents, 2); tr_variantDictAddInt(d, TR_KEY_id, tor->uniqueId); tr_variantDictAddInt(d, TR_KEY_date, tr_time()); @@ -2076,7 +2079,9 @@ void tr_torrentFree(tr_torrent* tor) if (tr_isTorrent(tor)) { tr_session* session = tor->session; + TR_ASSERT(tr_isSession(session)); + tr_sessionLock(session); tr_torrentClearCompletenessCallback(tor); @@ -2115,12 +2120,11 @@ static void removeTorrent(void* vdata) void tr_torrentRemove(tr_torrent* tor, bool deleteFlag, tr_fileFunc deleteFunc) { - struct remove_data* data; - TR_ASSERT(tr_isTorrent(tor)); + tor->isDeleting = true; - data = tr_new0(struct remove_data, 1); + struct remove_data* data = tr_new0(struct remove_data, 1); data->tor = tor; data->deleteFlag = deleteFlag; data->deleteFunc = deleteFunc; @@ -2438,13 +2442,12 @@ void tr_torrentSetMetadataCallback(tr_torrent* tor, tr_torrent_metadata_func fun void tr_torrentInitFilePriority(tr_torrent* tor, tr_file_index_t fileIndex, tr_priority_t priority) { - tr_file* file; - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(fileIndex < tor->info.fileCount); TR_ASSERT(tr_isPriority(priority)); - file = &tor->info.files[fileIndex]; + tr_file* file = &tor->info.files[fileIndex]; + file->priority = priority; for (tr_piece_index_t i = file->firstPiece; i <= file->lastPiece; ++i) @@ -2457,6 +2460,7 @@ void tr_torrentSetFilePriorities(tr_torrent* tor, tr_file_index_t const* files, tr_priority_t priority) { TR_ASSERT(tr_isTorrent(tor)); + tr_torrentLock(tor); for (tr_file_index_t i = 0; i < fileCount; ++i) @@ -2475,11 +2479,9 @@ void tr_torrentSetFilePriorities(tr_torrent* tor, tr_file_index_t const* files, tr_priority_t* tr_torrentGetFilePriorities(tr_torrent const* tor) { - tr_priority_t* p; - TR_ASSERT(tr_isTorrent(tor)); - p = tr_new0(tr_priority_t, tor->info.fileCount); + tr_priority_t* p = tr_new0(tr_priority_t, tor->info.fileCount); for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { @@ -2581,6 +2583,7 @@ void tr_torrentInitFileDLs(tr_torrent* tor, tr_file_index_t const* files, tr_fil void tr_torrentSetFileDLs(tr_torrent* tor, tr_file_index_t const* files, tr_file_index_t fileCount, bool doDownload) { TR_ASSERT(tr_isTorrent(tor)); + tr_torrentLock(tor); tr_torrentInitFileDLs(tor, files, fileCount, doDownload); @@ -2654,10 +2657,10 @@ void tr_torrentGetBlockLocation(tr_torrent const* tor, tr_block_index_t block, t tr_block_index_t _tr_block(tr_torrent const* tor, tr_piece_index_t index, uint32_t offset) { - tr_block_index_t ret; - TR_ASSERT(tr_isTorrent(tor)); + tr_block_index_t ret; + ret = index; ret *= tor->info.pieceSize / tor->blockSize; ret += offset / tor->blockSize; @@ -2666,10 +2669,10 @@ tr_block_index_t _tr_block(tr_torrent const* tor, tr_piece_index_t index, uint32 bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_t offset, uint32_t length) { - int err = 0; - TR_ASSERT(tr_isTorrent(tor)); + int err = 0; + if (index >= tor->info.pieceCount) { err = 1; @@ -2702,10 +2705,10 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_ uint64_t tr_pieceOffset(tr_torrent const* tor, tr_piece_index_t index, uint32_t offset, uint32_t length) { - uint64_t ret; - TR_ASSERT(tr_isTorrent(tor)); + uint64_t ret; + ret = tor->info.pieceSize; ret *= index; ret += offset; @@ -2840,13 +2843,13 @@ static int compareTrackerByTier(void const* va, void const* vb) bool tr_torrentSetAnnounceList(tr_torrent* tor, tr_tracker_info const* trackers_in, int trackerCount) { - tr_variant metainfo; - bool ok = true; - tr_tracker_info* trackers; + TR_ASSERT(tr_isTorrent(tor)); tr_torrentLock(tor); - TR_ASSERT(tr_isTorrent(tor)); + tr_variant metainfo; + bool ok = true; + tr_tracker_info* trackers; /* ensure the trackers' tiers are in ascending order */ trackers = tr_memdup(trackers_in, sizeof(tr_tracker_info) * trackerCount); @@ -2982,10 +2985,10 @@ void tr_torrentSetDoneDate(tr_torrent* tor, time_t t) uint64_t tr_torrentGetBytesLeftToAllocate(tr_torrent const* tor) { - uint64_t bytesLeft = 0; - TR_ASSERT(tr_isTorrent(tor)); + uint64_t bytesLeft = 0; + for (tr_file_index_t i = 0; i < tor->info.fileCount; ++i) { if (!tor->info.files[i].dnd) @@ -3282,15 +3285,17 @@ struct LocationData static void setLocation(void* vdata) { - bool err = false; struct LocationData* data = vdata; tr_torrent* tor = data->tor; + + TR_ASSERT(tr_isTorrent(tor)); + + tr_torrentLock(tor); + + bool err = false; bool const do_move = data->move_from_old_location; char const* location = data->location; double bytesHandled = 0; - tr_torrentLock(tor); - - TR_ASSERT(tr_isTorrent(tor)); tr_logAddDebug("Moving \"%s\" location from currentDir \"%s\" to \"%s\"", tr_torrentName(tor), tor->currentDir, location); @@ -3377,8 +3382,6 @@ static void setLocation(void* vdata) void tr_torrentSetLocation(tr_torrent* tor, char const* location, bool move_from_old_location, double volatile* setme_progress, int volatile* setme_state) { - struct LocationData* data; - TR_ASSERT(tr_isTorrent(tor)); if (setme_state != NULL) @@ -3392,7 +3395,7 @@ void tr_torrentSetLocation(tr_torrent* tor, char const* location, bool move_from } /* run this in the libtransmission thread */ - data = tr_new(struct LocationData, 1); + struct LocationData* data = tr_new(struct LocationData, 1); data->tor = tor; data->location = tr_strdup(location); data->move_from_old_location = move_from_old_location; @@ -3470,11 +3473,11 @@ static void tr_torrentPieceCompleted(tr_torrent* tor, tr_piece_index_t pieceInde void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block) { - bool const block_is_new = !tr_torrentBlockIsComplete(tor, block); - TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tr_amInEventThread(tor->session)); + bool const block_is_new = !tr_torrentBlockIsComplete(tor, block); + if (block_is_new) { tr_piece_index_t p; @@ -3516,15 +3519,15 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block) bool tr_torrentFindFile2(tr_torrent const* tor, tr_file_index_t fileNum, char const** base, char** subpath, time_t* mtime) { + TR_ASSERT(tr_isTorrent(tor)); + TR_ASSERT(fileNum < tor->info.fileCount); + char* part = NULL; tr_file const* file; char const* b = NULL; char const* s = NULL; tr_sys_path_info file_info; - TR_ASSERT(tr_isTorrent(tor)); - TR_ASSERT(fileNum < tor->info.fileCount); - file = &tor->info.files[fileNum]; /* look in the download dir... */ @@ -3644,6 +3647,7 @@ static void refreshCurrentDir(tr_torrent* tor) TR_ASSERT(dir != NULL); TR_ASSERT(dir == tor->downloadDir || dir == tor->incompleteDir); + tor->currentDir = dir; } @@ -3997,17 +4001,18 @@ struct rename_data static void torrentRenamePath(void* vdata) { - int error = 0; struct rename_data* data = vdata; tr_torrent* const tor = data->tor; - char const* const oldpath = data->oldpath; - char const* const newname = data->newname; + + TR_ASSERT(tr_isTorrent(tor)); /*** **** ***/ - TR_ASSERT(tr_isTorrent(tor)); + int error = 0; + char const* const oldpath = data->oldpath; + char const* const newname = data->newname; if (!renameArgsAreValid(oldpath, newname)) { diff --git a/libtransmission/tr-assert.h b/libtransmission/tr-assert.h index 61bd76017..69d1ce47f 100644 --- a/libtransmission/tr-assert.h +++ b/libtransmission/tr-assert.h @@ -40,8 +40,8 @@ bool TR_NORETURN tr_assert_report(char const* file, int line, char const* message_fmt, ...) TR_GNUC_PRINTF(3, 4); -#define TR_ASSERT(x) (TR_LIKELY(x) || tr_assert_report(__FILE__, __LINE__, "%s", #x)) -#define TR_ASSERT_MSG(x, ...) (TR_LIKELY(x) || tr_assert_report(__FILE__, __LINE__, __VA_ARGS__)) +#define TR_ASSERT(x) ((void)(TR_LIKELY(x) || tr_assert_report(__FILE__, __LINE__, "%s", #x))) +#define TR_ASSERT_MSG(x, ...) ((void)(TR_LIKELY(x) || tr_assert_report(__FILE__, __LINE__, __VA_ARGS__))) #define TR_ENABLE_ASSERTS diff --git a/libtransmission/tr-dht.c b/libtransmission/tr-dht.c index 3f34b3a67..a19e1b3f8 100644 --- a/libtransmission/tr-dht.c +++ b/libtransmission/tr-dht.c @@ -774,9 +774,6 @@ void tr_dhtUpkeep(tr_session* session) void tr_dhtCallback(unsigned char* buf, int buflen, struct sockaddr* from, socklen_t fromlen, void* sv) { - time_t tosleep; - int rc; - TR_ASSERT(tr_isSession(sv)); if (sv != session) @@ -784,7 +781,8 @@ void tr_dhtCallback(unsigned char* buf, int buflen, struct sockaddr* from, sockl return; } - rc = dht_periodic(buf, buflen, from, fromlen, &tosleep, callback, NULL); + time_t tosleep; + int rc = dht_periodic(buf, buflen, from, fromlen, &tosleep, callback, NULL); if (rc < 0) { @@ -845,6 +843,7 @@ int dht_random_bytes(void* buf, size_t size) int dht_gettimeofday(struct timeval* tv, struct timezone* tz) { TR_ASSERT(tz == NULL); + return tr_gettimeofday(tv); } diff --git a/libtransmission/tr-lpd.c b/libtransmission/tr-lpd.c index 1ee14c162..44a87f2ac 100644 --- a/libtransmission/tr-lpd.c +++ b/libtransmission/tr-lpd.c @@ -171,12 +171,11 @@ static int lpd_unsolicitedMsgCounter; */ static char const* lpd_extractHeader(char const* s, struct lpd_protocolVersion* const ver) { + TR_ASSERT(s != NULL); + int major = -1; int minor = -1; - size_t len; - - TR_ASSERT(s != NULL); - len = strlen(s); + size_t len = strlen(s); /* something might be rotten with this chunk of data */ if (len == 0 || len > lpd_maxDatagramLength) @@ -232,18 +231,19 @@ static char const* lpd_extractHeader(char const* s, struct lpd_protocolVersion* */ static bool lpd_extractParam(char const* const str, char const* const name, int n, char* const val) { - /* configure maximum length of search string here */ - enum - { - maxLength = 30 - }; - char sstr[maxLength] = { 0 }; - char const* pos; - TR_ASSERT(str != NULL); TR_ASSERT(name != NULL); TR_ASSERT(val != NULL); + enum + { + /* configure maximum length of search string here */ + maxLength = 30 + }; + + char sstr[maxLength] = { 0 }; + char const* pos; + if (strlen(name) > maxLength - strlen(CRLF ": ")) { return false; diff --git a/libtransmission/tr-udp.c b/libtransmission/tr-udp.c index 4483be7a0..f04ab87b9 100644 --- a/libtransmission/tr-udp.c +++ b/libtransmission/tr-udp.c @@ -240,15 +240,15 @@ fail: static void event_callback(evutil_socket_t s, short type UNUSED, void* sv) { + TR_ASSERT(tr_isSession(sv)); + TR_ASSERT(type == EV_READ); + int rc; socklen_t fromlen; unsigned char buf[4096]; struct sockaddr_storage from; tr_session* ss = sv; - TR_ASSERT(tr_isSession(sv)); - TR_ASSERT(type == EV_READ); - fromlen = sizeof(from); rc = recvfrom(s, (void*)buf, 4096 - 1, 0, (struct sockaddr*)&from, &fromlen); @@ -295,14 +295,14 @@ static void event_callback(evutil_socket_t s, short type UNUSED, void* sv) void tr_udpInit(tr_session* ss) { + TR_ASSERT(ss->udp_socket == TR_BAD_SOCKET); + TR_ASSERT(ss->udp6_socket == TR_BAD_SOCKET); + bool is_default; struct tr_address const* public_addr; struct sockaddr_in sin; int rc; - TR_ASSERT(ss->udp_socket == TR_BAD_SOCKET); - TR_ASSERT(ss->udp6_socket == TR_BAD_SOCKET); - ss->udp_port = tr_sessionGetPeerPort(ss); if (ss->udp_port <= 0) diff --git a/libtransmission/utils.c b/libtransmission/utils.c index 8750db8c1..bbbda8c1c 100644 --- a/libtransmission/utils.c +++ b/libtransmission/utils.c @@ -657,6 +657,9 @@ int tr_snprintf(char* buf, size_t buflen, char const* fmt, ...) */ size_t tr_strlcpy(char* dst, void const* src, size_t siz) { + TR_ASSERT(dst != NULL); + TR_ASSERT(src != NULL); + #ifdef HAVE_STRLCPY return strlcpy(dst, src, siz); @@ -667,9 +670,6 @@ size_t tr_strlcpy(char* dst, void const* src, size_t siz) char const* s = src; size_t n = siz; - TR_ASSERT(s != NULL); - TR_ASSERT(d != NULL); - /* Copy as many bytes as will fit */ if (n != 0) { @@ -2047,12 +2047,12 @@ bool tr_env_key_exists(char const* key) int tr_env_get_int(char const* key, int default_value) { + TR_ASSERT(key != NULL); + #ifdef _WIN32 char value[16]; - TR_ASSERT(key != NULL); - if (GetEnvironmentVariableA(key, value, TR_N_ELEMENTS(value)) > 1) { return atoi(value); @@ -2060,11 +2060,7 @@ int tr_env_get_int(char const* key, int default_value) #else - char const* value; - - TR_ASSERT(key != NULL); - - value = getenv(key); + char const* value = getenv(key); if (value != NULL && *value != '\0') { @@ -2078,13 +2074,13 @@ int tr_env_get_int(char const* key, int default_value) char* tr_env_get_string(char const* key, char const* default_value) { + TR_ASSERT(key != NULL); + #ifdef _WIN32 - wchar_t* wide_key; + wchar_t* wide_key = tr_win32_utf8_to_native(key, -1); char* value = NULL; - wide_key = tr_win32_utf8_to_native(key, -1); - if (wide_key != NULL) { DWORD const size = GetEnvironmentVariableW(wide_key, NULL, 0); @@ -2113,11 +2109,7 @@ char* tr_env_get_string(char const* key, char const* default_value) #else - char* value; - - TR_ASSERT(key != NULL); - - value = getenv(key); + char* value = getenv(key); if (value == NULL) { diff --git a/libtransmission/variant-json.c b/libtransmission/variant-json.c index 933e9bf59..22cb616e9 100644 --- a/libtransmission/variant-json.c +++ b/libtransmission/variant-json.c @@ -127,10 +127,11 @@ static void action_callback_PUSH(jsonsl_t jsn, jsonsl_action_t action UNUSED, st /* like sscanf(in+2, "%4x", &val) but less slow */ static bool decode_hex_string(char const* in, unsigned int* setme) { + TR_ASSERT(in != NULL); + unsigned int val = 0; char const* const end = in + 6; - TR_ASSERT(in != NULL); TR_ASSERT(in[0] == '\\'); TR_ASSERT(in[1] == 'u'); in += 2; diff --git a/libtransmission/variant.c b/libtransmission/variant.c index 8e343ac76..b45e2458c 100644 --- a/libtransmission/variant.c +++ b/libtransmission/variant.c @@ -487,10 +487,10 @@ void tr_variantInitList(tr_variant* v, size_t reserve_count) static void containerReserve(tr_variant* v, size_t count) { - size_t const needed = v->val.l.count + count; - TR_ASSERT(tr_variantIsContainer(v)); + size_t const needed = v->val.l.count + count; + if (needed > v->val.l.alloc) { /* scale the alloc size in powers-of-2 */ @@ -509,6 +509,7 @@ static void containerReserve(tr_variant* v, size_t count) void tr_variantListReserve(tr_variant* list, size_t count) { TR_ASSERT(tr_variantIsList(list)); + containerReserve(list, count); } @@ -521,17 +522,17 @@ void tr_variantInitDict(tr_variant* v, size_t reserve_count) void tr_variantDictReserve(tr_variant* dict, size_t reserve_count) { TR_ASSERT(tr_variantIsDict(dict)); + containerReserve(dict, reserve_count); } tr_variant* tr_variantListAdd(tr_variant* list) { - tr_variant* child; - TR_ASSERT(tr_variantIsList(list)); containerReserve(list, 1); - child = &list->val.l.vals[list->val.l.count++]; + + tr_variant* child = &list->val.l.vals[list->val.l.count++]; child->key = 0; tr_variantInit(child, TR_VARIANT_TYPE_INT); @@ -596,15 +597,14 @@ tr_variant* tr_variantListAddDict(tr_variant* list, size_t reserve_count) tr_variant* tr_variantDictAdd(tr_variant* dict, tr_quark const key) { - tr_variant* val; - TR_ASSERT(tr_variantIsDict(dict)); containerReserve(dict, 1); - val = dict->val.l.vals + dict->val.l.count++; + tr_variant* val = dict->val.l.vals + dict->val.l.count++; tr_variantInit(val, TR_VARIANT_TYPE_INT); val->key = key; + return val; } @@ -1006,10 +1006,10 @@ static size_t tr_variantDictSize(tr_variant const* dict) bool tr_variantDictChild(tr_variant* dict, size_t n, tr_quark* key, tr_variant** val) { - bool success = 0; - TR_ASSERT(tr_variantIsDict(dict)); + bool success = false; + if (tr_variantIsDict(dict) && n < dict->val.l.count) { *key = dict->val.l.vals[n].key; @@ -1022,11 +1022,11 @@ bool tr_variantDictChild(tr_variant* dict, size_t n, tr_quark* key, tr_variant** void tr_variantMergeDicts(tr_variant* target, tr_variant const* source) { - size_t const sourceCount = tr_variantDictSize(source); - TR_ASSERT(tr_variantIsDict(target)); TR_ASSERT(tr_variantIsDict(source)); + size_t const sourceCount = tr_variantDictSize(source); + tr_variantDictReserve(target, sourceCount + tr_variantDictSize(target)); for (size_t i = 0; i < sourceCount; ++i) diff --git a/libtransmission/verify.c b/libtransmission/verify.c index 460e68568..1fc253079 100644 --- a/libtransmission/verify.c +++ b/libtransmission/verify.c @@ -279,12 +279,10 @@ static int compareVerifyByPriorityAndSize(void const* va, void const* vb) void tr_verifyAdd(tr_torrent* tor, tr_verify_done_func callback_func, void* callback_data) { - struct verify_node* node; - TR_ASSERT(tr_isTorrent(tor)); tr_logAddTorInfo(tor, "%s", _("Queued for verification")); - node = tr_new(struct verify_node, 1); + struct verify_node* node = tr_new(struct verify_node, 1); node->torrent = tor; node->callback_func = callback_func; node->callback_data = callback_data; @@ -311,11 +309,11 @@ static int compareVerifyByTorrent(void const* va, void const* vb) void tr_verifyRemove(tr_torrent* tor) { + TR_ASSERT(tr_isTorrent(tor)); + tr_lock* lock = getVerifyLock(); tr_lockLock(lock); - TR_ASSERT(tr_isTorrent(tor)); - if (tor == currentNode.torrent) { stopCurrent = true; diff --git a/libtransmission/watchdir.c b/libtransmission/watchdir.c index cbe3b13df..866ede35d 100644 --- a/libtransmission/watchdir.c +++ b/libtransmission/watchdir.c @@ -303,18 +303,21 @@ void tr_watchdir_free(tr_watchdir_t handle) char const* tr_watchdir_get_path(tr_watchdir_t handle) { TR_ASSERT(handle != NULL); + return handle->path; } tr_watchdir_backend* tr_watchdir_get_backend(tr_watchdir_t handle) { TR_ASSERT(handle != NULL); + return handle->backend; } struct event_base* tr_watchdir_get_event_base(tr_watchdir_t handle) { TR_ASSERT(handle != NULL); + return handle->event_base; } @@ -324,11 +327,11 @@ struct event_base* tr_watchdir_get_event_base(tr_watchdir_t handle) void tr_watchdir_process(tr_watchdir_t handle, char const* name) { + TR_ASSERT(handle != NULL); + tr_watchdir_retry const search_key = { .name = (char*)name }; tr_watchdir_retry* existing_retry; - TR_ASSERT(handle != NULL); - if ((existing_retry = tr_watchdir_retries_find(&handle->active_retries, &search_key)) != NULL) { tr_watchdir_retry_restart(existing_retry); diff --git a/libtransmission/web.c b/libtransmission/web.c index 452d7ec5d..61d96486b 100644 --- a/libtransmission/web.c +++ b/libtransmission/web.c @@ -506,7 +506,9 @@ static void tr_webThreadFunc(void* vsession) long req_bytes_sent; CURL* e = msg->easy_handle; curl_easy_getinfo(e, CURLINFO_PRIVATE, (void*)&task); + TR_ASSERT(e == task->curl_easy); + curl_easy_getinfo(e, CURLINFO_RESPONSE_CODE, &task->code); curl_easy_getinfo(e, CURLINFO_REQUEST_SIZE, &req_bytes_sent); curl_easy_getinfo(e, CURLINFO_TOTAL_TIME, &total_time);