summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore2
-rw-r--r--DEDICATION2
-rw-r--r--DESIGN162
-rw-r--r--Makefile11
-rw-r--r--Mk/release.mk3
-rw-r--r--Mk/tests.mk4
-rw-r--r--man1/opentracker.18
-rw-r--r--man5/opentracker.conf.512
-rw-r--r--opentracker.conf.sample14
-rw-r--r--src/opentracker.c50
-rw-r--r--src/ot_accesslist.c44
-rw-r--r--src/ot_accesslist.h5
-rw-r--r--src/ot_clean.c156
-rw-r--r--src/ot_config.c38
-rw-r--r--src/ot_event.c9
-rw-r--r--src/ot_fdstate.c12
-rw-r--r--src/ot_fdstate.h8
-rw-r--r--src/ot_fullscrape.c42
-rw-r--r--src/ot_http.c73
-rw-r--r--src/ot_livesync.c10
-rw-r--r--src/ot_socket.c14
-rw-r--r--src/ot_socket.h2
-rw-r--r--src/ot_stats.c100
-rw-r--r--src/ot_tcp.c24
-rw-r--r--src/ot_udp.c182
-rw-r--r--src/ot_urlencoded.c12
-rw-r--r--src/ot_urlencoded.h4
-rw-r--r--src/ot_vector.c61
-rw-r--r--src/ot_vector.h2
-rw-r--r--src/ot_workqueue.c35
-rw-r--r--src/ot_workqueue.h3
-rw-r--r--src/trackerlogic.c247
-rw-r--r--src/trackerlogic.h104
-rw-r--r--tests/integration/harness.py10
-rw-r--r--tests/integration/test_accesslist.py44
-rw-r--r--tests/integration/test_announce.py15
-rw-r--r--tests/integration/test_concurrency.py2
-rw-r--r--tests/integration/test_config.py21
-rw-r--r--tests/integration/test_dynamic_accesslist.py18
-rw-r--r--tests/integration/test_fullscrape.py12
-rw-r--r--tests/integration/test_keepalive.py35
-rw-r--r--tests/integration/test_livesync.py13
-rw-r--r--tests/integration/test_statefile.py97
-rw-r--r--tests/integration/test_stats.py38
-rw-r--r--tests/integration/test_udp.py52
-rw-r--r--tests/runner.c1
-rw-r--r--tests/stubs.c11
-rw-r--r--tests/t_clean.c222
-rw-r--r--tests/t_socket.c19
-rw-r--r--tests/t_urlencoded.c66
-rw-r--r--tests/t_vector.c61
-rw-r--r--tests/t_workqueue.c52
-rw-r--r--tests/test.h1
53 files changed, 1627 insertions, 618 deletions
diff --git a/.gitignore b/.gitignore
index df288e0..b4ad7cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ opentracker
4opentracker.debug 4opentracker.debug
5opentracker.integration 5opentracker.integration
6opentracker.tsan 6opentracker.tsan
7opentracker.livesync
7proxy 8proxy
8proxy.debug 9proxy.debug
9tests/runner 10tests/runner
@@ -12,3 +13,4 @@ tests/runner.sanitize
12.buildstamp 13.buildstamp
13.tarball-version 14.tarball-version
14opentracker-*.tar.gz 15opentracker-*.tar.gz
16opentracker-*.tar.bz2
diff --git a/DEDICATION b/DEDICATION
new file mode 100644
index 0000000..eca7d99
--- /dev/null
+++ b/DEDICATION
@@ -0,0 +1,2 @@
1This release is dedicated to Felix von Leitner, whose libowfat carried
2opentracker for its first eighteen years.
diff --git a/DESIGN b/DESIGN
index f058fe0..7933223 100644
--- a/DESIGN
+++ b/DESIGN
@@ -46,6 +46,9 @@ every thread on every tick for the life of the process to catch something
46that happens once: at eight workers it doubled idle context switches, 255 to 46that happens once: at eight workers it doubled idle context switches, 255 to
47495 over thirty seconds. 47495 over thirty seconds.
48 48
49The cleaner is the exception, and waits on a pipe nobody reads. A poll
50timeout is an interval rather than a deadline, so no clock enters into it.
51
49Each binary is built in one compiler invocation. Without object files a build 52Each binary is built in one compiler invocation. Without object files a build
50cannot link objects compiled with different FEATURES, which was a real 53cannot link objects compiled with different FEATURES, which was a real
51failure mode. It costs incremental rebuilds, 0.075 seconds becoming 1.56. 54failure mode. It costs incremental rebuilds, 0.075 seconds becoming 1.56.
@@ -54,6 +57,13 @@ A socket is read or written, never both. http_interest_set replaces an
54add-and-drop pair so that the invariant cannot be broken by accident, and the 57add-and-drop pair so that the invariant cannot be broken by accident, and the
55event layer hears about a change once instead of twice. 58event layer hears about a change once instead of twice.
56 59
60A task belongs to a connection, not to a descriptor number. The queue files
61it under the number, and the kernel hands that number to the next connection
62the moment this one closes. So a connection that is owed an answer is not
63read from, closing it cancels every task filed under its number, and a result
64carries the generation the descriptor had when the task was pushed, which the
65main loop holds against the current one before it sends anything.
66
57Accept waits until the client's request has arrived: TCP_DEFER_ACCEPT on 67Accept waits until the client's request has arrived: TCP_DEFER_ACCEPT on
58Linux, the accf_data filter on FreeBSD. Measured against a flood of silent 68Linux, the accf_data filter on FreeBSD. Measured against a flood of silent
59connections, the filter serves more requests than no filter, not fewer, so it 69connections, the filter serves more requests than no filter, not fewer, so it
@@ -81,6 +91,150 @@ finish a sweep in OT_CLEAN_INTERVAL_MINUTES. At the default bucket count that
81is one bucket every 117 ms. 91is one bucket every 117 ms.
82 92
83 93
94A torrent carries its hash, one peerlist pointer, a base and a down count, 40
95bytes on a 64-bit host. The base and the down count live on the torrent, not
96on a list, so a torrent kept only for its download count holds no list at all.
97The one peerlist, allocated on the first peer of either family and freed when
98the last peer of both goes, holds the two family vectors and a single seeder
99count. The peer count is not stored, since a vector's own size is the count
100for a plain list and the sum of its buckets for a split one. That leaves the
101seeder count the only tally to maintain, because seeding is a per-peer flag
102and counting it would mean a walk.
103
104This is paid for in the common shape of a large table. A tracker carrying
105millions of torrents averages close to two peers each, a few crowded swarms
106over a long tail of near-empty ones, so fixed per-torrent cost, not peer
107payload, is most of resident memory. An earlier layout gave each torrent two
108always-allocated peer lists with their own counters and kept an idle torrent
109alive for a day to preserve one number: on glibc 168 bytes before a peer. The
110merged layout costs 40 for an empty torrent and, on glibc, 136 for a
111single-family one and 184 for a torrent carrying both. A torrent with peers in
112both families now takes one allocation rather than two. The split is drawn
113along the family distribution: empty and both-family torrents gain, a
114single-family torrent pays for the absent family's vector header. On jemalloc
115the bins differ, so the per-shape figures do too, but the empty-torrent and
116single-allocation gains hold on both.
117
118Reading those structs for one announce is a walk down cold memory. With the
119hash in hand, the steady-state path to an existing torrent reads, in order:
120
121 step reads load
122 lock one bucket mutex cold
123 bucket header that bucket's torrent vector cold
124 torrent search a hash per probe, log2 of the bucket cold
125 peerlist the torrent's peerlist cold
126 peer search a peer per probe, log2 of the swarm cold
127 reply counts the peerlist's sizes and seeder count hot
128
129Each cold line is a separate allocation, and on a large table each is a miss.
130The hot line rode in on the peerlist step before it. The torrent search
131dominates, one miss per probe into a bucket of hundreds of thousands, with the
132peerlist pointer chase and the peer search behind it. Aging the torrent adds
133nothing in steady state: one touched this minute has a zero span and the
134cleaner returns at once. The reply counts are hot because the two family
135sizes and the seeder count share the peerlist's line. A split swarm is the
136exception, since summing its size walks the bucket headers, but those are the
137largest torrents, where handing out peers already walks the swarm.
138
139A request waits on two system calls around this, a receive and a send, each
140on the order of a handful of misses. Memory latency and kernel time are
141co-dominant. Neither hides behind the other, and no term in the table is one
142a cache would hold still.
143
144A refused announce is answered over UDP with a well formed announce for an
145empty swarm rather than with the error action. BEP 15 binds a client to the
146interval it is handed and says nothing about what a client should do with an
147error, so an error puts the client on its own retry schedule instead. Over
148five minutes against one blacklisted torrent, libtorrent 2.0.8 sent seven
149connects and three announces to a tracker answering with the error and two of
150each to one answering with an empty swarm, and was still going on a widening
151backoff. Transmission 3.00 retries twenty seconds after an error, then at
152five, fifteen, thirty, sixty and finally every hundred and twenty minutes.
153That last figure sets OT_CLIENT_REJECT_INTERVAL: at anything under two hours
154Transmission's own backoff would be the cheaper of the two in steady state.
155Neither client bounds a tracker's interval from above, and libtorrent clamps
156it from below at five minutes.
157
158The reject interval is a constant and not a config entry, because the
159ordinary announce interval is a constant too and an operator has nothing to
160measure a different value against. Over HTTP a refusal stays a failure
161reason, which is the only place a user is told why.
162
163The state file keeps a wall clock minute, and it is the only thing in the
164tracker that reads that clock. Everything else runs off a monotonic one,
165where a time step cannot evict a swarm, but a file outlives the process that
166wrote it and minutes since this boot mean nothing to the next run. So the
167dump converts on the way out and load_state converts on the way back in, and
168what lands on disk is the format opentracker has written for years. A step
169between writing and reading mis-dates a torrent by the size of the step,
170which costs it part of its last day and nothing else.
171
172Build hardening the shipped binary
173----------------------------------
174
175The production and debug binaries carry -fstack-protector-strong, -fPIE and
176_FORTIFY_SOURCE=2 on every platform. The GNU-style linkers also get -pie and
177full RELRO (-z relro,-z now). Measured cost on
178the announce hot path is 300 to 305 nanoseconds, under two per cent, and the
179individual flags sit inside the run-to-run noise: add_peer has few stack
180buffers, most buffer sizes are known at compile time so FORTIFY emits no
181runtime check, and PIE on arm64 is almost free. On x86-64 PIE costs a little
182more. End to end it is invisible, since a UDP announce is mostly kernel time.
183
184The link flags -pie and RELRO are gated on the operating system: Apple's
185linker rejects -z, and flags a bare -pie in the combined compile-and-link as
186unused, while macOS links executables PIE by default, so leaving both off
187there costs no hardening. The branch runs in the shell through a != assignment,
188the one form both bmake and GNU make 4 accept. $(shell) is GNU only and GNU
189make 3.81, which stock macOS ships, has neither. On that old make the != line
190is inert and leaves the flags empty, which is the right answer for macOS
191anyway, so every platform resolves correctly without a make conditional.
192
193The flags are not in OT_CFLAGS, so the sanitizer test builds do not inherit
194them. AddressSanitizer checks harder than FORTIFY does, and the two clash on
195FreeBSD, where a FORTIFY plus ASan build aborted a multi hash scrape that the
196hardened production binary serves without complaint.
197
198Startup and teardown order
199--------------------------
200
201Nothing that consults the access list runs before the list has been read.
202The loader used to do its first read inside its own thread, so whatever ran
203next saw an empty list: a state file read with -l was checked against it and
204a blacklist build restored torrents it should have refused, a whitelist build
205restored none at all. Announces arriving in the same window went the same
206way, 3089 of them refused over 373 ms against a two million entry whitelist.
207The first read is therefore synchronous in accesslist_init, and the thread
208only handles reloads.
209
210Nothing that adds a peer starts before the state file has been read. That is
211the TCP and UDP listeners and live sync, so main starts all three after
212load_state rather than leaving live sync inside trackerlogic_init. A cluster
213packet arriving in that window created the torrent, and the saved state for it
214was then dropped on the exactmatch add_torrent_from_saved_state bails on,
215losing that torrent's completed count.
216
217A udp address somebody else holds is warned about and bound all the same.
218Linux permits the second bind when both sockets set SO_REUSEADDR, which the
219tracker always does, and FreeBSD when both asked to share the port, which it
220does for a group of workers. The two then take or split each other's datagrams
221without either noticing. Every udp entry is probed before the first of them is
222bound, with a socket that asks for no sharing, so that an overlap within the
223tracker's own configuration is not mistaken for a stranger. TCP is not probed:
224there the bind itself fails unless a balanced group was asked for, and on
225Linux a probe would also trip over the connections a restart leaves behind.
226
227Teardown stops the cleaner first. It is the one worker that calls into other
228modules, accesslist_cleanup and stats_cleanup, so stopping it after them left
229it locking a mutex accesslist_deinit had already destroyed: five shutdowns in
230sixty at a bucket count low enough to make the window easy to hit.
231
232Signal handlers are installed before the first thread exists. A thread
233created earlier runs with whatever disposition a signal still has, and
234SIGUSR1, the one that wakes a blocked worker, terminates a process by
235default.
236
237
84Paths not taken 238Paths not taken
85--------------- 239---------------
86 240
@@ -114,13 +268,19 @@ A directory for object files. bmake has no pattern rules and the Makefile
114builds under FreeBSD's make today. Building each binary in one invocation 268builds under FreeBSD's make today. Building each binary in one invocation
115clears the objects out of the tree without giving that up. 269clears the objects out of the tree without giving that up.
116 270
271A cached peer count on the torrent or the peerlist. The count is a vector's
272own size, a field in a line the peer insert has already loaded, so a cache
273would hold a second copy of a number already in reach and have to be kept in
274step with the vector it copies. Only a split swarm pays, to sum its buckets,
275and there the sum is lost against walking the swarm to answer at all.
276
117 277
118 278
119Platform differences that cost us code 279Platform differences that cost us code
120-------------------------------------- 280--------------------------------------
121 281
122SO_REUSEPORT means three different things. Linux spreads datagrams over the 282SO_REUSEPORT means three different things. Linux spreads datagrams over the
123group; FreeBSD permits the bind and needs SO_REUSEPORT_LB to spread. Darwin 283group. FreeBSD permits the bind and needs SO_REUSEPORT_LB to spread. Darwin
124hands every datagram to whichever socket bound last, so a group there starves 284hands every datagram to whichever socket bound last, so a group there starves
125all but one reader. 285all but one reader.
126 286
diff --git a/Makefile b/Makefile
index d2e0c2d..15828bb 100644
--- a/Makefile
+++ b/Makefile
@@ -10,8 +10,10 @@ STRIP?=strip
10 10
11#FEATURES+=-DWANT_SYNC_LIVE 11#FEATURES+=-DWANT_SYNC_LIVE
12#FEATURES+=-DWANT_IP_FROM_QUERY_STRING 12#FEATURES+=-DWANT_IP_FROM_QUERY_STRING
13#FEATURES+=-DWANT_KEEPALIVE
13 14
14#FEATURES+=-DWANT_RESTRICT_STATS 15#FEATURES+=-DWANT_RESTRICT_STATS
16#FEATURES+=-DWANT_RESTRICT_FULLSCRAPE
15#FEATURES+=-DWANT_IP_FROM_PROXY 17#FEATURES+=-DWANT_IP_FROM_PROXY
16#FEATURES+=-DWANT_LOG_NUMWANT 18#FEATURES+=-DWANT_LOG_NUMWANT
17#FEATURES+=-DWANT_MODEST_FULLSCRAPES 19#FEATURES+=-DWANT_MODEST_FULLSCRAPES
@@ -41,6 +43,9 @@ include Mk/gzip.mk
41CFLAGS?=-O3 43CFLAGS?=-O3
42 44
43OT_CFLAGS+=-Wall -Wextra -Wwrite-strings -pipe -pthread 45OT_CFLAGS+=-Wall -Wextra -Wwrite-strings -pipe -pthread
46
47HARDENING=-fstack-protector-strong -fPIE -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2
48HARDENING_LD!= case `uname -s` in Darwin) ;; *) printf %s "-pie -Wl,-z,relro,-z,now" ;; esac
44OT_LDFLAGS+=-pthread 49OT_LDFLAGS+=-pthread
45 50
46OPTS_debug=-D_DEBUG -g -ggdb 51OPTS_debug=-D_DEBUG -g -ggdb
@@ -63,14 +68,14 @@ BUILDDEPS=Makefile $(BUILDSTAMP)
63all: $(BINARY) $(BINARY).debug 68all: $(BINARY) $(BINARY).debug
64 69
65$(BINARY): $(SOURCES) $(HEADERS) $(BUILDDEPS) 70$(BINARY): $(SOURCES) $(HEADERS) $(BUILDDEPS)
66 $(CC) -o $@ $(CFLAGS) $(COMPILE) $(SOURCES) $(LINK) 71 $(CC) -o $@ $(CFLAGS) $(COMPILE) $(HARDENING) $(SOURCES) $(LINK) $(HARDENING_LD)
67 $(STRIP) $@ 72 $(STRIP) $@
68 73
69$(BINARY).debug: $(SOURCES) $(HEADERS) $(BUILDDEPS) 74$(BINARY).debug: $(SOURCES) $(HEADERS) $(BUILDDEPS)
70 $(CC) -o $@ $(OPTS_debug) $(COMPILE) $(SOURCES) $(LINK) 75 $(CC) -o $@ $(OPTS_debug) $(COMPILE) $(HARDENING) $(SOURCES) $(LINK) $(HARDENING_LD)
71 76
72$(BUILDSTAMP): FORCE 77$(BUILDSTAMP): FORCE
73 @echo "$(CFLAGS) $(COMPILE) $(LINK)" | cmp -s - $@ 2>/dev/null || echo "$(CFLAGS) $(COMPILE) $(LINK)" > $@ 78 @echo "$(CFLAGS) $(COMPILE) $(HARDENING) $(LINK) $(HARDENING_LD)" | cmp -s - $@ 2>/dev/null || echo "$(CFLAGS) $(COMPILE) $(HARDENING) $(LINK) $(HARDENING_LD)" > $@
74 79
75clean: 80clean:
76 rm -rf $(BINARIES) $(BINARIES:=.dSYM) $(BUILDSTAMP) *.o *~ src/*.o src/*~ 81 rm -rf $(BINARIES) $(BINARIES:=.dSYM) $(BUILDSTAMP) *.o *~ src/*.o src/*~
diff --git a/Mk/release.mk b/Mk/release.mk
index e5336e0..507a989 100644
--- a/Mk/release.mk
+++ b/Mk/release.mk
@@ -2,7 +2,7 @@
2# In a checkout it is absent and git answers instead. A release is always 2# In a checkout it is absent and git answers instead. A release is always
3# tagged, so in a tarball both of these are that tag, and the gitweb link 3# tagged, so in a tarball both of these are that tag, and the gitweb link
4# is to it. Between releases there is no tag and the version is the commit. 4# is to it. Between releases there is no tag and the version is the commit.
5VERSION=2.0.0 5VERSION=2.2.1
6 6
7TARBALL_VERSION=test -r .tarball-version && read v < .tarball-version && echo "$$v" 7TARBALL_VERSION=test -r .tarball-version && read v < .tarball-version && echo "$$v"
8HAVE_GIT=command -v git >/dev/null && test -d .git 8HAVE_GIT=command -v git >/dev/null && test -d .git
@@ -22,6 +22,7 @@ dist:
22 git archive --format=tar --prefix=$(DISTNAME)/ HEAD | tar -xf - 22 git archive --format=tar --prefix=$(DISTNAME)/ HEAD | tar -xf -
23 git describe --tags --match "v*" --always > $(DISTNAME)/.tarball-version 23 git describe --tags --match "v*" --always > $(DISTNAME)/.tarball-version
24 tar -czf $(DISTNAME).tar.gz $(DISTNAME) 24 tar -czf $(DISTNAME).tar.gz $(DISTNAME)
25 tar -cjf $(DISTNAME).tar.bz2 $(DISTNAME)
25 rm -rf $(DISTNAME) 26 rm -rf $(DISTNAME)
26 27
27.PHONY: dist 28.PHONY: dist
diff --git a/Mk/tests.mk b/Mk/tests.mk
index 2efdd72..22ea69e 100644
--- a/Mk/tests.mk
+++ b/Mk/tests.mk
@@ -4,8 +4,8 @@ BUILDDEPS+=Mk/tests.mk
4# may reach a static function by including the source. tests/stubs.c supplies 4# may reach a static function by including the source. tests/stubs.c supplies
5# the few symbols those modules reference but the tests never reach. 5# the few symbols those modules reference but the tests never reach.
6TESTBIN=tests/runner 6TESTBIN=tests/runner
7TEST_SOURCES=tests/runner.c tests/test.c tests/stubs.c tests/t_urlencoded.c tests/t_iovec.c tests/t_vector.c tests/t_random.c tests/t_hex.c tests/t_accesslist.c tests/t_scan.c tests/t_buf.c tests/t_ip.c tests/t_socket.c tests/t_mutex.c tests/t_trackerlogic.c tests/t_workqueue.c tests/t_batch.c tests/t_fdstate.c tests/t_event.c tests/t_fmt.c 7TEST_SOURCES=tests/runner.c tests/test.c tests/stubs.c tests/t_urlencoded.c tests/t_iovec.c tests/t_vector.c tests/t_random.c tests/t_hex.c tests/t_accesslist.c tests/t_scan.c tests/t_buf.c tests/t_ip.c tests/t_socket.c tests/t_mutex.c tests/t_trackerlogic.c tests/t_clean.c tests/t_workqueue.c tests/t_batch.c tests/t_fdstate.c tests/t_event.c tests/t_fmt.c
8TEST_UNITS=src/ot_urlencoded.c src/ot_fmt.c src/ot_event.c src/ot_batch.c src/ot_fdstate.c src/ot_buf.c src/ot_ip.c src/ot_socket.c src/ot_iovec.c src/ot_vector.c src/ot_random.c src/ot_hex.c src/ot_scan.c src/ot_accesslist.c src/ot_mutex.c src/ot_workqueue.c src/trackerlogic.c 8TEST_UNITS=src/ot_urlencoded.c src/ot_fmt.c src/ot_event.c src/ot_batch.c src/ot_fdstate.c src/ot_buf.c src/ot_ip.c src/ot_socket.c src/ot_iovec.c src/ot_vector.c src/ot_random.c src/ot_hex.c src/ot_scan.c src/ot_accesslist.c src/ot_mutex.c src/ot_workqueue.c src/ot_clean.c src/trackerlogic.c
9TEST_HEADERS=tests/test.h $(HEADERS) 9TEST_HEADERS=tests/test.h $(HEADERS)
10 10
11# A test binary is not a production binary, so it is built with the features 11# A test binary is not a production binary, so it is built with the features
diff --git a/man1/opentracker.1 b/man1/opentracker.1
index 897584f..10f4afc 100644
--- a/man1/opentracker.1
+++ b/man1/opentracker.1
@@ -1,7 +1,7 @@
1.Dd 15/4/2024 1.Dd 2026-11-10
2.Dt opentracker 1 2.Dt opentracker 1
3.Os Unix 3.Os Unix
4.Sh opentracker 4.Sh NAME
5.Nm opentracker 5.Nm opentracker
6.Nd a free and open bittorrent tracker 6.Nd a free and open bittorrent tracker
7.Sh SYNOPSIS 7.Sh SYNOPSIS
@@ -82,9 +82,9 @@ under after all operations that need privileges have finished.
82If 82If
83.Nm 83.Nm
84has been compiled with the 84has been compiled with the
85.B WANT_ACCESSLIST_BLACK 85.Sy WANT_ACCESSLIST_BLACK
86or 86or
87.Br WANT_ACCESSLIST_WHITE 87.Sy WANT_ACCESSLIST_WHITE
88options, this option sets the location of the accesslist. 88options, this option sets the location of the accesslist.
89.It Fl v 89.It Fl v
90Report the version, the event mechanism in use and the feature flags this 90Report the version, the event mechanism in use and the feature flags this
diff --git a/man5/opentracker.conf.5 b/man5/opentracker.conf.5
index 2250fe5..cc4c942 100644
--- a/man5/opentracker.conf.5
+++ b/man5/opentracker.conf.5
@@ -70,7 +70,7 @@ Specifies the path to the FIFO (named pipe) used for dynamic changesets to acces
70Specifies the path to the FIFO (named pipe) used for dynamic changesets to accesslists. Info hashes written to this FIFO will be removed from the main accesslist file. 70Specifies the path to the FIFO (named pipe) used for dynamic changesets to accesslists. Info hashes written to this FIFO will be removed from the main accesslist file.
71.Pp 71.Pp
72.It access.stats Ar ip_address_or_network 72.It access.stats Ar ip_address_or_network
73Specifies the IP address or network in CIDR notation allowed to fetch stats from opentracker. 73Specifies the IP address or network in CIDR notation allowed to fetch stats from opentracker, in case they are restricted.
74.Pp 74.Pp
75.It access.stats_path Ar path 75.It access.stats_path Ar path
76Specifies the path to the stats location. You can configure opentracker to appear anywhere on your tracker. Defaults to /stats. 76Specifies the path to the stats location. You can configure opentracker to appear anywhere on your tracker. Defaults to /stats.
@@ -78,6 +78,9 @@ Specifies the path to the stats location. You can configure opentracker to appea
78.It access.proxy Ar ip_address_or_network 78.It access.proxy Ar ip_address_or_network
79Specifies the IP address or network of the reverse proxies. Opentracker will take the X-Forwarded-For address instead of the source IP address. Can be added more than once. 79Specifies the IP address or network of the reverse proxies. Opentracker will take the X-Forwarded-For address instead of the source IP address. Can be added more than once.
80.Pp 80.Pp
81.It access.fullscrape Ar ip_address_or_network
82Specifies the IP address or network in CIDR notation allowed to fetch fullscrapes from opentracker, in case they are restricted.
83.Pp
81.It livesync.cluster.listen Ar ip_address:port 84.It livesync.cluster.listen Ar ip_address:port
82Specifies the IP address and port opentracker will listen on for incoming live 85Specifies the IP address and port opentracker will listen on for incoming live
83sync packets to keep a cluster of opentrackers synchronized. Every member of a 86sync packets to keep a cluster of opentrackers synchronized. Every member of a
@@ -105,6 +108,13 @@ Specifies the user opentracker will setuid to after binding to potentially privi
105.Pp 108.Pp
106.It tracker.redirect_url Ar URL 109.It tracker.redirect_url Ar URL
107Specifies the URL opentracker will redirect to in response to a "GET / HTTP" request. 110Specifies the URL opentracker will redirect to in response to a "GET / HTTP" request.
111.Pp
112.It tracker.empty_torrent_timeout Ar minutes
113Specifies how long a torrent that has no peers left in either family is held for
114its download count alone.
115Defaults to and is limited to 1440 minutes. Lower values save memory at the cost
116of less realiable download counts. A value of zero immediately destroys empty
117torrents.
108.El 118.El
109.Sh TUNING 119.Sh TUNING
110A worker is a thread that blocks in a read until a datagram arrives. Where the 120A worker is a thread that blocks in a read until a datagram arrives. Where the
diff --git a/opentracker.conf.sample b/opentracker.conf.sample
index 7b35369..da0b601 100644
--- a/opentracker.conf.sample
+++ b/opentracker.conf.sample
@@ -119,7 +119,6 @@
119# 119#
120# access.stats_path stats 120# access.stats_path stats
121# 121#
122# II
123# If opentracker lives behind one or multiple reverse proxies, 122# If opentracker lives behind one or multiple reverse proxies,
124# every http connection appears to come from these proxies. In order to 123# every http connection appears to come from these proxies. In order to
125# take the X-Forwarded-For address instead, compile opentracker with the 124# take the X-Forwarded-For address instead, compile opentracker with the
@@ -128,6 +127,12 @@
128# access.proxy 10.0.1.23 127# access.proxy 10.0.1.23
129# access.proxy 192.0.0.0/8 128# access.proxy 192.0.0.0/8
130# 129#
130# Symmetrically, if you have restricted the access to fullscrapes with
131# the WANT_RESTRICT_FULLSCRAPE compile option, this is how you bless ip
132# addresses to fetch fullscrapes
133#
134# access.fullscrape 10.1.1.23
135#
131 136
132# III) Live sync uses udp multicast packets to keep a cluster of opentrackers 137# III) Live sync uses udp multicast packets to keep a cluster of opentrackers
133# synchronized. This option tells opentracker which port to listen for 138# synchronized. This option tells opentracker which port to listen for
@@ -181,3 +186,10 @@
181# redirect to another location (shell option -r). 186# redirect to another location (shell option -r).
182# 187#
183# tracker.redirect_url https://your.tracker.local/ 188# tracker.redirect_url https://your.tracker.local/
189
190# VII) How long a torrent that has fallen empty is kept for its download count
191# alone, in minutes. Default and maximum is 1440 minutes (24 hours).
192# Trade-off: lower value less memory usage at the cost of less reliable
193# download counts.
194#
195# tracker.empty_torrent_timeout 60
diff --git a/src/opentracker.c b/src/opentracker.c
index 60a6d8c..81b4df6 100644
--- a/src/opentracker.c
+++ b/src/opentracker.c
@@ -7,6 +7,7 @@
7#include <errno.h> 7#include <errno.h>
8#include <limits.h> 8#include <limits.h>
9#include <pthread.h> 9#include <pthread.h>
10#include <grp.h>
10#include <pwd.h> 11#include <pwd.h>
11#include <signal.h> 12#include <signal.h>
12#include <stdint.h> 13#include <stdint.h>
@@ -24,6 +25,7 @@
24#include "ot_config.h" 25#include "ot_config.h"
25#include "ot_hex.h" 26#include "ot_hex.h"
26#include "ot_http.h" 27#include "ot_http.h"
28#include "ot_iovec.h"
27#include "ot_ip.h" 29#include "ot_ip.h"
28#include "ot_livesync.h" 30#include "ot_livesync.h"
29#include "ot_mutex.h" 31#include "ot_mutex.h"
@@ -106,6 +108,7 @@ static void *server_mainloop(void *args) {
106 struct iovec *iovector; 108 struct iovec *iovector;
107 size_t iovec_entries; 109 size_t iovec_entries;
108 int is_partial; 110 int is_partial;
111 uint32_t generation;
109 112
110 (void)args; 113 (void)args;
111 114
@@ -148,10 +151,15 @@ static void *server_mainloop(void *args) {
148 } 151 }
149 } 152 }
150 153
151 while ((sock = workqueue_popresult(&iovec_entries, &iovector, &is_partial)) != -1) 154 while ((sock = workqueue_popresult(&iovec_entries, &iovector, &is_partial, &generation)) != -1) {
155 if (fdstate_generation((int)sock) != generation) {
156 iovec_free(&iovec_entries, &iovector);
157 continue;
158 }
152 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial); 159 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial);
160 }
153 161
154 if (time_now_seconds() > next_timeout_check) { 162 if (time_is_past(next_timeout_check)) {
155 int cursor = 0; 163 int cursor = 0;
156 164
157 while ((sock = fdstate_next_expired(time_now_seconds(), &cursor)) != -1) 165 while ((sock = fdstate_next_expired(time_now_seconds(), &cursor)) != -1)
@@ -219,6 +227,16 @@ static void listen_bind_one(ot_listen *entry) {
219#endif 227#endif
220} 228}
221 229
230static void listen_warn_if_taken(const ot_listen *entry) {
231 char address[64];
232
233 if (entry->proto != FLAG_UDP || !socket_udp_is_taken(entry->ip, entry->port))
234 return;
235
236 address[ip_format(address, entry->ip)] = 0;
237 fprintf(stderr, "Warning: udp address [%s]:%d is already in use, by another tracker instance perhaps.\n", address, entry->port);
238}
239
222/* Bound in the order the entries were given. 240/* Bound in the order the entries were given.
223 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */ 241 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */
224static void listen_bind_all(void) { 242static void listen_bind_all(void) {
@@ -226,6 +244,9 @@ static void listen_bind_all(void) {
226 ot_listen *entries = config_listen_entries(&count); 244 ot_listen *entries = config_listen_entries(&count);
227 245
228 for (i = 0; i < count; ++i) 246 for (i = 0; i < count; ++i)
247 listen_warn_if_taken(entries + i);
248
249 for (i = 0; i < count; ++i)
229 listen_bind_one(entries + i); 250 listen_bind_one(entries + i);
230} 251}
231 252
@@ -300,9 +321,13 @@ void load_state(const char *const state_filename) {
300 FILE *state_filehandle; 321 FILE *state_filehandle;
301 char inbuf[512]; 322 char inbuf[512];
302 ot_hash infohash; 323 ot_hash infohash;
303 uint64_t base, downcount; 324 uint64_t touched, downcount;
304 int consumed; 325 int consumed;
305 326
327 /* The file records the minute a torrent was last touched, by the clock that
328 survives a restart */
329 uint64_t now = (uint64_t)time_wall_minutes();
330
306 state_filehandle = fopen(state_filename, "r"); 331 state_filehandle = fopen(state_filename, "r");
307 332
308 if (state_filehandle == NULL) { 333 if (state_filehandle == NULL) {
@@ -318,12 +343,12 @@ void load_state(const char *const state_filename) {
318 continue; 343 continue;
319 i = 2 * sizeof(ot_hash); 344 i = 2 * sizeof(ot_hash);
320 345
321 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &base, UINT64_MAX))) 346 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &touched, now)))
322 continue; 347 continue;
323 i += consumed; 348 i += consumed;
324 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &downcount, UINT64_MAX))) 349 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &downcount, SIZE_MAX)))
325 continue; 350 continue;
326 add_torrent_from_saved_state(infohash, base, downcount); 351 add_torrent_from_saved_state(infohash, (ot_time)(now - touched), (size_t)downcount);
327 } 352 }
328 353
329 fclose(state_filehandle); 354 fclose(state_filehandle);
@@ -356,10 +381,10 @@ int drop_privileges(const char *const serveruser, const char *const serverdir) {
356 /* If we can't find server user, revert to nobody's default uid */ 381 /* If we can't find server user, revert to nobody's default uid */
357 if (!pws) { 382 if (!pws) {
358 fprintf(stderr, "Warning: Could not get password entry for %s. Reverting to uid -2.\n", serveruser); 383 fprintf(stderr, "Warning: Could not get password entry for %s. Reverting to uid -2.\n", serveruser);
359 if (setegid((gid_t)-2) || setgid((gid_t)-2) || setuid((uid_t)-2) || seteuid((uid_t)-2)) 384 if (setgroups(0, NULL) || setegid((gid_t)-2) || setgid((gid_t)-2) || setuid((uid_t)-2) || seteuid((uid_t)-2))
360 panic("Could not set uid to value -2"); 385 panic("Could not set uid to value -2");
361 } else { 386 } else {
362 if (setegid(pws->pw_gid) || setgid(pws->pw_gid) || setuid(pws->pw_uid) || seteuid(pws->pw_uid)) 387 if (setgroups(0, NULL) || setegid(pws->pw_gid) || setgid(pws->pw_gid) || setuid(pws->pw_uid) || seteuid(pws->pw_uid))
363 panic("Could not set uid to specified value"); 388 panic("Could not set uid to specified value");
364 } 389 }
365 390
@@ -410,6 +435,10 @@ int main(int argc, char **argv) {
410 if (event_add(g_self_pipe[0], EVENT_IN, fdstate_open(g_self_pipe[0], (void *)FLAG_SELFPIPE, 0)) == -1) 435 if (event_add(g_self_pipe[0], EVENT_IN, fdstate_open(g_self_pipe[0], (void *)FLAG_SELFPIPE, 0)) == -1)
411 panic("selfpipe event_add"); 436 panic("selfpipe event_add");
412 437
438 /* Before any thread exists, so none of them runs with a signal still at its
439 default disposition */
440 install_signal_handlers();
441
413 /* Init all sub systems. This call may fail with an exit() */ 442 /* Init all sub systems. This call may fail with an exit() */
414 trackerlogic_init(); 443 trackerlogic_init();
415 444
@@ -422,13 +451,14 @@ int main(int argc, char **argv) {
422 if (g_statefile) 451 if (g_statefile)
423 load_state(g_statefile); 452 load_state(g_statefile);
424 453
425 install_signal_handlers(); 454 /* Nothing that adds a peer runs before the state file has been read */
426 455 livesync_init();
427 listen_start_tcp_workers(); 456 listen_start_tcp_workers();
428 listen_start_udp_workers(); 457 listen_start_udp_workers();
429 458
430 server_mainloop(0); 459 server_mainloop(0);
431 worker_stop_all(); 460 worker_stop_all();
461 livesync_deinit();
432 462
433 /* No thread is serving any more, so the teardown can run where a debugger 463 /* No thread is serving any more, so the teardown can run where a debugger
434 and the sanitizers can follow it */ 464 and the sanitizers can follow it */
diff --git a/src/ot_accesslist.c b/src/ot_accesslist.c
index 86f9a7d..5d4f059 100644
--- a/src/ot_accesslist.c
+++ b/src/ot_accesslist.c
@@ -33,7 +33,7 @@ const char *g_accesslist_filename = NULL;
33const char *g_accesslist_pipe_add = NULL; 33const char *g_accesslist_pipe_add = NULL;
34const char *g_accesslist_pipe_delete = NULL; 34const char *g_accesslist_pipe_delete = NULL;
35#endif 35#endif
36static pthread_mutex_t g_accesslist_mutex; 36static pthread_mutex_t g_accesslist_mutex = PTHREAD_MUTEX_INITIALIZER;
37 37
38/* Accesslists are lock free linked lists. We can not make them locking, because every announce 38/* Accesslists are lock free linked lists. We can not make them locking, because every announce
39 would try to acquire the mutex, making it the most contested mutex in the whole of opentracker, 39 would try to acquire the mutex, making it the most contested mutex in the whole of opentracker,
@@ -91,7 +91,7 @@ static ot_accesslist *accesslist_make(ot_accesslist *next, size_t size) {
91 This will never delete head, because that might still be in use. */ 91 This will never delete head, because that might still be in use. */
92static void accesslist_clean(ot_accesslist *accesslist) { 92static void accesslist_clean(ot_accesslist *accesslist) {
93 while (accesslist && accesslist->next) { 93 while (accesslist && accesslist->next) {
94 if (accesslist->next->base + 5 < time_now_minutes()) 94 if (time_since_minutes(accesslist->next->base) > 5)
95 accesslist->next = accesslist_free(accesslist->next); 95 accesslist->next = accesslist_free(accesslist->next);
96 accesslist = accesslist->next; 96 accesslist = accesslist->next;
97 } 97 }
@@ -257,15 +257,14 @@ static void *accesslist_worker(void *args) {
257 (void)args; 257 (void)args;
258 258
259 while (1) { 259 while (1) {
260 /* Wait for signals */
261 while (sigwait(&signal_mask, &sig) != 0)
262 ;
263
260 if (!g_opentracker_running) 264 if (!g_opentracker_running)
261 return NULL; 265 return NULL;
262 266
263 /* Initial attempt to read accesslist */
264 accesslist_readfile(); 267 accesslist_readfile();
265
266 /* Wait for signals */
267 while (sigwait(&signal_mask, &sig) != 0 && sig != SIGHUP)
268 ;
269 } 268 }
270 return NULL; 269 return NULL;
271} 270}
@@ -282,8 +281,7 @@ static void *accesslist_adddel_worker(const char *fifoname, ot_accesslist *_
282 return NULL; 281 return NULL;
283 } 282 }
284 } else { 283 } else {
285 int error = mkfifo(fifoname, 0755); 284 if (mkfifo(fifoname, 0600) && errno != EEXIST) {
286 if (error && error != EEXIST) {
287 fprintf(stderr, "Error when starting dynamic accesslists: Couldn't create FIFO at %s, error: %s\n", fifoname, strerror(errno)); 285 fprintf(stderr, "Error when starting dynamic accesslists: Couldn't create FIFO at %s, error: %s\n", fifoname, strerror(errno));
288 return NULL; 286 return NULL;
289 } 287 }
@@ -354,11 +352,17 @@ static void *accesslist_adddel_worker(const char *fifoname, ot_accesslist *_
354 /* Only if the info hash is not in the adding_to list, create a new head with that entry */ 352 /* Only if the info hash is not in the adding_to list, create a new head with that entry */
355 if (!exactmatch) { 353 if (!exactmatch) {
356 ot_accesslist *accesslist_new = accesslist_make(*adding_to, (*adding_to)->size + 1); 354 ot_accesslist *accesslist_new = accesslist_make(*adding_to, (*adding_to)->size + 1);
357 ptrdiff_t off = insert_point - (*adding_to)->list;
358 if (accesslist_new) { 355 if (accesslist_new) {
359 memcpy(accesslist_new->list, (*adding_to)->list, sizeof(ot_hash) * off); 356 ptrdiff_t off = (*adding_to)->size ? insert_point - (*adding_to)->list : 0;
357 size_t after = (*adding_to)->size - off;
358
359 /* A reload leaves an empty list with no array at all, and memcpy
360 may not be handed a null pointer even for nothing */
361 if (off)
362 memcpy(accesslist_new->list, (*adding_to)->list, sizeof(ot_hash) * off);
360 memcpy(accesslist_new->list + off, info_hash, sizeof(info_hash)); 363 memcpy(accesslist_new->list + off, info_hash, sizeof(info_hash));
361 memcpy(accesslist_new->list + off + 1, (*adding_to)->list + off, sizeof(ot_hash) * ((*adding_to)->size - off)); 364 if (after)
365 memcpy(accesslist_new->list + off + 1, (*adding_to)->list + off, sizeof(ot_hash) * after);
362 (*adding_to)->base = time_now_minutes(); 366 (*adding_to)->base = time_now_minutes();
363 *adding_to = accesslist_new; 367 *adding_to = accesslist_new;
364 } 368 }
@@ -405,13 +409,16 @@ static void accesslist_stop_fifo_worker(pthread_t thread, _Atomic int *left, con
405 409
406static pthread_t thread_id; 410static pthread_t thread_id;
407void accesslist_init(void) { 411void accesslist_init(void) {
408 pthread_mutex_init(&g_accesslist_mutex, NULL); 412 /* Everything that consults the list starts after this returns */
409 pthread_create(&thread_id, NULL, accesslist_worker, NULL); 413 accesslist_readfile();
414
415 if (pthread_create(&thread_id, NULL, accesslist_worker, NULL))
416 exerr("Cannot create accesslist worker thread.");
410#ifdef WANT_DYNAMIC_ACCESSLIST 417#ifdef WANT_DYNAMIC_ACCESSLIST
411 if (g_accesslist_pipe_add) 418 if (g_accesslist_pipe_add && pthread_create(&thread_adder_id, NULL, accesslist_adder_worker, NULL))
412 pthread_create(&thread_adder_id, NULL, accesslist_adder_worker, NULL); 419 exerr("Cannot create accesslist adder thread.");
413 if (g_accesslist_pipe_delete) 420 if (g_accesslist_pipe_delete && pthread_create(&thread_deleter_id, NULL, accesslist_deleter_worker, NULL))
414 pthread_create(&thread_deleter_id, NULL, accesslist_deleter_worker, NULL); 421 exerr("Cannot create accesslist deleter thread.");
415#endif 422#endif
416} 423}
417 424
@@ -436,7 +443,6 @@ void accesslist_deinit(void) {
436#endif 443#endif
437 444
438 pthread_mutex_unlock(&g_accesslist_mutex); 445 pthread_mutex_unlock(&g_accesslist_mutex);
439 pthread_mutex_destroy(&g_accesslist_mutex);
440} 446}
441 447
442void accesslist_cleanup(void) { 448void accesslist_cleanup(void) {
diff --git a/src/ot_accesslist.h b/src/ot_accesslist.h
index 68c88dc..c0f3fc2 100644
--- a/src/ot_accesslist.h
+++ b/src/ot_accesslist.h
@@ -12,8 +12,9 @@
12 12
13#if defined(WANT_ACCESSLIST_BLACK) || defined(WANT_ACCESSLIST_WHITE) 13#if defined(WANT_ACCESSLIST_BLACK) || defined(WANT_ACCESSLIST_WHITE)
14#define WANT_ACCESSLIST 14#define WANT_ACCESSLIST
15/* Starts a thread that rereads the list when sent SIGHUP, and is stopped by 15/* Reads the list, then starts a thread that rereads it when sent SIGHUP and
16 being sent one, so the caller blocks SIGHUP process wide beforehand */ 16 is stopped by being sent one, so the caller blocks SIGHUP process wide
17 beforehand */
17void accesslist_init(void); 18void accesslist_init(void);
18void accesslist_deinit(void); 19void accesslist_deinit(void);
19int accesslist_hashisvalid(const ot_hash hash); 20int accesslist_hashisvalid(const ot_hash hash);
diff --git a/src/ot_clean.c b/src/ot_clean.c
index f181e83..8eb1da2 100644
--- a/src/ot_clean.c
+++ b/src/ot_clean.c
@@ -2,8 +2,9 @@
2 It is considered beerware. Prost. Skol. Cheers or whatever. */ 2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3 3
4/* System */ 4/* System */
5#include <errno.h> 5#include <poll.h>
6#include <pthread.h> 6#include <pthread.h>
7#include <stdio.h>
7#include <string.h> 8#include <string.h>
8#include <unistd.h> 9#include <unistd.h>
9 10
@@ -15,9 +16,16 @@
15#include "ot_vector.h" 16#include "ot_vector.h"
16#include "trackerlogic.h" 17#include "trackerlogic.h"
17 18
19ot_time g_empty_torrent_timeout = OT_TORRENT_TIMEOUT;
20
18/* Returns amount of removed peers */ 21/* Returns amount of removed peers */
19static ssize_t clean_single_bucket(ot_peer *peers, size_t peer_count, size_t peer_size, time_t timedout, size_t *removed_seeders) { 22static ssize_t clean_single_bucket(ot_peer *peers, size_t peer_count, size_t peer_size, time_t timedout, size_t *removed_seeders) {
20 ot_peer *last_peer = peers + peer_count * peer_size, *insert_point; 23 ot_peer *last_peer, *insert_point;
24
25 if (!peer_count)
26 return 0;
27
28 last_peer = peers + peer_count * peer_size;
21 29
22 /* Two scan modes: unless there is one peer removed, just increase ot_peertime */ 30 /* Two scan modes: unless there is one peer removed, just increase ot_peertime */
23 while (peers < last_peer) { 31 while (peers < last_peer) {
@@ -43,86 +51,102 @@ static ssize_t clean_single_bucket(ot_peer *peers, size_t peer_count, size_t pee
43 return (peers - insert_point) / peer_size; 51 return (peers - insert_point) / peer_size;
44} 52}
45 53
46int clean_single_peer_list(ot_peerlist *peer_list, size_t peer_size) { 54/* Age one family's peers by timedout minutes. Releases and zeroes the vector
47 ot_vector *peer_vector = &peer_list->peers; 55 once its last peer is gone, so an empty family costs nothing. */
48 time_t timedout = (time_t)(time_now_minutes() - peer_list->base); 56static void clean_family_vector(ot_vector *peer_vector, size_t peer_size, ot_time timedout, size_t *removed_seeders) {
49 size_t num_buckets = 1, removed_seeders = 0; 57 ot_vector *bucket = peer_vector;
50 58 size_t num_buckets = 1, peer_count;
51 /* No need to clean empty torrent */
52 if (!timedout)
53 return 0;
54
55 /* Torrent has idled out */
56 if (timedout > OT_TORRENT_TIMEOUT)
57 return 1;
58 59
59 /* Nothing to be cleaned here? Test if torrent is worth keeping */ 60 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
60 if (timedout > OT_PEER_TIMEOUT) {
61 if (!peer_list->peer_count)
62 return peer_list->down_count ? 0 : 1;
63 timedout = OT_PEER_TIMEOUT;
64 }
65
66 if (OT_PEERLIST_HASBUCKETS(peer_list)) {
67 num_buckets = peer_vector->size; 61 num_buckets = peer_vector->size;
68 peer_vector = (ot_vector *)peer_vector->data; 62 bucket = (ot_vector *)peer_vector->data;
69 } 63 }
70 64
71 while (num_buckets--) { 65 while (num_buckets--) {
72 size_t removed_peers = clean_single_bucket(peer_vector->data, peer_vector->size, peer_size, timedout, &removed_seeders); 66 size_t removed_peers = clean_single_bucket(bucket->data, bucket->size, peer_size, timedout, removed_seeders);
73 peer_list->peer_count -= removed_peers; 67 bucket->size -= removed_peers;
74 peer_vector->size -= removed_peers;
75 if (removed_peers) 68 if (removed_peers)
76 vector_fixup_peers(peer_vector, peer_size); 69 vector_fixup_peers(bucket, peer_size);
77 70
78 /* Skip to next bucket, a vector containing peers */ 71 /* Skip to next bucket, a vector containing peers */
79 ++peer_vector; 72 ++bucket;
80 } 73 }
81 74
82 peer_list->seed_count -= removed_seeders; 75 peer_count = vector_peer_count(peer_vector);
83 76
84 /* See if we need to convert a torrent from simple vector to bucket list */ 77 /* Run dry: release the family (a collapsed bucket list or a plain vector) */
85 if ((peer_list->peer_count > OT_PEER_BUCKET_MINCOUNT) || OT_PEERLIST_HASBUCKETS(peer_list)) 78 if (!peer_count) {
86 vector_redistribute_buckets(peer_list, peer_size); 79 free_peer_vector(peer_vector);
87 80 memset(peer_vector, 0, sizeof(*peer_vector));
88 if (peer_list->peer_count) 81 return;
89 peer_list->base = time_now_minutes();
90 else {
91 /* When we got here, the last time that torrent
92 has been touched is OT_PEER_TIMEOUT Minutes before */
93 peer_list->base = time_now_minutes() - OT_PEER_TIMEOUT;
94 } 82 }
95 return 0; 83
84 /* See if we need to convert the vector from simple to bucket list or back */
85 if ((peer_count > OT_PEER_BUCKET_MINCOUNT) || OT_VECTOR_HASBUCKETS(peer_vector))
86 vector_redistribute_buckets(peer_vector, peer_size, peer_count);
96} 87}
97 88
98/* Clean a single torrent 89/* Clean a single torrent
99 return 1 if torrent timed out 90 return 1 if torrent timed out
100*/ 91*/
101int clean_single_torrent(ot_torrent *torrent) { 92int clean_single_torrent(ot_torrent *torrent) {
102 return clean_single_peer_list(torrent->peer_list6, OT_PEER_SIZE6) * clean_single_peer_list(torrent->peer_list4, OT_PEER_SIZE4); 93 ot_time timedout = time_since_minutes(torrent->base);
94 ot_peerlist *peer_list = torrent->peer_list;
95 size_t removed_seeders = 0;
96
97 /* Touched since the last sweep: nothing to do */
98 if (!timedout)
99 return 0;
100
101 /* Torrent has idled out */
102 if (timedout > OT_TORRENT_TIMEOUT)
103 return 1;
104
105 /* Already empty and nothing arrived before the peer timeout: keep it only
106 while a down count is worth remembering */
107 if (timedout > OT_PEER_TIMEOUT && !peer_list)
108 return (torrent->down_count && timedout <= g_empty_torrent_timeout) ? 0 : 1;
109
110 /* Peers past the peer timeout are gone regardless, which caps how far the
111 lists are aged in this pass */
112 if (timedout > OT_PEER_TIMEOUT)
113 timedout = OT_PEER_TIMEOUT;
114
115 if (peer_list) {
116 clean_family_vector(&peer_list->peers6, OT_PEER_SIZE6, timedout, &removed_seeders);
117 clean_family_vector(&peer_list->peers4, OT_PEER_SIZE4, timedout, &removed_seeders);
118 peer_list->seed_count -= removed_seeders;
119
120 /* Both families gone: drop the peerlist, the torrent keeps only its count */
121 if (!vector_peer_count(&peer_list->peers6) && !vector_peer_count(&peer_list->peers4)) {
122 free_peerlist(peer_list);
123 torrent->peer_list = peer_list = NULL;
124 }
125 }
126
127 if (peer_list)
128 torrent->base = time_now_minutes(); /* still carrying peers */
129 else {
130 /* Fell empty: hold base a peer timeout back so a later idle sweep makes
131 the keep-or-drop decision above */
132 ot_time now = time_now_minutes();
133 torrent->base = now > OT_PEER_TIMEOUT ? (uint32_t)(now - OT_PEER_TIMEOUT) : 0;
134 }
135 return 0;
103} 136}
104 137
105static pthread_mutex_t g_clean_mutex = PTHREAD_MUTEX_INITIALIZER; 138/* Written to once, by clean_deinit, and never read: the byte stays in and
106static pthread_cond_t g_clean_wakeup = PTHREAD_COND_INITIALIZER; 139 every sleep after it returns at once */
140static int g_clean_pipe[2] = {-1, -1};
107 141
108static void clean_sleep(void) { 142static void clean_sleep(void) {
109 struct timespec deadline; 143 struct pollfd pfd;
110 144
111 clock_gettime(CLOCK_REALTIME, &deadline); 145 pfd.fd = g_clean_pipe[0];
112 deadline.tv_sec += OT_CLEAN_SLEEP / 1000000; 146 pfd.events = POLLIN;
113 deadline.tv_nsec += (OT_CLEAN_SLEEP % 1000000) * 1000; 147 pfd.revents = 0;
114 if (deadline.tv_nsec >= 1000000000) {
115 ++deadline.tv_sec;
116 deadline.tv_nsec -= 1000000000;
117 }
118 148
119 /* Both sides hold the mutex, so the flag cannot be cleared and signalled 149 poll(&pfd, 1, OT_CLEAN_SLEEP / 1000);
120 in the window between testing it and waiting on it */
121 pthread_mutex_lock(&g_clean_mutex);
122 while (g_opentracker_running)
123 if (pthread_cond_timedwait(&g_clean_wakeup, &g_clean_mutex, &deadline) == ETIMEDOUT)
124 break;
125 pthread_mutex_unlock(&g_clean_mutex);
126} 150}
127 151
128/* Clean up all peers in one bucket, remove timedout pools and torrents */ 152/* Clean up all peers in one bucket, remove timedout pools and torrents */
@@ -166,11 +190,19 @@ static void *clean_worker(void *args) {
166} 190}
167 191
168static pthread_t thread_id; 192static pthread_t thread_id;
169void clean_init(void) { pthread_create(&thread_id, NULL, clean_worker, NULL); } 193void clean_init(void) {
194 if (pipe(g_clean_pipe) == -1)
195 fprintf(stderr, "Warning: the cleaner has no pipe to be woken through and will take up to one sleep interval to stop.\n");
196 if (pthread_create(&thread_id, NULL, clean_worker, NULL))
197 exerr("Cannot create cleanup worker thread.");
198}
170 199
171void clean_deinit(void) { 200void clean_deinit(void) {
172 pthread_mutex_lock(&g_clean_mutex); 201 const char byte = 0;
173 pthread_cond_signal(&g_clean_wakeup); 202
174 pthread_mutex_unlock(&g_clean_mutex); 203 (void)!write(g_clean_pipe[1], &byte, 1);
175 pthread_join(thread_id, NULL); 204 pthread_join(thread_id, NULL);
205
206 close(g_clean_pipe[0]);
207 close(g_clean_pipe[1]);
176} 208}
diff --git a/src/ot_config.c b/src/ot_config.c
index 6b51c61..e689314 100644
--- a/src/ot_config.c
+++ b/src/ot_config.c
@@ -79,10 +79,12 @@ static listen_option_kind parse_listen_option(char **p) {
79 79
80 for (i = 0; i < listen_option_count; ++i) { 80 for (i = 0; i < listen_option_count; ++i) {
81 const listen_option_key *key = &listen_option_keys[i]; 81 const listen_option_key *key = &listen_option_keys[i];
82 char delimiter = (*p)[key->len]; 82 char delimiter;
83 83
84 if (strncmp(*p, key->name, key->len)) 84 if (strncmp(*p, key->name, key->len))
85 continue; 85 continue;
86 /* The match guarantees *p is at least key->len bytes, so this is in bounds */
87 delimiter = (*p)[key->len];
86 if (key->takes_value ? delimiter != '=' : (delimiter && !isspace((unsigned char)delimiter))) 88 if (key->takes_value ? delimiter != '=' : (delimiter && !isspace((unsigned char)delimiter)))
87 continue; 89 continue;
88 90
@@ -126,7 +128,7 @@ static const char *set_config_option(const char **option, char *value) {
126#ifdef _DEBUG 128#ifdef _DEBUG
127 fprintf(stderr, "Setting config option: %s\n", value); 129 fprintf(stderr, "Setting config option: %s\n", value);
128#endif 130#endif
129 while (isspace(*value)) 131 while (isspace((unsigned char)*value))
130 ++value; 132 ++value;
131 free((char *)*option); 133 free((char *)*option);
132 return *option = strdup(value); 134 return *option = strdup(value);
@@ -136,7 +138,7 @@ static int scan_ip6_port(const char *src, ot_ip6 ip, uint16_t *port) {
136 const char *s = src; 138 const char *s = src;
137 uint64_t value; 139 uint64_t value;
138 int off, bracket = 0; 140 int off, bracket = 0;
139 while (isspace(*s)) 141 while (isspace((unsigned char)*s))
140 ++s; 142 ++s;
141 if (*s == '[') 143 if (*s == '[')
142 ++s, ++bracket; /* for v6 style notation */ 144 ++s, ++bracket; /* for v6 style notation */
@@ -145,7 +147,7 @@ static int scan_ip6_port(const char *src, ot_ip6 ip, uint16_t *port) {
145 s += off; 147 s += off;
146 if (bracket && *s == ']') 148 if (bracket && *s == ']')
147 ++s; 149 ++s;
148 if (*s == 0 || isspace(*s)) 150 if (*s == 0 || isspace((unsigned char)*s))
149 return s - src; 151 return s - src;
150 if (!ip_is_v4mapped(ip)) { 152 if (!ip_is_v4mapped(ip)) {
151 if (*s != ':' && *s != '.') 153 if (*s != ':' && *s != '.')
@@ -167,7 +169,7 @@ static int scan_ip6_net(const char *src, ot_net *net) {
167 const char *s = src; 169 const char *s = src;
168 uint64_t value; 170 uint64_t value;
169 int off; 171 int off;
170 while (isspace(*s)) 172 while (isspace((unsigned char)*s))
171 ++s; 173 ++s;
172 if (!(off = ip_parse(s, net->address))) 174 if (!(off = ip_parse(s, net->address)))
173 return 0; 175 return 0;
@@ -192,6 +194,7 @@ typedef enum {
192 CONFIG_UNKNOWN, 194 CONFIG_UNKNOWN,
193 CONFIG_TRACKER_ROOTDIR, 195 CONFIG_TRACKER_ROOTDIR,
194 CONFIG_TRACKER_USER, 196 CONFIG_TRACKER_USER,
197 CONFIG_TRACKER_EMPTY_TIMEOUT,
195 CONFIG_LISTEN_TCP_UDP, 198 CONFIG_LISTEN_TCP_UDP,
196 CONFIG_LISTEN_TCP, 199 CONFIG_LISTEN_TCP,
197 CONFIG_LISTEN_UDP, 200 CONFIG_LISTEN_UDP,
@@ -205,6 +208,7 @@ typedef enum {
205 CONFIG_ACCESS_STATS, 208 CONFIG_ACCESS_STATS,
206 CONFIG_ACCESS_STATS_PATH, 209 CONFIG_ACCESS_STATS_PATH,
207 CONFIG_ACCESS_PROXY, 210 CONFIG_ACCESS_PROXY,
211 CONFIG_ACCESS_FULLSCRAPE,
208 CONFIG_TRACKER_REDIRECT_URL, 212 CONFIG_TRACKER_REDIRECT_URL,
209 CONFIG_LIVESYNC_CLUSTER_NODE_IP, 213 CONFIG_LIVESYNC_CLUSTER_NODE_IP,
210 CONFIG_LIVESYNC_CLUSTER_LISTEN, 214 CONFIG_LIVESYNC_CLUSTER_LISTEN,
@@ -222,6 +226,7 @@ typedef struct {
222static const config_key config_keys[] = { 226static const config_key config_keys[] = {
223 CONFIG_KEY("tracker.rootdir", CONFIG_TRACKER_ROOTDIR), 227 CONFIG_KEY("tracker.rootdir", CONFIG_TRACKER_ROOTDIR),
224 CONFIG_KEY("tracker.user", CONFIG_TRACKER_USER), 228 CONFIG_KEY("tracker.user", CONFIG_TRACKER_USER),
229 CONFIG_KEY("tracker.empty_torrent_timeout", CONFIG_TRACKER_EMPTY_TIMEOUT),
225 CONFIG_KEY("listen.tcp_udp", CONFIG_LISTEN_TCP_UDP), 230 CONFIG_KEY("listen.tcp_udp", CONFIG_LISTEN_TCP_UDP),
226 CONFIG_KEY("listen.tcp", CONFIG_LISTEN_TCP), 231 CONFIG_KEY("listen.tcp", CONFIG_LISTEN_TCP),
227 CONFIG_KEY("listen.udp", CONFIG_LISTEN_UDP), 232 CONFIG_KEY("listen.udp", CONFIG_LISTEN_UDP),
@@ -244,6 +249,9 @@ static const config_key config_keys[] = {
244#ifdef WANT_IP_FROM_PROXY 249#ifdef WANT_IP_FROM_PROXY
245 CONFIG_KEY("access.proxy", CONFIG_ACCESS_PROXY), 250 CONFIG_KEY("access.proxy", CONFIG_ACCESS_PROXY),
246#endif 251#endif
252#ifdef WANT_RESTRICT_FULLSCRAPE
253 CONFIG_KEY("access.fullscrape", CONFIG_ACCESS_FULLSCRAPE),
254#endif
247 CONFIG_KEY("tracker.redirect_url", CONFIG_TRACKER_REDIRECT_URL), 255 CONFIG_KEY("tracker.redirect_url", CONFIG_TRACKER_REDIRECT_URL),
248#ifdef WANT_SYNC_LIVE 256#ifdef WANT_SYNC_LIVE
249 CONFIG_KEY("livesync.cluster.node_ip", CONFIG_LIVESYNC_CLUSTER_NODE_IP), 257 CONFIG_KEY("livesync.cluster.node_ip", CONFIG_LIVESYNC_CLUSTER_NODE_IP),
@@ -272,7 +280,7 @@ static int parse_configfile(char *config_filename) {
272 FILE *config_file_handle; 280 FILE *config_file_handle;
273 char inbuf[512]; 281 char inbuf[512];
274 ot_ip6 tmpip; 282 ot_ip6 tmpip;
275#if defined(WANT_RESTRICT_STATS) || defined(WANT_IP_FROM_PROXY) || defined(WANT_SYNC_LIVE) 283#if defined(WANT_RESTRICT_STATS) || defined(WANT_RESTRICT_FULLSCRAPE) || defined(WANT_IP_FROM_PROXY) || defined(WANT_SYNC_LIVE)
276 ot_net tmpnet; 284 ot_net tmpnet;
277#endif 285#endif
278 int bound = 0; 286 int bound = 0;
@@ -312,6 +320,11 @@ static int parse_configfile(char *config_filename) {
312 case CONFIG_TRACKER_USER: 320 case CONFIG_TRACKER_USER:
313 set_config_option(&g_serveruser, p); 321 set_config_option(&g_serveruser, p);
314 break; 322 break;
323 case CONFIG_TRACKER_EMPTY_TIMEOUT:
324 if (!scan_uint(p, &value, UINT_MAX))
325 goto parse_error;
326 g_empty_torrent_timeout = (ot_time)value;
327 break;
315 case CONFIG_LISTEN_TCP_UDP: 328 case CONFIG_LISTEN_TCP_UDP:
316 case CONFIG_LISTEN_TCP: 329 case CONFIG_LISTEN_TCP:
317 case CONFIG_LISTEN_UDP: { 330 case CONFIG_LISTEN_UDP: {
@@ -376,6 +389,13 @@ static int parse_configfile(char *config_filename) {
376 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_PROXY); 389 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_PROXY);
377 break; 390 break;
378#endif 391#endif
392#ifdef WANT_RESTRICT_FULLSCRAPE
393 case CONFIG_ACCESS_FULLSCRAPE:
394 if (!scan_ip6_net(p, &tmpnet))
395 goto parse_error;
396 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_FULLSCRAPE);
397 break;
398#endif
379 case CONFIG_TRACKER_REDIRECT_URL: 399 case CONFIG_TRACKER_REDIRECT_URL:
380 set_config_option(&g_redirecturl, p); 400 set_config_option(&g_redirecturl, p);
381 break; 401 break;
@@ -465,10 +485,10 @@ static void listen_resolve_defaults(void) {
465 /* A tcp worker hands a connection it cannot finish to the event loop, 485 /* A tcp worker hands a connection it cannot finish to the event loop,
466 which only one thread may touch where the set is ours rather than the 486 which only one thread may touch where the set is ours rather than the
467 kernel's */ 487 kernel's */
468 if (entry->proto == FLAG_TCP && entry->workers > 1 && !event_can_share()) { 488 if (entry->proto == FLAG_TCP && entry->workers > 0 && !event_can_share()) {
469 fprintf(stderr, "Warning: Multiple workers impossible on this platform with event mechanism %s chosen.\n", 489 fprintf(stderr, "Warning: tcp workers impossible on this platform with event mechanism %s chosen.\n",
470 event_mechanism()); 490 event_mechanism());
471 entry->workers = 1; 491 entry->workers = 0;
472 } 492 }
473 } 493 }
474} 494}
diff --git a/src/ot_event.c b/src/ot_event.c
index 6062f70..cc575f6 100644
--- a/src/ot_event.c
+++ b/src/ot_event.c
@@ -143,7 +143,7 @@ void event_deinit(void) {
143 back untouched. */ 143 back untouched. */
144static int event_change(int fd, int what, uint32_t generation, int deleting) { 144static int event_change(int fd, int what, uint32_t generation, int deleting) {
145 struct kevent change[2], result[2]; 145 struct kevent change[2], result[2];
146 void *udata = (void *)(uintptr_t)(((uint64_t)generation << 32) | (uint32_t)fd); 146 void *udata = (void *)(uintptr_t)generation;
147 int succeeded = 0, count, i; 147 int succeeded = 0, count, i;
148 148
149 EV_SET(&change[0], (uintptr_t)fd, EVFILT_READ, 149 EV_SET(&change[0], (uintptr_t)fd, EVFILT_READ,
@@ -206,11 +206,10 @@ int event_wait(ot_event *out, int max, int timeout_ms) {
206 if ((count = kevent(g_kqueue, NULL, 0, g_ready, max, deadline)) == -1) 206 if ((count = kevent(g_kqueue, NULL, 0, g_ready, max, deadline)) == -1)
207 return errno == EINTR ? 0 : -1; 207 return errno == EINTR ? 0 : -1;
208 for (i = 0; i < count; ++i) { 208 for (i = 0; i < count; ++i) {
209 uint64_t udata = (uint64_t)(uintptr_t)g_ready[i].udata; 209 int eof = (g_ready[i].flags & (EV_EOF | EV_ERROR)) != 0;
210 int eof = (g_ready[i].flags & (EV_EOF | EV_ERROR)) != 0;
211 210
212 out[i].fd = (int)(uint32_t)udata; 211 out[i].fd = (int)g_ready[i].ident;
213 out[i].generation = (uint32_t)(udata >> 32); 212 out[i].generation = (uint32_t)(uintptr_t)g_ready[i].udata;
214 out[i].what = ((g_ready[i].filter == EVFILT_READ || eof) ? EVENT_IN : 0) | 213 out[i].what = ((g_ready[i].filter == EVFILT_READ || eof) ? EVENT_IN : 0) |
215 ((g_ready[i].filter == EVFILT_WRITE || eof) ? EVENT_OUT : 0); 214 ((g_ready[i].filter == EVFILT_WRITE || eof) ? EVENT_OUT : 0);
216 } 215 }
diff --git a/src/ot_fdstate.c b/src/ot_fdstate.c
index 8e4bd89..bbb25d2 100644
--- a/src/ot_fdstate.c
+++ b/src/ot_fdstate.c
@@ -24,7 +24,7 @@ enum { FD_FREE, FD_IDLE, FD_BUSY, FD_CLOSING };
24typedef struct { 24typedef struct {
25 _Atomic uint64_t state; 25 _Atomic uint64_t state;
26 _Atomic(void *) cookie; 26 _Atomic(void *) cookie;
27 _Atomic ot_time expiry; 27 _Atomic unsigned long expiry;
28} ot_fdslot; 28} ot_fdslot;
29 29
30/* A descriptor the kernel can hand out is below the limit it was handed out 30/* A descriptor the kernel can hand out is below the limit it was handed out
@@ -72,7 +72,7 @@ static ot_fdslot *fdstate_slot(int fd) {
72 return g_slots + fd; 72 return g_slots + fd;
73} 73}
74 74
75uint32_t fdstate_open(int fd, void *cookie, ot_time expiry) { 75uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry) {
76 ot_fdslot *slot = fdstate_slot(fd); 76 ot_fdslot *slot = fdstate_slot(fd);
77 uint64_t word; 77 uint64_t word;
78 78
@@ -132,10 +132,10 @@ void fdstate_release(int fd) {
132 atomic_store_explicit(&slot->state, FD_SET_ST(word, FD_IDLE), memory_order_release); 132 atomic_store_explicit(&slot->state, FD_SET_ST(word, FD_IDLE), memory_order_release);
133} 133}
134 134
135int fdstate_claim_expired(int fd, ot_time now) { 135int fdstate_claim_expired(int fd, unsigned long now) {
136 ot_fdslot *slot = fdstate_slot(fd); 136 ot_fdslot *slot = fdstate_slot(fd);
137 uint64_t word; 137 uint64_t word;
138 ot_time expiry; 138 unsigned long expiry;
139 139
140 if (!slot) 140 if (!slot)
141 return 0; 141 return 0;
@@ -168,7 +168,7 @@ void fdstate_close(int fd) {
168 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word) + 1, FD_FREE), memory_order_release); 168 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word) + 1, FD_FREE), memory_order_release);
169} 169}
170 170
171int fdstate_next_expired(ot_time now, int *cursor) { 171int fdstate_next_expired(unsigned long now, int *cursor) {
172 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed); 172 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed);
173 173
174 for (; (size_t)*cursor <= highest; ++*cursor) 174 for (; (size_t)*cursor <= highest; ++*cursor)
@@ -194,7 +194,7 @@ void fdstate_set_cookie(int fd, void *cookie) {
194 atomic_store_explicit(&slot->cookie, cookie, memory_order_release); 194 atomic_store_explicit(&slot->cookie, cookie, memory_order_release);
195} 195}
196 196
197void fdstate_set_expiry(int fd, ot_time expiry) { 197void fdstate_set_expiry(int fd, unsigned long expiry) {
198 ot_fdslot *slot = fdstate_slot(fd); 198 ot_fdslot *slot = fdstate_slot(fd);
199 199
200 if (slot) 200 if (slot)
diff --git a/src/ot_fdstate.h b/src/ot_fdstate.h
index 60fe070..20f469d 100644
--- a/src/ot_fdstate.h
+++ b/src/ot_fdstate.h
@@ -27,7 +27,7 @@ size_t fdstate_slots(void);
27 27
28/* Take a freshly accepted descriptor into the table and return the 28/* Take a freshly accepted descriptor into the table and return the
29 generation to quote when asking for it back. expiry of 0 never expires. */ 29 generation to quote when asking for it back. expiry of 0 never expires. */
30uint32_t fdstate_open(int fd, void *cookie, ot_time expiry); 30uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry);
31 31
32/* Which generation a descriptor currently carries, to check an event that 32/* Which generation a descriptor currently carries, to check an event that
33 was handed out earlier against the connection living there now. */ 33 was handed out earlier against the connection living there now. */
@@ -40,7 +40,7 @@ void fdstate_release(int fd);
40 40
41/* The cleaner's side of the same thing: takes the descriptor only if nobody 41/* The cleaner's side of the same thing: takes the descriptor only if nobody
42 is working on it and it really has expired. Never waits. */ 42 is working on it and it really has expired. Never waits. */
43int fdstate_claim_expired(int fd, ot_time now); 43int fdstate_claim_expired(int fd, unsigned long now);
44 44
45/* Give the descriptor up. The generation is bumped here, which has to happen 45/* Give the descriptor up. The generation is bumped here, which has to happen
46 before close(2) so that the kernel cannot reissue the number while events 46 before close(2) so that the kernel cannot reissue the number while events
@@ -50,13 +50,13 @@ void fdstate_close(int fd);
50/* Walks the table for descriptors that have expired, handing back one at a 50/* Walks the table for descriptors that have expired, handing back one at a
51 time until it returns -1. The cursor belongs to the caller, so several 51 time until it returns -1. The cursor belongs to the caller, so several
52 sweepers can run without sharing anything. */ 52 sweepers can run without sharing anything. */
53int fdstate_next_expired(ot_time now, int *cursor); 53int fdstate_next_expired(unsigned long now, int *cursor);
54 54
55/* Both only valid while the caller holds the descriptor. */ 55/* Both only valid while the caller holds the descriptor. */
56void *fdstate_cookie(int fd); 56void *fdstate_cookie(int fd);
57 57
58/* Hand the slot a different cookie, for a connection whose state has moved */ 58/* Hand the slot a different cookie, for a connection whose state has moved */
59void fdstate_set_cookie(int fd, void *cookie); 59void fdstate_set_cookie(int fd, void *cookie);
60void fdstate_set_expiry(int fd, ot_time expiry); 60void fdstate_set_expiry(int fd, unsigned long expiry);
61 61
62#endif 62#endif
diff --git a/src/ot_fullscrape.c b/src/ot_fullscrape.c
index 9afad92..00c08e0 100644
--- a/src/ot_fullscrape.c
+++ b/src/ot_fullscrape.c
@@ -43,8 +43,6 @@ static void fullscrape_make_gzip(int taskid, ot_tasktype mode);
43static void fullscrape_make_zstd(int taskid, ot_tasktype mode); 43static void fullscrape_make_zstd(int taskid, ot_tasktype mode);
44#endif 44#endif
45 45
46/* Converter function from memory to human readable hex strings
47 XXX - Duplicated from ot_stats. Needs fix. */
48/* This is the entry point into this worker thread 46/* This is the entry point into this worker thread
49 It grabs tasks from mutex_tasklist and delivers results back 47 It grabs tasks from mutex_tasklist and delivers results back
50*/ 48*/
@@ -74,7 +72,8 @@ static void *fullscrape_worker(void *args) {
74 72
75static pthread_t thread_id; 73static pthread_t thread_id;
76void fullscrape_init(void) { 74void fullscrape_init(void) {
77 pthread_create( &thread_id, NULL, fullscrape_worker, NULL ); 75 if (pthread_create(&thread_id, NULL, fullscrape_worker, NULL))
76 exerr("Cannot create fullscrape worker thread.");
78} 77}
79 78
80void fullscrape_deinit(void) { 79void fullscrape_deinit(void) {
@@ -92,9 +91,9 @@ static void fullscrape_write_one( ot_tasktype mode, char **cursor, ot_torrent *t
92 exactly that size */ 91 exactly that size */
93 char *r = *cursor; 92 char *r = *cursor;
94 const char *r_end = r + OT_SCRAPE_MAXENTRYLEN; 93 const char *r_end = r + OT_SCRAPE_MAXENTRYLEN;
95 size_t seed_count = torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 94 size_t seed_count = torrent_seed_count(torrent);
96 size_t peer_count = torrent->peer_list6->peer_count + torrent->peer_list4->peer_count; 95 size_t peer_count = torrent_peer_count(torrent);
97 size_t down_count = torrent->peer_list6->down_count + torrent->peer_list4->down_count; 96 size_t down_count = torrent->down_count;
98 97
99 switch (mode & TASK_TASK_MASK) { 98 switch (mode & TASK_TASK_MASK) {
100 case TASK_FULLSCRAPE: 99 case TASK_FULLSCRAPE:
@@ -122,9 +121,8 @@ static void fullscrape_write_one( ot_tasktype mode, char **cursor, ot_torrent *t
122 case TASK_FULLSCRAPE_TPB_BINARY: 121 case TASK_FULLSCRAPE_TPB_BINARY:
123 memcpy(r, *hash, sizeof(ot_hash)); 122 memcpy(r, *hash, sizeof(ot_hash));
124 r += sizeof(ot_hash); 123 r += sizeof(ot_hash);
125 *(uint32_t *)(r + 0) = htonl((uint32_t)seed_count); 124 pack_uint32(&r, (uint32_t)seed_count);
126 *(uint32_t *)(r + 4) = htonl((uint32_t)(peer_count - seed_count)); 125 pack_uint32(&r, (uint32_t)(peer_count - seed_count));
127 r += 8;
128 break; 126 break;
129 case TASK_FULLSCRAPE_TPB_URLENCODED: 127 case TASK_FULLSCRAPE_TPB_URLENCODED:
130 r += urlencoded_format(r, *hash, sizeof(ot_hash)); 128 r += urlencoded_format(r, *hash, sizeof(ot_hash));
@@ -133,7 +131,7 @@ static void fullscrape_write_one( ot_tasktype mode, char **cursor, ot_torrent *t
133 case TASK_FULLSCRAPE_TRACKERSTATE: 131 case TASK_FULLSCRAPE_TRACKERSTATE:
134 hex_from_hash(r, *hash); 132 hex_from_hash(r, *hash);
135 r += 2 * sizeof(ot_hash); 133 r += 2 * sizeof(ot_hash);
136 fmt_append(&r, r_end, ":%zd:%zd\n", torrent->peer_list6->base, down_count); 134 fmt_append(&r, r_end, ":%zd:%zd\n", (ssize_t)(time_wall_minutes() - time_since_minutes(torrent->base)), down_count);
137 break; 135 break;
138 } 136 }
139 *cursor = r; 137 *cursor = r;
@@ -190,8 +188,10 @@ static void fullscrape_make(int taskid, ot_tasktype mode) {
190 mutex_bucket_unlock(bucket, 0); 188 mutex_bucket_unlock(bucket, 0);
191 189
192 /* Parent thread died? */ 190 /* Parent thread died? */
193 if (!g_opentracker_running) 191 if (!g_opentracker_running) {
192 free(iovector.iov_base);
194 return; 193 return;
194 }
195 } 195 }
196 196
197 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) 197 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE)
@@ -219,8 +219,10 @@ static void fullscrape_make_gzip(int taskid, ot_tasktype mode) {
219 memset(&strm, 0, sizeof(strm)); 219 memset(&strm, 0, sizeof(strm));
220 strm.next_out = (uint8_t *)iovector.iov_base; 220 strm.next_out = (uint8_t *)iovector.iov_base;
221 strm.avail_out = OT_SCRAPE_CHUNK_SIZE; 221 strm.avail_out = OT_SCRAPE_CHUNK_SIZE;
222 if (deflateInit2(&strm, 7, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY) != Z_OK) 222 if (deflateInit2(&strm, 7, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY) != Z_OK) {
223 fprintf(stderr, "not ok.\n"); 223 free(iovector.iov_base);
224 return;
225 }
224 226
225 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) { 227 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
226 strm.next_in = (uint8_t *)"d5:filesd"; 228 strm.next_in = (uint8_t *)"d5:filesd";
@@ -252,6 +254,7 @@ static void fullscrape_make_gzip(int taskid, ot_tasktype mode) {
252 254
253 if (workqueue_pushchunked(taskid, &iovector)) { 255 if (workqueue_pushchunked(taskid, &iovector)) {
254 free(iovector.iov_base); 256 free(iovector.iov_base);
257 deflateEnd(&strm);
255 mutex_bucket_unlock(bucket, 0); 258 mutex_bucket_unlock(bucket, 0);
256 return; 259 return;
257 } 260 }
@@ -276,6 +279,7 @@ static void fullscrape_make_gzip(int taskid, ot_tasktype mode) {
276 279
277 /* Parent thread died? */ 280 /* Parent thread died? */
278 if (!g_opentracker_running) { 281 if (!g_opentracker_running) {
282 free(iovector.iov_base);
279 deflateEnd(&strm); 283 deflateEnd(&strm);
280 return; 284 return;
281 } 285 }
@@ -377,7 +381,7 @@ static void fullscrape_make_zstd(int taskid, ot_tasktype mode) {
377 381
378 /* Check if there still is enough buffer left */ 382 /* Check if there still is enough buffer left */
379 while (outbuf.pos + OT_SCRAPE_MAXENTRYLEN > outbuf.size) { 383 while (outbuf.pos + OT_SCRAPE_MAXENTRYLEN > outbuf.size) {
380 iovector.iov_len = outbuf.size; 384 iovector.iov_len = outbuf.pos;
381 385
382 if (workqueue_pushchunked(taskid, &iovector)) { 386 if (workqueue_pushchunked(taskid, &iovector)) {
383 free(iovector.iov_base); 387 free(iovector.iov_base);
@@ -404,14 +408,22 @@ static void fullscrape_make_zstd(int taskid, ot_tasktype mode) {
404 mutex_bucket_unlock(bucket, 0); 408 mutex_bucket_unlock(bucket, 0);
405 409
406 /* Parent thread died? */ 410 /* Parent thread died? */
407 if (!g_opentracker_running) 411 if (!g_opentracker_running) {
412 free(iovector.iov_base);
413 ZSTD_freeCCtx(zstream);
408 return; 414 return;
415 }
409 } 416 }
410 417
411 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) { 418 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
412 inbuf.src = (const void *)"ee"; 419 inbuf.src = (const void *)"ee";
413 inbuf.size = strlen("ee"); 420 inbuf.size = strlen("ee");
414 inbuf.pos = 0; 421 inbuf.pos = 0;
422 } else {
423 /* Nothing more to feed, and with no torrent written nothing was set */
424 inbuf.src = (const void *)"";
425 inbuf.size = 0;
426 inbuf.pos = 0;
415 } 427 }
416 428
417 more_bytes = ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end); 429 more_bytes = ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end);
diff --git a/src/ot_http.c b/src/ot_http.c
index 96b8f4e..2e21546 100644
--- a/src/ot_http.c
+++ b/src/ot_http.c
@@ -141,9 +141,9 @@ static void http_senddata(const int64_t sock, struct ot_workstruct *ws) {
141 141
142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size); 142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size);
143 143
144 /* writeable short data sockets just have a tcp timeout */ 144 /* Reset any connections potentially near their timeout */
145 if (!ws->keep_alive) 145 if (!ws->keep_alive)
146 fdstate_set_expiry(sock, 0); 146 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
147 http_interest_set(sock, cookie, EVENT_OUT); 147 http_interest_set(sock, cookie, EVENT_OUT);
148 } 148 }
149} 149}
@@ -279,7 +279,6 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
279 {"tcp4", TASK_STATS_TCP}, 279 {"tcp4", TASK_STATS_TCP},
280 {"torr", TASK_STATS_TORRENTS}, 280 {"torr", TASK_STATS_TORRENTS},
281 {"fscr", TASK_STATS_FULLSCRAPE}, 281 {"fscr", TASK_STATS_FULLSCRAPE},
282 {"s24s", TASK_STATS_SLASH24S},
283 {"tpbs", TASK_STATS_TPB}, 282 {"tpbs", TASK_STATS_TPB},
284 {"herr", TASK_STATS_HTTPERRORS}, 283 {"herr", TASK_STATS_HTTPERRORS},
285 {"completed", TASK_STATS_COMPLETED}, 284 {"completed", TASK_STATS_COMPLETED},
@@ -313,7 +312,7 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
313#endif 312#endif
314 313
315 while (scanon) { 314 while (scanon) {
316 switch (urlencoded_match_keyword(keywords_main, &read_ptr, SCAN_SEARCHPATH_PARAM)) { 315 switch (urlencoded_match_keyword(keywords_main, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
317 case -2: 316 case -2:
318 scanon = 0; 317 scanon = 0;
319 break; /* TERMINATOR */ 318 break; /* TERMINATOR */
@@ -323,11 +322,11 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
323 urlencoded_skip_value(&read_ptr); 322 urlencoded_skip_value(&read_ptr);
324 break; 323 break;
325 case 1: /* matched "mode" */ 324 case 1: /* matched "mode" */
326 if ((mode = urlencoded_match_keyword(keywords_mode, &read_ptr, SCAN_SEARCHPATH_VALUE)) <= 0) 325 if ((mode = urlencoded_match_keyword(keywords_mode, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
327 HTTPERROR_400_PARAM; 326 HTTPERROR_400_PARAM;
328 break; 327 break;
329 case 2: /* matched "format" */ 328 case 2: /* matched "format" */
330 if ((format = urlencoded_match_keyword(keywords_format, &read_ptr, SCAN_SEARCHPATH_VALUE)) <= 0) 329 if ((format = urlencoded_match_keyword(keywords_format, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
331 HTTPERROR_400_PARAM; 330 HTTPERROR_400_PARAM;
332 break; 331 break;
333 case 3: 332 case 3:
@@ -342,6 +341,10 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
342 } 341 }
343 342
344 if (mode == TASK_STATS_TPB) { 343 if (mode == TASK_STATS_TPB) {
344#ifdef WANT_RESTRICT_FULLSCRAPE
345 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_FULLSCRAPE))
346 HTTPERROR_403_IP;
347#endif
345#ifdef WANT_COMPRESSION_GZIP 348#ifdef WANT_COMPRESSION_GZIP
346 ws->request[ws->request_size - 1] = 0; 349 ws->request[ws->request_size - 1] = 0;
347#ifndef WANT_COMPRESSION_GZIP_ALWAYS 350#ifndef WANT_COMPRESSION_GZIP_ALWAYS
@@ -363,6 +366,7 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
363 a home of its own and only then be made reachable by a worker thread */ 366 a home of its own and only then be made reachable by a worker thread */
364 if (!http_adopt(sock)) 367 if (!http_adopt(sock))
365 HTTPERROR_500; 368 HTTPERROR_500;
369 ws->handed_off = 1;
366 fullscrape_deliver(sock, format); 370 fullscrape_deliver(sock, format);
367 return ws->reply_size = -2; 371 return ws->reply_size = -2;
368 } 372 }
@@ -375,9 +379,11 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c
375 379
376 /* Complex stats also include expensive memory debugging tools */ 380 /* Complex stats also include expensive memory debugging tools */
377 fdstate_set_expiry(sock, 0); 381 fdstate_set_expiry(sock, 0);
382 http_interest_set(sock, cookie, 0);
378 383
379 if (!http_adopt(sock)) 384 if (!http_adopt(sock))
380 HTTPERROR_500; 385 HTTPERROR_500;
386 ws->handed_off = 1;
381 stats_deliver(sock, mode); 387 stats_deliver(sock, mode);
382 return ws->reply_size = -2; 388 return ws->reply_size = -2;
383 } 389 }
@@ -402,6 +408,14 @@ static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct *
402 struct http_data *cookie = fdstate_cookie(sock); 408 struct http_data *cookie = fdstate_cookie(sock);
403 int format = 0; 409 int format = 0;
404 410
411 if (!cookie)
412 HTTPERROR_500;
413
414#ifdef WANT_RESTRICT_FULLSCRAPE
415 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_FULLSCRAPE))
416 HTTPERROR_403_IP;
417#endif
418
405#ifdef WANT_MODEST_FULLSCRAPES 419#ifdef WANT_MODEST_FULLSCRAPES
406 { 420 {
407 ot_scrape_log this_peer, *new_peer; 421 ot_scrape_log this_peer, *new_peer;
@@ -414,7 +428,7 @@ static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct *
414 pthread_mutex_unlock(&g_modest_fullscrape_mutex); 428 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
415 HTTPERROR_500; 429 HTTPERROR_500;
416 } 430 }
417 if (exactmatch && (this_peer.last_fullscrape - new_peer->last_fullscrape) < OT_MODEST_PEER_TIMEOUT) { 431 if (exactmatch && time_since_seconds(new_peer->last_fullscrape) < OT_MODEST_PEER_TIMEOUT) {
418 pthread_mutex_unlock(&g_modest_fullscrape_mutex); 432 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
419 HTTPERROR_402_NOTMODEST; 433 HTTPERROR_402_NOTMODEST;
420 } 434 }
@@ -464,6 +478,7 @@ static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct *
464 478
465 if (!http_adopt(sock)) 479 if (!http_adopt(sock))
466 HTTPERROR_500; 480 HTTPERROR_500;
481 ws->handed_off = 1;
467 fullscrape_deliver(sock, format); 482 fullscrape_deliver(sock, format);
468 return ws->reply_size = -2; 483 return ws->reply_size = -2;
469} 484}
@@ -489,7 +504,7 @@ static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws,
489 } 504 }
490 505
491 while (scanon) { 506 while (scanon) {
492 switch (urlencoded_match_keyword(keywords_scrape, &read_ptr, SCAN_SEARCHPATH_PARAM)) { 507 switch (urlencoded_match_keyword(keywords_scrape, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
493 case -2: 508 case -2:
494 scanon = 0; 509 scanon = 0;
495 break; /* TERMINATOR */ 510 break; /* TERMINATOR */
@@ -499,10 +514,12 @@ static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws,
499 urlencoded_skip_value(&read_ptr); 514 urlencoded_skip_value(&read_ptr);
500 break; 515 break;
501 case 1: /* matched "info_hash" */ 516 case 1: /* matched "info_hash" */
517 {
502 /* ignore this, when we have less than 20 bytes */ 518 /* ignore this, when we have less than 20 bytes */
503 if (urlencoded_parse(&read_ptr, (char *)(multiscrape_buf + numwant++), SCAN_SEARCHPATH_VALUE) != (ssize_t)sizeof(ot_hash)) 519 ot_hash *slot = multiscrape_buf + numwant++;
520 if (urlencoded_parse(&read_ptr, (char *)slot, (char *)(slot + 1), SCAN_SEARCHPATH_VALUE) != (ssize_t)sizeof(ot_hash))
504 HTTPERROR_400_PARAM; 521 HTTPERROR_400_PARAM;
505 break; 522 } break;
506 } 523 }
507 } 524 }
508 525
@@ -519,7 +536,7 @@ static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws,
519 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash); 536 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash);
520 for (i = unique = 1; i < numwant; ++i) 537 for (i = unique = 1; i < numwant; ++i)
521 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash))) 538 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash)))
522 memcpy(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash)); 539 memmove(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash));
523 numwant = unique; 540 numwant = unique;
524 541
525 /* Enough for http header + whole scrape string */ 542 /* Enough for http header + whole scrape string */
@@ -606,7 +623,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
606 scanon = 1; 623 scanon = 1;
607 624
608 while (scanon) { 625 while (scanon) {
609 switch (urlencoded_match_keyword(keywords_announce, &read_ptr, SCAN_SEARCHPATH_PARAM)) { 626 switch (urlencoded_match_keyword(keywords_announce, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
610 case -2: 627 case -2:
611 scanon = 0; 628 scanon = 0;
612 break; /* TERMINATOR */ 629 break; /* TERMINATOR */
@@ -616,14 +633,14 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
616 urlencoded_skip_value(&read_ptr); 633 urlencoded_skip_value(&read_ptr);
617 break; 634 break;
618 case 1: /* matched "port" */ 635 case 1: /* matched "port" */
619 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE); 636 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
620 if ((len <= 0) || scan_int(write_ptr, len, &tmp) || (tmp > 0xffff)) 637 if ((len <= 0) || scan_int(write_ptr, len, &tmp) || (tmp < 0) || (tmp > 0xffff))
621 HTTPERROR_400_PARAM; 638 HTTPERROR_400_PARAM;
622 port = htons((uint16_t)tmp); 639 port = htons((uint16_t)tmp);
623 OT_SETPORT(&ws->peer, &port); 640 OT_SETPORT(&ws->peer, &port);
624 break; 641 break;
625 case 2: /* matched "left" */ 642 case 2: /* matched "left" */
626 if ((len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE)) <= 0) 643 if ((len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
627 HTTPERROR_400_PARAM; 644 HTTPERROR_400_PARAM;
628 if (scan_int(write_ptr, len, &tmp)) 645 if (scan_int(write_ptr, len, &tmp))
629 tmp = 0; 646 tmp = 0;
@@ -631,7 +648,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
631 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_SEEDING; 648 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_SEEDING;
632 break; 649 break;
633 case 3: /* matched "event" */ 650 case 3: /* matched "event" */
634 switch (urlencoded_match_keyword(keywords_announce_event, &read_ptr, SCAN_SEARCHPATH_VALUE)) { 651 switch (urlencoded_match_keyword(keywords_announce_event, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) {
635 case -1: 652 case -1:
636 HTTPERROR_400_PARAM; 653 HTTPERROR_400_PARAM;
637 case 1: /* matched "completed" */ 654 case 1: /* matched "completed" */
@@ -645,7 +662,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
645 } 662 }
646 break; 663 break;
647 case 4: /* matched "numwant" */ 664 case 4: /* matched "numwant" */
648 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE); 665 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
649 if ((len <= 0) || scan_int(write_ptr, len, &tmp)) 666 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
650 HTTPERROR_400_PARAM; 667 HTTPERROR_400_PARAM;
651 if (tmp < 0) 668 if (tmp < 0)
@@ -655,7 +672,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
655 numwant = (size_t)tmp; 672 numwant = (size_t)tmp;
656 break; 673 break;
657 case 5: /* matched "compact" */ 674 case 5: /* matched "compact" */
658 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE); 675 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
659 if ((len <= 0) || scan_int(write_ptr, len, &tmp)) 676 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
660 HTTPERROR_400_PARAM; 677 HTTPERROR_400_PARAM;
661 if (!tmp) 678 if (!tmp)
@@ -665,7 +682,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
665 if (ws->hash) 682 if (ws->hash)
666 HTTPERROR_400_DOUBLEHASH; 683 HTTPERROR_400_DOUBLEHASH;
667 /* ignore this, when we have less than 20 bytes */ 684 /* ignore this, when we have less than 20 bytes */
668 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE) != 20) 685 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
669 HTTPERROR_400_PARAM; 686 HTTPERROR_400_PARAM;
670 ws->hash = (ot_hash *)write_ptr; 687 ws->hash = (ot_hash *)write_ptr;
671 break; 688 break;
@@ -673,16 +690,19 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
673 case 7: /* matched "ip" */ 690 case 7: /* matched "ip" */
674 { 691 {
675 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16; 692 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16;
676 len = urlencoded_parse(&read_ptr, tmp_buf2, SCAN_SEARCHPATH_VALUE); 693 /* One short of the end, for the terminator below */
694 len = urlencoded_parse(&read_ptr, tmp_buf2, ws->outbuf + G_OUTBUF_SIZE - 1, SCAN_SEARCHPATH_VALUE);
695 if (len <= 0)
696 HTTPERROR_400_PARAM;
677 tmp_buf2[len] = 0; 697 tmp_buf2[len] = 0;
678 if ((len <= 0) || ip_parse(tmp_buf2, tmp_buf1) != (size_t)len) 698 if (ip_parse(tmp_buf2, tmp_buf1) != (size_t)len)
679 HTTPERROR_400_PARAM; 699 HTTPERROR_400_PARAM;
680 OT_SETIP(&ws->peer, tmp_buf1); 700 OT_SETIP(&ws->peer, tmp_buf1);
681 } break; 701 } break;
682#endif 702#endif
683 case 8: /* matched "peer_id" */ 703 case 8: /* matched "peer_id" */
684 /* ignore this, when we have less than 20 bytes */ 704 /* ignore this, when we have less than 20 bytes */
685 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE) != 20) 705 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
686 HTTPERROR_400_PARAM; 706 HTTPERROR_400_PARAM;
687 ws->peer_id = write_ptr; 707 ws->peer_id = write_ptr;
688 break; 708 break;
@@ -729,6 +749,7 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
729 subroutine gets to answer: an error reply finishes with the connection 749 subroutine gets to answer: an error reply finishes with the connection
730 on its way out, and ws outlives the connection it was serving */ 750 on its way out, and ws outlives the connection it was serving */
731 ws->keep_alive = 0; 751 ws->keep_alive = 0;
752 ws->handed_off = 0;
732#ifdef WANT_KEEPALIVE 753#ifdef WANT_KEEPALIVE
733 if ((write_ptr = http_header(ws->request, ws->header_size, "connection")) && (*write_ptr == 'K' || *write_ptr == 'k')) 754 if ((write_ptr = http_header(ws->request, ws->header_size, "connection")) && (*write_ptr == 'K' || *write_ptr == 'k'))
734 ws->keep_alive = 1; 755 ws->keep_alive = 1;
@@ -743,8 +764,8 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
743 } 764 }
744 } 765 }
745 766
746 /* This one implicitely tests strlen < 5, too -- remember, it is \n terminated */ 767 /* The request need not be NUL terminated and can be shorter than the literal */
747 if (memcmp(read_ptr, "GET /", 5)) 768 if (ws->request_size < 5 || memcmp(read_ptr, "GET /", 5))
748 HTTPERROR_400; 769 HTTPERROR_400;
749 770
750 /* Skip leading '/' */ 771 /* Skip leading '/' */
@@ -755,7 +776,7 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
755 In reality we abandoned requiring the url to be correct. This now 776 In reality we abandoned requiring the url to be correct. This now
756 only decodes url encoded characters, we check for announces and 777 only decodes url encoded characters, we check for announces and
757 scrapes by looking for "a*" or "sc" */ 778 scrapes by looking for "a*" or "sc" */
758 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, SCAN_PATH); 779 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_PATH);
759 780
760 /* If parsing returned an error, leave with not found */ 781 /* If parsing returned an error, leave with not found */
761 if (g_redirecturl && (len == -2)) 782 if (g_redirecturl && (len == -2))
@@ -767,7 +788,7 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
767 if ((*write_ptr == 'a') || (*write_ptr == '?')) 788 if ((*write_ptr == 'a') || (*write_ptr == '?'))
768 http_handle_announce(sock, ws, read_ptr); 789 http_handle_announce(sock, ws, read_ptr);
769#ifdef WANT_FULLSCRAPE 790#ifdef WANT_FULLSCRAPE
770 else if (!memcmp(write_ptr, "scrape HTTP/", 12)) 791 else if (ws->request + ws->request_size - write_ptr >= 12 && !memcmp(write_ptr, "scrape HTTP/", 12))
771 http_handle_fullscrape(sock, ws); 792 http_handle_fullscrape(sock, ws);
772#endif 793#endif
773 /* This is the hardcore match for scrape */ 794 /* This is the hardcore match for scrape */
diff --git a/src/ot_livesync.c b/src/ot_livesync.c
index 85577f7..1381b3b 100644
--- a/src/ot_livesync.c
+++ b/src/ot_livesync.c
@@ -30,7 +30,7 @@ static uint16_t g_port = LIVESYNC_PORT;
30#define LIVESYNC_INCOMING_BUFFSIZE (256 * 256) 30#define LIVESYNC_INCOMING_BUFFSIZE (256 * 256)
31 31
32#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480 32#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480
33#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_peer) + sizeof(ot_hash)) 33#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_hash) + OT_PEER_SIZE6)
34 34
35#define LIVESYNC_MAXDELAY 15 /* seconds */ 35#define LIVESYNC_MAXDELAY 15 /* seconds */
36 36
@@ -127,6 +127,10 @@ static void livesync_issue_peersync(sync_buffer *buf) {
127 char mycopy[LIVESYNC_OUTGOING_BUFFSIZE_PEERS]; 127 char mycopy[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
128 size_t fill = buf->fill; 128 size_t fill = buf->fill;
129 129
130 /* The flush watermark keeps fill within the buffer */
131 if (fill > LIVESYNC_OUTGOING_BUFFSIZE_PEERS)
132 fill = LIVESYNC_OUTGOING_BUFFSIZE_PEERS;
133
130 memcpy(mycopy, buf->data, fill); 134 memcpy(mycopy, buf->data, fill);
131 buf->fill = sizeof(g_tracker_id) + sizeof(uint32_t); 135 buf->fill = sizeof(g_tracker_id) + sizeof(uint32_t);
132 buf->next_packet_time = time_future_seconds(LIVESYNC_MAXDELAY); 136 buf->next_packet_time = time_future_seconds(LIVESYNC_MAXDELAY);
@@ -178,13 +182,13 @@ void livesync_ticker(void) {
178 182
179 /* livesync_issue_peersync sets g_next_packet_time */ 183 /* livesync_issue_peersync sets g_next_packet_time */
180 pthread_mutex_lock(&g_outbuf_mutex); 184 pthread_mutex_lock(&g_outbuf_mutex);
181 if (time_now_seconds() > g_v6_buf.next_packet_time && g_v6_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t)) 185 if (time_is_past(g_v6_buf.next_packet_time) && g_v6_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t))
182 livesync_issue_peersync(&g_v6_buf); 186 livesync_issue_peersync(&g_v6_buf);
183 else 187 else
184 pthread_mutex_unlock(&g_outbuf_mutex); 188 pthread_mutex_unlock(&g_outbuf_mutex);
185 189
186 pthread_mutex_lock(&g_outbuf_mutex); 190 pthread_mutex_lock(&g_outbuf_mutex);
187 if (time_now_seconds() > g_v4_buf.next_packet_time && g_v4_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t)) 191 if (time_is_past(g_v4_buf.next_packet_time) && g_v4_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t))
188 livesync_issue_peersync(&g_v4_buf); 192 livesync_issue_peersync(&g_v4_buf);
189 else 193 else
190 pthread_mutex_unlock(&g_outbuf_mutex); 194 pthread_mutex_unlock(&g_outbuf_mutex);
diff --git a/src/ot_socket.c b/src/ot_socket.c
index b6a1803..8b17080 100644
--- a/src/ot_socket.c
+++ b/src/ot_socket.c
@@ -161,6 +161,20 @@ int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing) {
161 return s; 161 return s;
162} 162}
163 163
164int socket_udp_is_taken(const ot_ip6 ip, uint16_t port) {
165 struct sockaddr_in6 sa;
166 int s = socket_v6(SOCK_DGRAM), taken;
167
168 if (s == -1)
169 return 0;
170
171 /* Asking for no sharing at all is refused whatever the holder allowed */
172 sockaddr_from_ip(&sa, ip, port);
173 taken = bind(s, (struct sockaddr *)&sa, sizeof(sa)) == -1 && errno == EADDRINUSE;
174 close(s);
175 return taken;
176}
177
164int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport) { 178int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport) {
165 struct sockaddr_in6 sa; 179 struct sockaddr_in6 sa;
166 int s = socket_v6(SOCK_STREAM); 180 int s = socket_v6(SOCK_STREAM);
diff --git a/src/ot_socket.h b/src/ot_socket.h
index 5c1d840..33446e4 100644
--- a/src/ot_socket.h
+++ b/src/ot_socket.h
@@ -32,6 +32,8 @@ int socket_can_balance(void);
32int socket_tcp_listen(const ot_ip6 ip, uint16_t port, socket_sharing sharing); 32int socket_tcp_listen(const ot_ip6 ip, uint16_t port, socket_sharing sharing);
33int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing); 33int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing);
34 34
35int socket_udp_is_taken(const ot_ip6 ip, uint16_t port);
36
35int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport); 37int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport);
36int socket_is_connected(int s); 38int socket_is_connected(int s);
37int socket_accept(int s, ot_ip6 ip, uint16_t *port); 39int socket_accept(int s, ot_ip6 ip, uint16_t *port);
diff --git a/src/ot_stats.c b/src/ot_stats.c
index 2d6335b..95f3cff 100644
--- a/src/ot_stats.c
+++ b/src/ot_stats.c
@@ -83,7 +83,7 @@ static void counters_total(unsigned long long *total) {
83 pthread_mutex_unlock(&g_counter_mutex); 83 pthread_mutex_unlock(&g_counter_mutex);
84} 84}
85 85
86#define COUNT(index, by) atomic_fetch_add_explicit(ws->counters + (index), (unsigned long long)(by), memory_order_relaxed) 86#define COUNT(index, by) atomic_fetch_add_explicit(ws->counters + (index), (unsigned long)(by), memory_order_relaxed)
87 87
88static const char *ot_failed_request_names[] = { 88static const char *ot_failed_request_names[] = {
89 "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest", 89 "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest",
@@ -91,12 +91,13 @@ static const char *ot_failed_request_names[] = {
91 91
92static time_t ot_start_time; 92static time_t ot_start_time;
93 93
94#ifdef WANT_SPOT_WOODPECKER
94#define STATS_NETWORK_NODE_BITWIDTH 4 95#define STATS_NETWORK_NODE_BITWIDTH 4
95#define STATS_NETWORK_NODE_COUNT (1 << STATS_NETWORK_NODE_BITWIDTH) 96#define STATS_NETWORK_NODE_COUNT (1 << STATS_NETWORK_NODE_BITWIDTH)
96 97
97#define __BYTE(P, D) (((uint8_t *)P)[D / 8]) 98#define __BYTE(P, D) (((uint8_t *)(P))[(D) / 8])
98#define __MSK (STATS_NETWORK_NODE_COUNT - 1) 99#define __MSK (STATS_NETWORK_NODE_COUNT - 1)
99#define __SHFT(D) ((D ^ STATS_NETWORK_NODE_BITWIDTH) & STATS_NETWORK_NODE_BITWIDTH) 100#define __SHFT(D) (((D) ^ STATS_NETWORK_NODE_BITWIDTH) & STATS_NETWORK_NODE_BITWIDTH)
100 101
101#define __LDR(P, D) ((__BYTE((P), (D)) >> __SHFT((D))) & __MSK) 102#define __LDR(P, D) ((__BYTE((P), (D)) >> __SHFT((D))) & __MSK)
102#define __STR(P, D, V) __BYTE((P), (D)) = (__BYTE((P), (D)) & ~(__MSK << __SHFT((D)))) | ((V) << __SHFT((D))) 103#define __STR(P, D, V) __BYTE((P), (D)) = (__BYTE((P), (D)) & ~(__MSK << __SHFT((D)))) | ((V) << __SHFT((D)))
@@ -236,50 +237,6 @@ static void stats_return_busy_networks(char **reply, const char *reply_end, stat
236 fmt_append(reply, reply_end, "\n"); 237 fmt_append(reply, reply_end, "\n");
237} 238}
238 239
239static void stats_slash24s_txt(char **reply, const char *reply_end, size_t amount) {
240 stats_network_node *slash24s_network_counters_root = NULL;
241 size_t i, bucket, peer_size = OT_PEER_SIZE4;
242
243 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
244 ot_vector *torrents_list = mutex_bucket_lock(bucket);
245 for (i = 0; i < torrents_list->size; ++i) {
246 ot_peerlist *peer_list = (((ot_torrent *)(torrents_list->data))[i]).peer_list4;
247 ot_vector *bucket_list = &peer_list->peers;
248 int num_buckets = 1;
249
250 if (OT_PEERLIST_HASBUCKETS(peer_list)) {
251 num_buckets = bucket_list->size;
252 bucket_list = (ot_vector *)bucket_list->data;
253 }
254
255 while (num_buckets--) {
256 ot_peer *peers = (ot_peer *)bucket_list->data;
257 size_t numpeers = bucket_list->size;
258 while (numpeers--) {
259 if (stat_increase_network_count(&slash24s_network_counters_root, 0, (uintptr_t)(peers)))
260 goto bailout_unlock;
261 peers += peer_size;
262 }
263 ++bucket_list;
264 }
265 }
266 mutex_bucket_unlock(bucket, 0);
267 if (!g_opentracker_running)
268 goto done;
269 }
270
271 /* The tree is built. Now analyze */
272 stats_return_busy_networks(reply, reply_end, slash24s_network_counters_root, amount, STATS_NETWORK_NODE_MAXDEPTH);
273 stats_return_busy_networks(reply, reply_end, slash24s_network_counters_root, amount, STATS_NETWORK_NODE_LIMIT);
274 goto done;
275
276bailout_unlock:
277 mutex_bucket_unlock(bucket, 0);
278done:
279 stats_shift_down_network_count(&slash24s_network_counters_root, 0, sizeof(int) * 8 - 1);
280}
281
282#ifdef WANT_SPOT_WOODPECKER
283static stats_network_node *stats_woodpeckers_tree; 240static stats_network_node *stats_woodpeckers_tree;
284static pthread_mutex_t g_woodpeckers_mutex = PTHREAD_MUTEX_INITIALIZER; 241static pthread_mutex_t g_woodpeckers_mutex = PTHREAD_MUTEX_INITIALIZER;
285 242
@@ -299,8 +256,8 @@ typedef struct {
299static int torrent_statter(ot_torrent *torrent, uintptr_t data) { 256static int torrent_statter(ot_torrent *torrent, uintptr_t data) {
300 torrent_stats *stats = (torrent_stats *)data; 257 torrent_stats *stats = (torrent_stats *)data;
301 stats->torrent_count++; 258 stats->torrent_count++;
302 stats->peer_count += torrent->peer_list6->peer_count + torrent->peer_list4->peer_count; 259 stats->peer_count += torrent_peer_count(torrent);
303 stats->seed_count += torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 260 stats->seed_count += torrent_seed_count(torrent);
304 return 0; 261 return 0;
305} 262}
306 263
@@ -343,8 +300,8 @@ void stats_top_txt(char **reply, const char *reply_end, size_t amount) {
343 ot_vector *torrents_list = mutex_bucket_lock(bucket); 300 ot_vector *torrents_list = mutex_bucket_lock(bucket);
344 for (j = 0; j < torrents_list->size; ++j) { 301 for (j = 0; j < torrents_list->size; ++j) {
345 ot_torrent *torrent = (ot_torrent *)(torrents_list->data) + j; 302 ot_torrent *torrent = (ot_torrent *)(torrents_list->data) + j;
346 size_t peer_count = torrent->peer_list6->peer_count + torrent->peer_list4->peer_count; 303 size_t peer_count = torrent_peer_count(torrent);
347 size_t seed_count = torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 304 size_t seed_count = torrent_seed_count(torrent);
348 size_t leech_count = peer_count - seed_count; 305 size_t leech_count = peer_count - seed_count;
349 306
350 stats_insert_into_highscore(peer_count, top100c, amount, &torrent->hash); 307 stats_insert_into_highscore(peer_count, top100c, amount, &torrent->hash);
@@ -373,7 +330,7 @@ void stats_top_txt(char **reply, const char *reply_end, size_t amount) {
373static unsigned long events_per_time(unsigned long long events, time_t t) { return events / ((unsigned int)t ? (unsigned int)t : 1); } 330static unsigned long events_per_time(unsigned long long events, time_t t) { return events / ((unsigned int)t ? (unsigned int)t : 1); }
374 331
375static void stats_connections_mrtg(char **reply, const char *reply_end) { 332static void stats_connections_mrtg(char **reply, const char *reply_end) {
376 ot_time t = time(NULL) - ot_start_time; 333 ot_time t = time_since_seconds(ot_start_time);
377 unsigned long long total[OT_COUNTER_COUNT]; 334 unsigned long long total[OT_COUNTER_COUNT];
378 335
379 counters_total(total); 336 counters_total(total);
@@ -386,7 +343,7 @@ static void stats_connections_mrtg(char **reply, const char *reply_end) {
386} 343}
387 344
388static void stats_udpconnections_mrtg(char **reply, const char *reply_end) { 345static void stats_udpconnections_mrtg(char **reply, const char *reply_end) {
389 ot_time t = time(NULL) - ot_start_time; 346 ot_time t = time_since_seconds(ot_start_time);
390 unsigned long long total[OT_COUNTER_COUNT]; 347 unsigned long long total[OT_COUNTER_COUNT];
391 348
392 counters_total(total); 349 counters_total(total);
@@ -398,7 +355,7 @@ static void stats_udpconnections_mrtg(char **reply, const char *reply_end) {
398} 355}
399 356
400static void stats_tcpconnections_mrtg(char **reply, const char *reply_end) { 357static void stats_tcpconnections_mrtg(char **reply, const char *reply_end) {
401 time_t t = time(NULL) - ot_start_time; 358 time_t t = time_since_seconds(ot_start_time);
402 unsigned long long total[OT_COUNTER_COUNT]; 359 unsigned long long total[OT_COUNTER_COUNT];
403 360
404 counters_total(total); 361 counters_total(total);
@@ -409,7 +366,7 @@ static void stats_tcpconnections_mrtg(char **reply, const char *reply_end) {
409} 366}
410 367
411static void stats_scrape_mrtg(char **reply, const char *reply_end) { 368static void stats_scrape_mrtg(char **reply, const char *reply_end) {
412 time_t t = time(NULL) - ot_start_time; 369 time_t t = time_since_seconds(ot_start_time);
413 unsigned long long total[OT_COUNTER_COUNT]; 370 unsigned long long total[OT_COUNTER_COUNT];
414 371
415 counters_total(total); 372 counters_total(total);
@@ -420,7 +377,7 @@ static void stats_scrape_mrtg(char **reply, const char *reply_end) {
420} 377}
421 378
422static void stats_fullscrapes_mrtg(char **reply, const char *reply_end) { 379static void stats_fullscrapes_mrtg(char **reply, const char *reply_end) {
423 ot_time t = time(NULL) - ot_start_time; 380 ot_time t = time_since_seconds(ot_start_time);
424 unsigned long long total[OT_COUNTER_COUNT]; 381 unsigned long long total[OT_COUNTER_COUNT];
425 382
426 counters_total(total); 383 counters_total(total);
@@ -468,7 +425,7 @@ static void stats_return_renew_bucket(char **reply, const char *reply_end) {
468} 425}
469 426
470static void stats_return_sync_mrtg(char **reply, const char *reply_end) { 427static void stats_return_sync_mrtg(char **reply, const char *reply_end) {
471 ot_time t = time(NULL) - ot_start_time; 428 ot_time t = time_since_seconds(ot_start_time);
472 unsigned long long total[OT_COUNTER_COUNT]; 429 unsigned long long total[OT_COUNTER_COUNT];
473 430
474 counters_total(total); 431 counters_total(total);
@@ -479,7 +436,7 @@ static void stats_return_sync_mrtg(char **reply, const char *reply_end) {
479} 436}
480 437
481static void stats_return_completed_mrtg(char **reply, const char *reply_end) { 438static void stats_return_completed_mrtg(char **reply, const char *reply_end) {
482 ot_time t = time(NULL) - ot_start_time; 439 ot_time t = time_since_seconds(ot_start_time);
483 unsigned long long total[OT_COUNTER_COUNT]; 440 unsigned long long total[OT_COUNTER_COUNT];
484 441
485 counters_total(total); 442 counters_total(total);
@@ -494,7 +451,7 @@ extern unsigned long long numwants[201];
494static void stats_return_numwants(char **reply, const char *reply_end) { 451static void stats_return_numwants(char **reply, const char *reply_end) {
495 int i; 452 int i;
496 for (i = 0; i <= 200; ++i) 453 for (i = 0; i <= 200; ++i)
497 fmt_append(reply, reply_end, "%03d => %lld\n", i, numwants[i]); 454 fmt_append(reply, reply_end, "%03d => %llu\n", i, numwants[i]);
498} 455}
499#endif 456#endif
500 457
@@ -510,7 +467,7 @@ static void stats_return_everything(char **reply, const char *reply_end) {
510 467
511 fmt_append(reply, reply_end, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); 468 fmt_append(reply, reply_end, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
512 fmt_append(reply, reply_end, "<stats>\n"); 469 fmt_append(reply, reply_end, "<stats>\n");
513 fmt_append(reply, reply_end, " <uptime>%llu</uptime>\n", (unsigned long long)(time(NULL) - ot_start_time)); 470 fmt_append(reply, reply_end, " <uptime>%llu</uptime>\n", (unsigned long long)time_since_seconds(ot_start_time));
514 fmt_append(reply, reply_end, " <torrents>\n"); 471 fmt_append(reply, reply_end, " <torrents>\n");
515 fmt_append(reply, reply_end, " <count_mutex>%zd</count_mutex>\n", mutex_get_torrent_count()); 472 fmt_append(reply, reply_end, " <count_mutex>%zd</count_mutex>\n", mutex_get_torrent_count());
516 fmt_append(reply, reply_end, " <count_iterator>%llu</count_iterator>\n", stats.torrent_count); 473 fmt_append(reply, reply_end, " <count_iterator>%llu</count_iterator>\n", stats.torrent_count);
@@ -588,6 +545,9 @@ static const char *const build_features[] = {
588#ifdef WANT_RESTRICT_STATS 545#ifdef WANT_RESTRICT_STATS
589 "WANT_RESTRICT_STATS", 546 "WANT_RESTRICT_STATS",
590#endif 547#endif
548#ifdef WANT_RESTRICT_FULLSCRAPE
549 "WANT_RESTRICT_FULLSCRAPE",
550#endif
591#ifdef WANT_LOG_NUMWANT 551#ifdef WANT_LOG_NUMWANT
592 "WANT_LOG_NUMWANT", 552 "WANT_LOG_NUMWANT",
593#endif 553#endif
@@ -692,9 +652,6 @@ static void stats_make(size_t *iovec_entries, struct iovec **iovector, ot_taskty
692 case TASK_STATS_PEERS: 652 case TASK_STATS_PEERS:
693 stats_peers_mrtg(&r, r_end); 653 stats_peers_mrtg(&r, r_end);
694 break; 654 break;
695 case TASK_STATS_SLASH24S:
696 stats_slash24s_txt(&r, r_end, 128);
697 break;
698 case TASK_STATS_TOP10: 655 case TASK_STATS_TOP10:
699 stats_top_txt(&r, r_end, 10); 656 stats_top_txt(&r, r_end, 10);
700 break; 657 break;
@@ -757,7 +714,8 @@ void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FL
757 714
758 time(&ttt); 715 time(&ttt);
759 localtime_r(&ttt, &time_now); 716 localtime_r(&ttt, &time_now);
760 strftime(timestring, sizeof(timestring), "%FT%T%z", &time_now); 717 if (!strftime(timestring, sizeof(timestring), "%FT%T%z", &time_now))
718 timestring[0] = 0;
761 719
762 hex_from_hash(hash_hex, *ws->hash); 720 hex_from_hash(hash_hex, *ws->hash);
763 if (ws->peer_id) 721 if (ws->peer_id)
@@ -785,26 +743,28 @@ void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FL
785 case EVENT_FULLSCRAPE_REQUEST: { 743 case EVENT_FULLSCRAPE_REQUEST: {
786 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */ 744 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */
787 char _debug[512]; 745 char _debug[512];
788 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)(time_now_seconds() - ot_start_time) / 60); 746 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)time_since_seconds(ot_start_time) / 60);
789 off += ip_format(_debug + off, *ip); 747 off += ip_format(_debug + off, *ip);
790 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n"); 748 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n");
791 (void)write(2, _debug, off); 749 (void)!write(2, _debug, off);
792 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1); 750 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1);
793 } break; 751 } break;
794 case EVENT_FULLSCRAPE_REQUEST_GZIP: { 752 case EVENT_FULLSCRAPE_REQUEST_GZIP: {
795 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */ 753 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */
796 char _debug[512]; 754 char _debug[512];
797 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)(time_now_seconds() - ot_start_time) / 60); 755 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)time_since_seconds(ot_start_time) / 60);
798 off += ip_format(_debug + off, *ip); 756 off += ip_format(_debug + off, *ip);
799 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n"); 757 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n");
800 (void)write(2, _debug, off); 758 (void)!write(2, _debug, off);
801 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1); 759 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1);
802 } break; 760 } break;
803 case EVENT_FAILED: 761 case EVENT_FAILED:
804 COUNT(OT_COUNTER_FAILED + event_data, 1); 762 if (event_data < CODE_HTTPERROR_COUNT)
763 COUNT(OT_COUNTER_FAILED + event_data, 1);
805 break; 764 break;
806 case EVENT_RENEW: 765 case EVENT_RENEW:
807 COUNT(OT_COUNTER_RENEWED + event_data, 1); 766 if (event_data < OT_PEER_TIMEOUT)
767 COUNT(OT_COUNTER_RENEWED + event_data, 1);
808 break; 768 break;
809 case EVENT_SYNC: 769 case EVENT_SYNC:
810 COUNT(OT_COUNTER_SYNCS, event_data); 770 COUNT(OT_COUNTER_SYNCS, event_data);
diff --git a/src/ot_tcp.c b/src/ot_tcp.c
index 1351b92..67a0ebc 100644
--- a/src/ot_tcp.c
+++ b/src/ot_tcp.c
@@ -44,7 +44,18 @@ static ssize_t header_complete(char *request, ssize_t byte_count) {
44 44
45void tcp_read(const int64_t sock, struct ot_workstruct *ws) { 45void tcp_read(const int64_t sock, struct ot_workstruct *ws) {
46 struct http_data *cookie = fdstate_cookie(sock); 46 struct http_data *cookie = fdstate_cookie(sock);
47 ssize_t byte_count = read((int)sock, ws->inbuf, G_INBUF_SIZE); 47 ssize_t byte_count;
48 uint32_t generation;
49
50 /* We're not supposed to read from a socket that waits for
51 our answer. Prevent its reply from being sent to the next
52 generation on that fd. */
53 if (cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)) {
54 http_close(sock);
55 return;
56 }
57
58 byte_count = read((int)sock, ws->inbuf, G_INBUF_SIZE);
48 59
49 if (byte_count == 0 || (byte_count == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { 60 if (byte_count == 0 || (byte_count == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
50 http_close(sock); 61 http_close(sock);
@@ -75,10 +86,21 @@ void tcp_read(const int64_t sock, struct ot_workstruct *ws) {
75 return; 86 return;
76 } 87 }
77 88
89 generation = fdstate_generation((int)sock);
78 while ((ws->header_size = header_complete(cookie->request.data, (ssize_t)cookie->request.size))) { 90 while ((ws->header_size = header_complete(cookie->request.data, (ssize_t)cookie->request.size))) {
79 ws->request = cookie->request.data; 91 ws->request = cookie->request.data;
80 ws->request_size = (ssize_t)cookie->request.size; 92 ws->request_size = (ssize_t)cookie->request.size;
81 http_handle_request(sock, ws); 93 http_handle_request(sock, ws);
94
95 /* A worker owns the connection now, and the buffer this loop reads hangs
96 off it, so there is nothing here left to look at */
97 if (ws->handed_off)
98 return;
99
100 /* The handler may have closed the connection inline, for instance on a
101 write error, which frees the cookie this loop reads from */
102 if (fdstate_generation((int)sock) != generation)
103 return;
82#ifdef WANT_KEEPALIVE 104#ifdef WANT_KEEPALIVE
83 if (!ws->keep_alive) 105 if (!ws->keep_alive)
84#endif 106#endif
diff --git a/src/ot_udp.c b/src/ot_udp.c
index 644b71d..609089b 100644
--- a/src/ot_udp.c
+++ b/src/ot_udp.c
@@ -19,6 +19,9 @@
19#include "ot_udp.h" 19#include "ot_udp.h"
20#include "trackerlogic.h" 20#include "trackerlogic.h"
21 21
22/* BEP 15: "Up to about 74 torrents can be scraped at once" */
23#define OT_MAX_SCRAPE_UDP 74
24
22static uint32_t g_rijndael_round_key[44] = {0}; 25static uint32_t g_rijndael_round_key[44] = {0};
23static volatile uint32_t g_key_of_the_hour[2] = {0}; 26static volatile uint32_t g_key_of_the_hour[2] = {0};
24static volatile ot_time g_hour_of_the_key; 27static volatile ot_time g_hour_of_the_key;
@@ -39,12 +42,12 @@ static void udp_make_connectionid(uint32_t connid[2], const ot_ip6 remoteip, int
39 int i; 42 int i;
40 uint32_t current_key_of_the_hour; 43 uint32_t current_key_of_the_hour;
41 44
42 if (time_now_minutes() - g_hour_of_the_key >= 60) { 45 if (time_since_minutes(g_hour_of_the_key) >= 60) {
43 uint32_t old_key_of_the_hour = g_key_of_the_hour[0]; 46 uint32_t old_key_of_the_hour = g_key_of_the_hour[0];
44 uint32_t new_key_of_the_hour = random_uint32(); 47 uint32_t new_key_of_the_hour = random_uint32();
45 /* If in the meantime another thread has performed 48 /* If in the meantime another thread has performed
46 key rotation, do not overwrite their results */ 49 key rotation, do not overwrite their results */
47 if (time_now_minutes() - g_hour_of_the_key >= 60) { 50 if (time_since_minutes(g_hour_of_the_key) >= 60) {
48 /* Upgrade en bloc */ 51 /* Upgrade en bloc */
49 g_hour_of_the_key = time_now_minutes(); 52 g_hour_of_the_key = time_now_minutes();
50 g_key_of_the_hour[0] = new_key_of_the_hour; 53 g_key_of_the_hour[0] = new_key_of_the_hour;
@@ -61,18 +64,71 @@ static void udp_make_connectionid(uint32_t connid[2], const ot_ip6 remoteip, int
61 connid[1] = crypt[2] ^ crypt[3]; 64 connid[1] = crypt[2] ^ crypt[3];
62} 65}
63 66
67/* BEP 15 packet layouts, as byte offsets into the datagram */
68enum {
69 /* Every request starts alike */
70 UDP_REQUEST_CONNECTION_ID_OFFSET = 0,
71 UDP_REQUEST_ACTION_OFFSET = 8,
72 UDP_REQUEST_TRANSACTION_ID_OFFSET = 12,
73 UDP_REQUEST_HEADER_SIZE = 16,
74
75 UDP_ANNOUNCE_INFO_HASH_OFFSET = 16,
76 UDP_ANNOUNCE_LEFT_OFFSET = 64, /* 64 bit */
77 UDP_ANNOUNCE_EVENT_OFFSET = 80,
78 UDP_ANNOUNCE_NUM_WANT_OFFSET = 92,
79 UDP_ANNOUNCE_PORT_OFFSET = 96, /* 16 bit */
80 UDP_ANNOUNCE_SIZE = 98,
81
82 UDP_SCRAPE_INFO_HASH_OFFSET = 16,
83
84 /* And so does every reply */
85 UDP_REPLY_ACTION_OFFSET = 0,
86 UDP_REPLY_TRANSACTION_ID_OFFSET = 4,
87 UDP_REPLY_HEADER_SIZE = 8
88};
89
90enum { UDP_ACTION_CONNECT = 0, UDP_ACTION_ANNOUNCE = 1, UDP_ACTION_SCRAPE = 2, UDP_ACTION_ERROR = 3 };
91enum { UDP_EVENT_COMPLETED = 1, UDP_EVENT_STOPPED = 3 };
92
93/* What a client puts where the connection id goes, when it asks for one */
94static const uint8_t g_udp_protocol_id[8] = {0x00, 0x00, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80};
95
96static uint32_t udp_read32(const char *packet, size_t offset) {
97 uint32_t value;
98 memcpy(&value, packet + offset, sizeof(value));
99 return ntohl(value);
100}
101
102/* Returns where the rest of the reply goes */
103static char *udp_reply_header(char *reply, uint32_t action, const char *request) {
104 action = htonl(action);
105 memcpy(reply + UDP_REPLY_ACTION_OFFSET, &action, sizeof(action));
106 memcpy(reply + UDP_REPLY_TRANSACTION_ID_OFFSET, request + UDP_REQUEST_TRANSACTION_ID_OFFSET, sizeof(uint32_t));
107 return reply + UDP_REPLY_HEADER_SIZE;
108}
109
110static void udp_send_error(int64_t serversocket, struct ot_workstruct *ws, const char *message, const ot_ip6 remoteip, uint16_t remoteport) {
111 size_t size = strlen(message) + 1;
112 char *reply = udp_reply_header(ws->outbuf, UDP_ACTION_ERROR, ws->inbuf);
113
114 memcpy(reply, message, size);
115 ws->reply_size = UDP_REPLY_HEADER_SIZE + size;
116 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
117}
118
64/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */ 119/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */
65int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) { 120int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
66 ot_ip6 remoteip; 121 ot_ip6 remoteip;
67 uint32_t *inpacket = (uint32_t *)ws->inbuf; 122 const char *request = ws->inbuf;
68 uint32_t *outpacket = (uint32_t *)ws->outbuf; 123 char *reply;
69 uint32_t left, event; 124 uint32_t left, event, numwant;
70 uint32_t connid[2]; 125 uint32_t connid[2];
71 uint32_t action; 126 uint32_t action;
72 uint16_t port, remoteport; 127 uint16_t port, remoteport;
73 size_t byte_count, scrape_count; 128 size_t byte_count, scrape_count, max_peers, i;
129 ot_hash *hashes;
74 130
75 ssize_t result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport); 131 ssize_t result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport);
76 if (result <= 0) 132 if (result <= 0)
77 return 0; 133 return 0;
78 byte_count = (size_t)result; 134 byte_count = (size_t)result;
@@ -81,12 +137,12 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
81 stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count); 137 stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count);
82 138
83 /* Minimum udp tracker packet size, also catches error */ 139 /* Minimum udp tracker packet size, also catches error */
84 if (byte_count < 16) 140 if (byte_count < UDP_REQUEST_HEADER_SIZE)
85 return 1; 141 return 1;
86 142
87 /* Get action to take. Ignore error messages and broken packets */ 143 /* Get action to take. Ignore error messages and broken packets */
88 action = ntohl(inpacket[2]); 144 action = udp_read32(request, UDP_REQUEST_ACTION_OFFSET);
89 if (action > 2) 145 if (action > UDP_ACTION_SCRAPE)
90 return 1; 146 return 1;
91 147
92 /* Generate the connection id we give out and expect to and from 148 /* Generate the connection id we give out and expect to and from
@@ -97,108 +153,98 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
97 ws->hash = NULL; 153 ws->hash = NULL;
98 ws->peer_id = NULL; 154 ws->peer_id = NULL;
99 155
100 /* If action is not 0 (connect), then we expect the derived 156 /* If action is not connect, then we expect the derived
101 connection id in first 64 bit */ 157 connection id in first 64 bit */
102 if ((action > 0) && (inpacket[0] != connid[0] || inpacket[1] != connid[1])) { 158 if (action != UDP_ACTION_CONNECT && memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
103 /* If connection id does not match, try the one that was 159 /* If connection id does not match, try the one that was
104 valid in the previous hour. Only if this also does not 160 valid in the previous hour. Only if this also does not
105 match, return an error packet */ 161 match, return an error packet */
106 udp_make_connectionid(connid, remoteip, 1); 162 udp_make_connectionid(connid, remoteip, 1);
107 if (inpacket[0] != connid[0] || inpacket[1] != connid[1]) { 163 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
108 const char err_idmiss[] = "Connection ID missmatch."; 164 static const char err_idmiss[] = "Connection ID missmatch.";
109 size_t s = sizeof(err_idmiss); 165
110 outpacket[0] = htonl(3); 166 /* Nobody has vouched for this address yet, so it is not sent more
111 outpacket[1] = inpacket[3]; 167 than was sent in its name */
112 memcpy(&outpacket[2], &err_idmiss[0], s); 168 if (byte_count >= UDP_REPLY_HEADER_SIZE + sizeof(err_idmiss))
113 socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport); 169 udp_send_error(serversocket, ws, err_idmiss, remoteip, remoteport);
114 stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, 8 + s); 170 stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, byte_count);
115 return 1; 171 return 1;
116 } 172 }
117 } 173 }
118 174
119 switch (action) { 175 switch (action) {
120 case 0: /* This is a connect action */ 176 case UDP_ACTION_CONNECT:
121 /* look for udp bittorrent magic id */ 177 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, g_udp_protocol_id, sizeof(g_udp_protocol_id)))
122 if ((ntohl(inpacket[0]) != 0x00000417) || (ntohl(inpacket[1]) != 0x27101980))
123 return 1; 178 return 1;
124 179
125 outpacket[0] = 0; 180 reply = udp_reply_header(ws->outbuf, UDP_ACTION_CONNECT, request);
126 outpacket[1] = inpacket[3]; 181 memcpy(reply, connid, sizeof(connid));
127 outpacket[2] = connid[0]; 182 reply += sizeof(connid);
128 outpacket[3] = connid[1];
129 183
130 socket_send(serversocket, ws->outbuf, 16, remoteip, remoteport); 184 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
131 stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, 16); 185 stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, reply - ws->outbuf);
132 break; 186 break;
133 case 1: /* This is an announce action */ 187
134 /* Minimum udp announce packet size */ 188 case UDP_ACTION_ANNOUNCE:
135 if (byte_count < 98) 189 if (byte_count < UDP_ANNOUNCE_SIZE)
136 return 1; 190 return 1;
137 191
138 /* We do only want to know, if it is zero */ 192 /* We do only want to know, if it is zero */
139 left = inpacket[64 / 4] | inpacket[68 / 4]; 193 left = udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET) | udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET + sizeof(uint32_t));
194 event = udp_read32(request, UDP_ANNOUNCE_EVENT_OFFSET);
195 numwant = udp_read32(request, UDP_ANNOUNCE_NUM_WANT_OFFSET);
196 ws->hash = (ot_hash *)(ws->inbuf + UDP_ANNOUNCE_INFO_HASH_OFFSET);
140 197
141 event = ntohl(inpacket[80 / 4]); 198 /* The peer keeps its port the way it came over the wire */
142 port = *(uint16_t *)(((char *)inpacket) + 96); 199 memcpy(&port, request + UDP_ANNOUNCE_PORT_OFFSET, sizeof(port));
143 ws->hash = (ot_hash *)(((char *)inpacket) + 16);
144 200
145 OT_SETIP(ws->peer, remoteip); 201 OT_SETIP(ws->peer, remoteip);
146 OT_SETPORT(ws->peer, &port); 202 OT_SETPORT(ws->peer, &port);
147 OT_PEERFLAG(ws->peer) = 0; 203 OT_PEERFLAG(ws->peer) = 0;
148 204
149 switch (event) { 205 if (event == UDP_EVENT_COMPLETED)
150 case 1:
151 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED; 206 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
152 break; 207 if (event == UDP_EVENT_STOPPED)
153 case 3:
154 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED; 208 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED;
155 break;
156 default:
157 break;
158 }
159
160 if (!left) 209 if (!left)
161 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING; 210 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;
162 211
163 outpacket[0] = htonl(1); /* announce action */ 212 ws->reply = udp_reply_header(ws->outbuf, UDP_ACTION_ANNOUNCE, request);
164 outpacket[1] = inpacket[12 / 4];
165 213
166 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */ 214 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */
167 ws->reply = ws->outbuf;
168 ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws); 215 ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws);
169 } else { 216 } else {
170 /* Limit amount of peers to OT_MAX_PEERS_UDP */ 217 /* List of peers should fit in a single UDP packet */
171 uint32_t numwant = ntohl(inpacket[92 / 4]); 218 max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
172 size_t max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
173 if (numwant > max_peers) 219 if (numwant > max_peers)
174 numwant = max_peers; 220 numwant = max_peers;
175 221
176 ws->reply = ws->outbuf + 8;
177 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant); 222 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant);
178 223
224 /* The announce path answers a refusal itself, so nothing is left here
225 but a tracker that could not get the memory to track the torrent */
179 if (!ws->reply_size) { 226 if (!ws->reply_size) {
180 const char err_unauth[] = "Requested download is not authorized for use with this tracker."; 227 udp_send_error(serversocket, ws, "Tracker is out of resources, try again later.", remoteip, remoteport);
181 size_t s = sizeof(err_unauth);
182 outpacket[0] = htonl(3);
183 memcpy(&outpacket[2], &err_unauth[0], s);
184 socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport);
185 return 1; 228 return 1;
186 } 229 }
187 ws->reply_size += 8;
188 } 230 }
231 ws->reply_size += UDP_REPLY_HEADER_SIZE;
189 232
190 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport); 233 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
191 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size); 234 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size);
192 break; 235 break;
193 236
194 case 2: /* This is a scrape action */ 237 case UDP_ACTION_SCRAPE:
195 outpacket[0] = htonl(2); /* scrape action */ 238 scrape_count = (byte_count - UDP_SCRAPE_INFO_HASH_OFFSET) / sizeof(ot_hash);
196 outpacket[1] = inpacket[12 / 4]; 239 if (scrape_count > OT_MAX_SCRAPE_UDP)
240 scrape_count = OT_MAX_SCRAPE_UDP;
197 241
198 for (scrape_count = 0; (scrape_count * 20 < byte_count - 16) && (scrape_count <= 74); scrape_count++) 242 hashes = (ot_hash *)(ws->inbuf + UDP_SCRAPE_INFO_HASH_OFFSET);
199 return_udp_scrape_for_torrent(*(ot_hash *)(((char *)inpacket) + 16 + 20 * scrape_count), ((char *)outpacket) + 8 + 12 * scrape_count); 243 reply = udp_reply_header(ws->outbuf, UDP_ACTION_SCRAPE, request);
244 for (i = 0; i < scrape_count; ++i)
245 reply += return_udp_scrape_for_torrent(hashes[i], reply);
200 246
201 socket_send(serversocket, ws->outbuf, 8 + 12 * scrape_count, remoteip, remoteport); 247 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
202 stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count); 248 stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count);
203 break; 249 break;
204 } 250 }
diff --git a/src/ot_urlencoded.c b/src/ot_urlencoded.c
index 4109bb5..c977adb 100644
--- a/src/ot_urlencoded.c
+++ b/src/ot_urlencoded.c
@@ -68,17 +68,18 @@ void urlencoded_skip_value(char **string) {
68 *string = (char *)s; 68 *string = (char *)s;
69} 69}
70 70
71int urlencoded_match_keyword(const ot_keywords *keywords, char **string, SCAN_SEARCHPATH_FLAG flags) { 71int urlencoded_match_keyword(const ot_keywords *keywords, char **string, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags) {
72 char *deststring = *string; 72 char *deststring = *string;
73 ssize_t match_length = urlencoded_parse(string, deststring, flags); 73 ssize_t match_length = urlencoded_parse(string, deststring, deststring_end, flags);
74 74
75 if (match_length < 0) 75 if (match_length < 0)
76 return match_length; 76 return match_length;
77 if (match_length == 0) 77 if (match_length == 0)
78 return -3; 78 return -3;
79 79
80 /* Compare on the exact decoded length. */
80 while (keywords->key) { 81 while (keywords->key) {
81 if (!strncmp(keywords->key, deststring, match_length) && !keywords->key[match_length]) 82 if ((size_t)match_length == strlen(keywords->key) && !memcmp(keywords->key, deststring, (size_t)match_length))
82 return keywords->value; 83 return keywords->value;
83 keywords++; 84 keywords++;
84 } 85 }
@@ -86,7 +87,7 @@ int urlencoded_match_keyword(const ot_keywords *keywords, char **string, SCAN_SE
86 return -3; 87 return -3;
87} 88}
88 89
89ssize_t urlencoded_parse(char **string, char *deststring, SCAN_SEARCHPATH_FLAG flags) { 90ssize_t urlencoded_parse(char **string, char *deststring, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags) {
90 const unsigned char *s = *(const unsigned char **)string; 91 const unsigned char *s = *(const unsigned char **)string;
91 unsigned char *d = (unsigned char *)deststring; 92 unsigned char *d = (unsigned char *)deststring;
92 unsigned char b, c; 93 unsigned char b, c;
@@ -106,6 +107,9 @@ ssize_t urlencoded_parse(char **string, char *deststring, SCAN_SEARCHPATH_FLAG f
106 c |= (b << 4); 107 c |= (b << 4);
107 } 108 }
108 109
110 if ((const char *)d >= deststring_end)
111 return -1;
112
109 /* Write (possibly decoded) character to output */ 113 /* Write (possibly decoded) character to output */
110 *d++ = c; 114 *d++ = c;
111 } 115 }
diff --git a/src/ot_urlencoded.h b/src/ot_urlencoded.h
index 9882468..053e079 100644
--- a/src/ot_urlencoded.h
+++ b/src/ot_urlencoded.h
@@ -28,7 +28,7 @@ typedef enum {
28 or -1 for parse error 28 or -1 for parse error
29 or -2 for terminator found 29 or -2 for terminator found
30*/ 30*/
31ssize_t urlencoded_parse(char **string, char *deststring, SCAN_SEARCHPATH_FLAG flags); 31ssize_t urlencoded_parse(char **string, char *deststring, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags);
32 32
33/* string in: pointer to source 33/* string in: pointer to source
34 out: pointer to next scan position 34 out: pointer to next scan position
@@ -38,7 +38,7 @@ ssize_t urlencoded_parse(char **string, char *deststring, SCAN_SEARCHPATH_FLAG f
38 or -2 for terminator found 38 or -2 for terminator found
39 or -3 for no keyword matched 39 or -3 for no keyword matched
40 */ 40 */
41int urlencoded_match_keyword(const ot_keywords *keywords, char **string, SCAN_SEARCHPATH_FLAG flags); 41int urlencoded_match_keyword(const ot_keywords *keywords, char **string, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags);
42 42
43/* string in: pointer to value of a param=value pair to skip 43/* string in: pointer to value of a param=value pair to skip
44 out: pointer to next scan position on return 44 out: pointer to next scan position on return
diff --git a/src/ot_vector.c b/src/ot_vector.c
index ab0566c..ef38919 100644
--- a/src/ot_vector.c
+++ b/src/ot_vector.c
@@ -160,13 +160,15 @@ void vector_remove_torrent(ot_vector *vector, ot_torrent *match) {
160 160
161 end = ((ot_torrent *)vector->data) + vector->size; 161 end = ((ot_torrent *)vector->data) + vector->size;
162 162
163 free_peerlist(match->peer_list6); 163 free_peerlist(match->peer_list);
164 free_peerlist(match->peer_list4);
165 164
166 memmove(match, match + 1, sizeof(ot_torrent) * (end - match - 1)); 165 memmove(match, match + 1, sizeof(ot_torrent) * (end - match - 1));
167 if ((--vector->size * OT_VECTOR_SHRINK_THRESH < vector->space) && (vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS)) { 166 if ((--vector->size * OT_VECTOR_SHRINK_THRESH < vector->space) && (vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS)) {
168 vector->space /= OT_VECTOR_SHRINK_RATIO; 167 void *new_data = realloc(vector->data, (vector->space / OT_VECTOR_SHRINK_RATIO) * sizeof(ot_torrent));
169 vector->data = realloc(vector->data, vector->space * sizeof(ot_torrent)); 168 if (new_data) {
169 vector->space /= OT_VECTOR_SHRINK_RATIO;
170 vector->data = new_data;
171 }
170 } 172 }
171} 173}
172 174
@@ -177,27 +179,27 @@ void vector_clean_list(ot_vector *vector, size_t num_buckets) {
177 return; 179 return;
178} 180}
179 181
180void vector_redistribute_buckets(ot_peerlist *peer_list, size_t peer_size) { 182void vector_redistribute_buckets(ot_vector *peer_vector, size_t peer_size, size_t peer_count) {
181 size_t bucket, bucket_size_new, num_buckets_new, num_buckets_old = 1; 183 size_t bucket, bucket_size_new, num_buckets_new, num_buckets_old = 1;
182 ot_vector *bucket_list_new, *bucket_list_old = &peer_list->peers; 184 ot_vector *bucket_list_new, *bucket_list_old = peer_vector;
183 int (*sort_func)(const void *, const void *) = peer_size == OT_PEER_SIZE6 ? &vector_compare_peer6 : &vector_compare_peer4; 185 int (*sort_func)(const void *, const void *) = peer_size == OT_PEER_SIZE6 ? &vector_compare_peer6 : &vector_compare_peer4;
184 186
185 if (OT_PEERLIST_HASBUCKETS(peer_list)) { 187 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
186 num_buckets_old = peer_list->peers.size; 188 num_buckets_old = peer_vector->size;
187 bucket_list_old = peer_list->peers.data; 189 bucket_list_old = peer_vector->data;
188 } 190 }
189 191
190 if (peer_list->peer_count < 255) 192 if (peer_count < 255)
191 num_buckets_new = 1; 193 num_buckets_new = 1;
192 else if (peer_list->peer_count > 8192) 194 else if (peer_count > 8192)
193 num_buckets_new = 64; 195 num_buckets_new = 64;
194 else if (peer_list->peer_count >= 512 && peer_list->peer_count < 4096) 196 else if (peer_count >= 512 && peer_count < 4096)
195 num_buckets_new = 16; 197 num_buckets_new = 16;
196 else if (peer_list->peer_count < 512 && num_buckets_old <= 16) 198 else if (peer_count < 512 && num_buckets_old <= 16)
197 num_buckets_new = num_buckets_old; 199 num_buckets_new = num_buckets_old;
198 else if (peer_list->peer_count < 512) 200 else if (peer_count < 512)
199 num_buckets_new = 1; 201 num_buckets_new = 1;
200 else if (peer_list->peer_count < 8192 && num_buckets_old > 1) 202 else if (peer_count < 8192 && num_buckets_old > 1)
201 num_buckets_new = num_buckets_old; 203 num_buckets_new = num_buckets_old;
202 else 204 else
203 num_buckets_new = 16; 205 num_buckets_new = 16;
@@ -211,7 +213,7 @@ void vector_redistribute_buckets(ot_peerlist *peer_list, size_t peer_size) {
211 return; 213 return;
212 214
213 bucket_size_new = OT_VECTOR_MIN_MEMBERS; 215 bucket_size_new = OT_VECTOR_MIN_MEMBERS;
214 while (bucket_size_new * num_buckets_new < peer_list->peer_count) 216 while (bucket_size_new * num_buckets_new < peer_count)
215 bucket_size_new *= OT_VECTOR_GROW_RATIO; 217 bucket_size_new *= OT_VECTOR_GROW_RATIO;
216 218
217 /* preallocate vectors to hold all peers */ 219 /* preallocate vectors to hold all peers */
@@ -250,20 +252,20 @@ void vector_redistribute_buckets(ot_peerlist *peer_list, size_t peer_size) {
250 for (bucket = 0; bucket < num_buckets_new; ++bucket) 252 for (bucket = 0; bucket < num_buckets_new; ++bucket)
251 qsort(bucket_list_new[bucket].data, bucket_list_new[bucket].size, peer_size, sort_func); 253 qsort(bucket_list_new[bucket].data, bucket_list_new[bucket].size, peer_size, sort_func);
252 254
253 /* Everything worked fine. Now link new bucket_list to peer_list */ 255 /* Everything worked fine. Now link new bucket_list to the vector */
254 if (OT_PEERLIST_HASBUCKETS(peer_list)) 256 if (OT_VECTOR_HASBUCKETS(peer_vector))
255 vector_clean_list((ot_vector *)peer_list->peers.data, peer_list->peers.size); 257 vector_clean_list((ot_vector *)peer_vector->data, peer_vector->size);
256 else 258 else
257 free(peer_list->peers.data); 259 free(peer_vector->data);
258 260
259 if (num_buckets_new > 1) { 261 if (num_buckets_new > 1) {
260 peer_list->peers.data = bucket_list_new; 262 peer_vector->data = bucket_list_new;
261 peer_list->peers.size = num_buckets_new; 263 peer_vector->size = num_buckets_new;
262 peer_list->peers.space = 0; /* Magic marker for "is list of buckets" */ 264 peer_vector->space = 0; /* Magic marker for "is list of buckets" */
263 } else { 265 } else {
264 peer_list->peers.data = bucket_list_new->data; 266 peer_vector->data = bucket_list_new->data;
265 peer_list->peers.size = bucket_list_new->size; 267 peer_vector->size = bucket_list_new->size;
266 peer_list->peers.space = bucket_list_new->space; 268 peer_vector->space = bucket_list_new->space;
267 free(bucket_list_new); 269 free(bucket_list_new);
268 } 270 }
269} 271}
@@ -282,6 +284,9 @@ void vector_fixup_peers(ot_vector *vector, size_t peer_size) {
282 vector->space /= OT_VECTOR_SHRINK_RATIO; 284 vector->space /= OT_VECTOR_SHRINK_RATIO;
283 need_fix++; 285 need_fix++;
284 } 286 }
285 if (need_fix) 287 if (need_fix) {
286 vector->data = realloc(vector->data, vector->space * peer_size); 288 void *new_data = realloc(vector->data, vector->space * peer_size);
289 if (new_data)
290 vector->data = new_data;
291 }
287} 292}
diff --git a/src/ot_vector.h b/src/ot_vector.h
index 8a5ba86..1a73fcf 100644
--- a/src/ot_vector.h
+++ b/src/ot_vector.h
@@ -32,7 +32,7 @@ int vector_remove_peer(ot_vector *vector, ot_peer const *peer, size_t peer_
32void vector_remove_torrent(ot_vector *vector, ot_torrent *match); 32void vector_remove_torrent(ot_vector *vector, ot_torrent *match);
33 33
34/* For ot_clean.c */ 34/* For ot_clean.c */
35void vector_redistribute_buckets(ot_peerlist *peer_list, size_t peer_size); 35void vector_redistribute_buckets(ot_vector *peer_vector, size_t peer_size, size_t peer_count);
36void vector_fixup_peers(ot_vector *vector, size_t peer_size); 36void vector_fixup_peers(ot_vector *vector, size_t peer_size);
37void vector_clean_list(ot_vector *vector, size_t num_buckets); 37void vector_clean_list(ot_vector *vector, size_t num_buckets);
38 38
diff --git a/src/ot_workqueue.c b/src/ot_workqueue.c
index 56a7cd2..cdefddc 100644
--- a/src/ot_workqueue.c
+++ b/src/ot_workqueue.c
@@ -9,6 +9,7 @@
9#include <unistd.h> 9#include <unistd.h>
10 10
11/* Opentracker */ 11/* Opentracker */
12#include "ot_fdstate.h"
12#include "ot_iovec.h" 13#include "ot_iovec.h"
13#include "ot_workqueue.h" 14#include "ot_workqueue.h"
14#include "trackerlogic.h" 15#include "trackerlogic.h"
@@ -20,6 +21,7 @@ struct ot_task {
20 ot_taskid taskid; 21 ot_taskid taskid;
21 ot_tasktype tasktype; 22 ot_tasktype tasktype;
22 int64_t sock; 23 int64_t sock;
24 uint32_t generation;
23 size_t iovec_entries; 25 size_t iovec_entries;
24 struct iovec *iovec; 26 struct iovec *iovec;
25 struct ot_task *next; 27 struct ot_task *next;
@@ -40,6 +42,7 @@ int workqueue_pushtask(int64_t sock, ot_tasktype tasktype) {
40 task->taskid = 0; 42 task->taskid = 0;
41 task->tasktype = tasktype; 43 task->tasktype = tasktype;
42 task->sock = sock; 44 task->sock = sock;
45 task->generation = fdstate_generation((int)sock);
43 task->iovec_entries = 0; 46 task->iovec_entries = 0;
44 task->iovec = NULL; 47 task->iovec = NULL;
45 task->next = 0; 48 task->next = 0;
@@ -65,22 +68,25 @@ void workqueue_canceltask(int64_t sock) {
65 /* Want exclusive access to tasklist */ 68 /* Want exclusive access to tasklist */
66 pthread_mutex_lock(&tasklist_mutex); 69 pthread_mutex_lock(&tasklist_mutex);
67 70
68 for (task = &tasklist; *task; task = &((*task)->next)) 71 task = &tasklist;
69 if ((*task)->sock == sock) { 72 while (*task) {
70 struct iovec *iovec = (*task)->iovec; 73 struct ot_task *ptask = *task;
71 struct ot_task *ptask = *task; 74 size_t i;
72 size_t i;
73
74 /* Free task's iovec, the buffers it points at and the vector itself */
75 for (i = 0; i < (*task)->iovec_entries; ++i)
76 free(iovec[i].iov_base);
77 free(iovec);
78 75
79 *task = (*task)->next; 76 if (ptask->sock != sock) {
80 free(ptask); 77 task = &ptask->next;
81 break; 78 continue;
82 } 79 }
83 80
81 /* Free task's iovec, the buffers it points at and the vector itself */
82 for (i = 0; i < ptask->iovec_entries; ++i)
83 free(ptask->iovec[i].iov_base);
84 free(ptask->iovec);
85
86 *task = ptask->next;
87 free(ptask);
88 }
89
84 /* Release lock */ 90 /* Release lock */
85 pthread_mutex_unlock(&tasklist_mutex); 91 pthread_mutex_unlock(&tasklist_mutex);
86} 92}
@@ -190,7 +196,7 @@ int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec) {
190 return task ? 0 : -1; 196 return task ? 0 : -1;
191} 197}
192 198
193int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is_partial) { 199int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is_partial, uint32_t *generation) {
194 struct ot_task **task; 200 struct ot_task **task;
195 int64_t sock = -1; 201 int64_t sock = -1;
196 202
@@ -205,6 +211,7 @@ int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is
205 *iovec_entries = ptask->iovec_entries; 211 *iovec_entries = ptask->iovec_entries;
206 *iovec = ptask->iovec; 212 *iovec = ptask->iovec;
207 sock = ptask->sock; 213 sock = ptask->sock;
214 *generation = ptask->generation;
208 215
209 if ((*task)->tasktype == TASK_DONE) { 216 if ((*task)->tasktype == TASK_DONE) {
210 *task = ptask->next; 217 *task = ptask->next;
diff --git a/src/ot_workqueue.h b/src/ot_workqueue.h
index 82ae29b..982292e 100644
--- a/src/ot_workqueue.h
+++ b/src/ot_workqueue.h
@@ -29,7 +29,6 @@ typedef enum {
29 TASK_STATS = 0x0100, /* Mask */ 29 TASK_STATS = 0x0100, /* Mask */
30 TASK_STATS_TORRENTS = 0x0101, 30 TASK_STATS_TORRENTS = 0x0101,
31 TASK_STATS_PEERS = 0x0102, 31 TASK_STATS_PEERS = 0x0102,
32 TASK_STATS_SLASH24S = 0x0103,
33 TASK_STATS_TOP10 = 0x0104, 32 TASK_STATS_TOP10 = 0x0104,
34 TASK_STATS_TOP100 = 0x0105, 33 TASK_STATS_TOP100 = 0x0105,
35 TASK_STATS_EVERYTHING = 0x0106, 34 TASK_STATS_EVERYTHING = 0x0106,
@@ -65,7 +64,7 @@ void workqueue_pushsuccess(ot_taskid taskid);
65ot_taskid workqueue_poptask(ot_tasktype *tasktype); 64ot_taskid workqueue_poptask(ot_tasktype *tasktype);
66int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovector); 65int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovector);
67int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec); 66int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec);
68int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovector, int *is_partial); 67int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovector, int *is_partial, uint32_t *generation);
69 68
70void workqueue_init(void); 69void workqueue_init(void);
71void workqueue_deinit(void); 70void workqueue_deinit(void);
diff --git a/src/trackerlogic.c b/src/trackerlogic.c
index 8e30a48..0b032e1 100644
--- a/src/trackerlogic.c
+++ b/src/trackerlogic.c
@@ -28,20 +28,33 @@
28/* Forward declaration */ 28/* Forward declaration */
29size_t return_peers_for_torrent(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto); 29size_t return_peers_for_torrent(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto);
30 30
31void free_peer_vector(ot_vector *peer_vector) {
32 if (OT_VECTOR_HASBUCKETS(peer_vector))
33 vector_clean_list((ot_vector *)peer_vector->data, peer_vector->size);
34 else
35 free(peer_vector->data); /* free(NULL) on an absent family is fine */
36}
37
31void free_peerlist(ot_peerlist *peer_list) { 38void free_peerlist(ot_peerlist *peer_list) {
32 if (peer_list && peer_list->peers.data) { 39 if (!peer_list)
33 if (OT_PEERLIST_HASBUCKETS(peer_list)) 40 return;
34 vector_clean_list((ot_vector *)peer_list->peers.data, peer_list->peers.size); 41 free_peer_vector(&peer_list->peers6);
35 else 42 free_peer_vector(&peer_list->peers4);
36 free(peer_list->peers.data);
37 }
38 free(peer_list); 43 free(peer_list);
39} 44}
40 45
41void add_torrent_from_saved_state(ot_hash const hash, ot_time base, size_t down_count) { 46/* How many minutes before this moment the torrent was last touched, which is
47 what a state dump records. */
48void add_torrent_from_saved_state(ot_hash const hash, ot_time age, size_t down_count) {
42 int exactmatch; 49 int exactmatch;
50 ot_time now = time_now_minutes();
43 ot_torrent *torrent; 51 ot_torrent *torrent;
44 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash); 52 ot_vector *torrents_list;
53
54 if (age > OT_TORRENT_TIMEOUT)
55 return;
56
57 torrents_list = mutex_bucket_lock_by_hash(hash);
45 58
46 if (!accesslist_hashisvalid(hash)) { 59 if (!accesslist_hashisvalid(hash)) {
47 mutex_bucket_unlock_by_hash(hash, 0); 60 mutex_bucket_unlock_by_hash(hash, 0);
@@ -54,28 +67,18 @@ void add_torrent_from_saved_state(ot_hash const hash, ot_time base, size_t down_
54 return; 67 return;
55 } 68 }
56 69
57 /* Create a new torrent entry, then */ 70 /* A restored torrent starts with no peers, carrying only its base and its
71 download count until the first announce brings a family list to life */
58 memset(torrent, 0, sizeof(ot_torrent)); 72 memset(torrent, 0, sizeof(ot_torrent));
59 memcpy(torrent->hash, hash, sizeof(ot_hash)); 73 memcpy(torrent->hash, hash, sizeof(ot_hash));
60 74 torrent->base = now > age ? (uint32_t)(now - age) : 0;
61 if (!(torrent->peer_list6 = malloc(sizeof(ot_peerlist))) || !(torrent->peer_list4 = malloc(sizeof(ot_peerlist)))) { 75 torrent->down_count = (uint32_t)down_count;
62 vector_remove_torrent(torrents_list, torrent);
63 mutex_bucket_unlock_by_hash(hash, 0);
64 return;
65 }
66
67 memset(torrent->peer_list6, 0, sizeof(ot_peerlist));
68 memset(torrent->peer_list4, 0, sizeof(ot_peerlist));
69 torrent->peer_list6->base = base;
70 torrent->peer_list4->base = base;
71 torrent->peer_list6->down_count = down_count;
72 torrent->peer_list4->down_count = down_count;
73 76
74 mutex_bucket_unlock_by_hash(hash, 1); 77 mutex_bucket_unlock_by_hash(hash, 1);
75} 78}
76 79
77size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount) { 80size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount) {
78 int exactmatch, delta_torrentcount = 0; 81 int exactmatch, delta_torrentcount = 0, completed = 0;
79 ot_torrent *torrent; 82 ot_torrent *torrent;
80 ot_peer *peer_dest; 83 ot_peer *peer_dest;
81 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash); 84 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash);
@@ -90,6 +93,13 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
90 memcpy(ws->reply, invalid_hash, strlen(invalid_hash)); 93 memcpy(ws->reply, invalid_hash, strlen(invalid_hash));
91 return strlen(invalid_hash); 94 return strlen(invalid_hash);
92 } 95 }
96 if (proto == FLAG_UDP) {
97 char *r = ws->reply;
98 pack_uint32(&r, OT_CLIENT_REJECT_INTERVAL_RANDOM);
99 pack_uint32(&r, 0);
100 pack_uint32(&r, 0);
101 return r - ws->reply;
102 }
93 return 0; 103 return 0;
94 } 104 }
95 105
@@ -103,26 +113,23 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
103 /* Create a new torrent entry, then */ 113 /* Create a new torrent entry, then */
104 memset(torrent, 0, sizeof(ot_torrent)); 114 memset(torrent, 0, sizeof(ot_torrent));
105 memcpy(torrent->hash, *ws->hash, sizeof(ot_hash)); 115 memcpy(torrent->hash, *ws->hash, sizeof(ot_hash));
106
107 if (!(torrent->peer_list6 = malloc(sizeof(ot_peerlist))) || !(torrent->peer_list4 = malloc(sizeof(ot_peerlist)))) {
108 vector_remove_torrent(torrents_list, torrent);
109 mutex_bucket_unlock_by_hash(*ws->hash, 0);
110 return 0;
111 }
112
113 memset(torrent->peer_list6, 0, sizeof(ot_peerlist));
114 memset(torrent->peer_list4, 0, sizeof(ot_peerlist));
115 delta_torrentcount = 1; 116 delta_torrentcount = 1;
116 } else 117 } else
117 clean_single_torrent(torrent); 118 clean_single_torrent(torrent);
118 119
119 torrent->peer_list6->base = time_now_minutes(); 120 torrent->base = time_now_minutes();
120 torrent->peer_list4->base = time_now_minutes();
121 121
122 peer_list = peer_size == OT_PEER_SIZE6 ? torrent->peer_list6 : torrent->peer_list4; 122 /* The peerlist, holding both families, is created on the first peer */
123 if (!torrent->peer_list && !(torrent->peer_list = calloc(1, sizeof(ot_peerlist)))) {
124 if (delta_torrentcount)
125 vector_remove_torrent(torrents_list, torrent);
126 mutex_bucket_unlock_by_hash(*ws->hash, 0);
127 return 0;
128 }
129 peer_list = torrent->peer_list;
123 130
124 /* Check for peer in torrent */ 131 /* Check for peer in its family's vector */
125 peer_dest = vector_find_or_insert_peer(&(peer_list->peers), peer_src, peer_size, &exactmatch); 132 peer_dest = vector_find_or_insert_peer(peer_size == OT_PEER_SIZE6 ? &peer_list->peers6 : &peer_list->peers4, peer_src, peer_size, &exactmatch);
126 if (!peer_dest) { 133 if (!peer_dest) {
127 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount); 134 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount);
128 return 0; 135 return 0;
@@ -145,10 +152,9 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
145 livesync_tell(ws); 152 livesync_tell(ws);
146#endif 153#endif
147 154
148 peer_list->peer_count++;
149 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED) { 155 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED) {
150 peer_list->down_count++; 156 torrent->down_count++;
151 stats_issue_event(ws, EVENT_COMPLETED, 0, 0); 157 completed = 1; /* the event, which may syslog, is issued after unlock */
152 } 158 }
153 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING) 159 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING)
154 peer_list->seed_count++; 160 peer_list->seed_count++;
@@ -174,8 +180,8 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
174 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_SEEDING) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING)) 180 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_SEEDING) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING))
175 peer_list->seed_count++; 181 peer_list->seed_count++;
176 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED)) { 182 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED)) {
177 peer_list->down_count++; 183 torrent->down_count++;
178 stats_issue_event(ws, EVENT_COMPLETED, 0, 0); 184 completed = 1; /* the event, which may syslog, is issued after unlock */
179 } 185 }
180 if (OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED) 186 if (OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED)
181 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED; 187 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
@@ -185,23 +191,29 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
185#ifdef WANT_SYNC 191#ifdef WANT_SYNC
186 if (proto == FLAG_MCA) { 192 if (proto == FLAG_MCA) {
187 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount); 193 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount);
194 if (completed)
195 stats_issue_event(ws, EVENT_COMPLETED, 0, 0);
188 return 0; 196 return 0;
189 } 197 }
190#endif 198#endif
191 199
192 ws->reply_size = return_peers_for_torrent(ws, torrent, amount, ws->reply, proto); 200 ws->reply_size = return_peers_for_torrent(ws, torrent, amount, ws->reply, proto);
193 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount); 201 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount);
202
203 /* Issued after bucket unlock, so a slow syslog cannot stall the bucket */
204 if (completed)
205 stats_issue_event(ws, EVENT_COMPLETED, 0, 0);
194 return ws->reply_size; 206 return ws->reply_size;
195} 207}
196 208
197static size_t return_peers_all(ot_peerlist *peer_list, size_t peer_size, char *reply) { 209static size_t return_peers_all(ot_vector *peer_vector, size_t peer_size, size_t peer_count, char *reply) {
198 size_t bucket, num_buckets = 1; 210 size_t bucket, num_buckets = 1;
199 ot_vector *bucket_list = &peer_list->peers; 211 ot_vector *bucket_list = peer_vector;
200 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size); 212 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
201 size_t result = compare_size * peer_list->peer_count; 213 size_t result = compare_size * peer_count;
202 char *r_end = reply + result; 214 char *r_end = reply + result;
203 215
204 if (OT_PEERLIST_HASBUCKETS(peer_list)) { 216 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
205 num_buckets = bucket_list->size; 217 num_buckets = bucket_list->size;
206 bucket_list = (ot_vector *)bucket_list->data; 218 bucket_list = (ot_vector *)bucket_list->data;
207 } 219 }
@@ -223,17 +235,17 @@ static size_t return_peers_all(ot_peerlist *peer_list, size_t peer_size, char *r
223 return result; 235 return result;
224} 236}
225 237
226static size_t return_peers_selection(struct ot_workstruct *ws, ot_peerlist *peer_list, size_t peer_size, size_t amount, char *reply) { 238static size_t return_peers_selection(struct ot_workstruct *ws, ot_vector *peer_vector, size_t peer_size, size_t amount, size_t peer_count, char *reply) {
227 size_t bucket_offset, bucket_index = 0, num_buckets = 1; 239 size_t bucket_offset, bucket_index = 0, num_buckets = 1;
228 ot_vector *bucket_list = &peer_list->peers; 240 ot_vector *bucket_list = peer_vector;
229 unsigned int shifted_pc = peer_list->peer_count; 241 unsigned int shifted_pc = peer_count;
230 unsigned int shifted_step = 0; 242 unsigned int shifted_step = 0;
231 unsigned int shift = 0; 243 unsigned int shift = 0;
232 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size); 244 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
233 size_t result = compare_size * amount; 245 size_t result = compare_size * amount;
234 char *r_end = reply + result; 246 char *r_end = reply + result;
235 247
236 if (OT_PEERLIST_HASBUCKETS(peer_list)) { 248 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
237 num_buckets = bucket_list->size; 249 num_buckets = bucket_list->size;
238 bucket_list = (ot_vector *)bucket_list->data; 250 bucket_list = (ot_vector *)bucket_list->data;
239 } 251 }
@@ -249,7 +261,7 @@ static size_t return_peers_selection(struct ot_workstruct *ws, ot_peerlist *peer
249 261
250 /* Initialize somewhere in the middle of peers so that 262 /* Initialize somewhere in the middle of peers so that
251 fixpoint's aliasing doesn't alway miss the same peers */ 263 fixpoint's aliasing doesn't alway miss the same peers */
252 bucket_offset = nrand48(ws->rand48_state) % peer_list->peer_count; 264 bucket_offset = nrand48(ws->rand48_state) % peer_count;
253 265
254 while (amount--) { 266 while (amount--) {
255 ot_peer *peer; 267 ot_peer *peer;
@@ -277,23 +289,24 @@ static size_t return_peers_selection(struct ot_workstruct *ws, ot_peerlist *peer
277static size_t return_peers_for_torrent_udp(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply) { 289static size_t return_peers_for_torrent_udp(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply) {
278 char *r = reply; 290 char *r = reply;
279 size_t peer_size = peer_size_from_peer6(&ws->peer); 291 size_t peer_size = peer_size_from_peer6(&ws->peer);
280 ot_peerlist *peer_list = peer_size == OT_PEER_SIZE6 ? torrent->peer_list6 : torrent->peer_list4; 292 ot_peerlist *peer_list = torrent->peer_list;
281 size_t peer_count = torrent->peer_list6->peer_count + torrent->peer_list4->peer_count; 293 ot_vector *family = peer_size == OT_PEER_SIZE6 ? &peer_list->peers6 : &peer_list->peers4;
282 size_t seed_count = torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 294 size_t list_count = vector_peer_count(family);
295 size_t peer_count = torrent_peer_count(torrent);
296 size_t seed_count = torrent_seed_count(torrent);
283 297
284 if (amount > peer_list->peer_count) 298 if (amount > list_count)
285 amount = peer_list->peer_count; 299 amount = list_count;
286 300
287 *(uint32_t *)(r + 0) = htonl(OT_CLIENT_REQUEST_INTERVAL_RANDOM); 301 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
288 *(uint32_t *)(r + 4) = htonl(peer_count - seed_count); 302 pack_uint32(&r, peer_count - seed_count);
289 *(uint32_t *)(r + 8) = htonl(seed_count); 303 pack_uint32(&r, seed_count);
290 r += 12;
291 304
292 if (amount) { 305 if (amount) {
293 if (amount == peer_list->peer_count) 306 if (amount == list_count)
294 r += return_peers_all(peer_list, peer_size, r); 307 r += return_peers_all(family, peer_size, list_count, r);
295 else 308 else
296 r += return_peers_selection(ws, peer_list, peer_size, amount, r); 309 r += return_peers_selection(ws, family, peer_size, amount, list_count, r);
297 } 310 }
298 return r - reply; 311 return r - reply;
299} 312}
@@ -302,13 +315,16 @@ static size_t return_peers_for_torrent_tcp(struct ot_workstruct *ws, ot_torrent
302 char *r = reply; 315 char *r = reply;
303 const char *r_end = ws->outbuf + G_OUTBUF_SIZE; 316 const char *r_end = ws->outbuf + G_OUTBUF_SIZE;
304 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM; 317 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM;
305 size_t seed_count = torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 318 ot_peerlist *peer_list = torrent->peer_list;
306 size_t down_count = torrent->peer_list6->down_count + torrent->peer_list4->down_count; 319 size_t count6 = vector_peer_count(&peer_list->peers6);
307 size_t peer_count = torrent->peer_list6->peer_count + torrent->peer_list4->peer_count - seed_count; 320 size_t count4 = vector_peer_count(&peer_list->peers4);
321 size_t seed_count = peer_list->seed_count;
322 size_t down_count = torrent->down_count;
323 size_t peer_count = count6 + count4 - seed_count;
308 324
309 /* Simple case: amount of peers in both lists is less than requested, here we return all results */ 325 /* Simple case: amount of peers in both lists is less than requested, here we return all results */
310 size_t amount_v4 = torrent->peer_list4->peer_count; 326 size_t amount_v4 = count4;
311 size_t amount_v6 = torrent->peer_list6->peer_count; 327 size_t amount_v6 = count6;
312 328
313 /* Complex case: both lists have more than enough entries and we need to split between v4 and v6 clients */ 329 /* Complex case: both lists have more than enough entries and we need to split between v4 and v6 clients */
314 if (amount_v4 + amount_v6 > amount) { 330 if (amount_v4 + amount_v6 > amount) {
@@ -324,8 +340,8 @@ static size_t return_peers_for_torrent_tcp(struct ot_workstruct *ws, ot_torrent
324 /* Fill the rest according to which family's pool provides more peers */ 340 /* Fill the rest according to which family's pool provides more peers */
325 amount_left = amount - (amount_v4 + amount_v6); 341 amount_left = amount - (amount_v4 + amount_v6);
326 342
327 left_v4 = torrent->peer_list4->peer_count - amount_v4; 343 left_v4 = count4 - amount_v4;
328 left_v6 = torrent->peer_list6->peer_count - amount_v6; 344 left_v6 = count6 - amount_v6;
329 345
330 if (left_v4 + left_v6) { 346 if (left_v4 + left_v6) {
331 percent_v4 = (SCALE * left_v4) / (left_v4 + left_v6); 347 percent_v4 = (SCALE * left_v4) / (left_v4 + left_v6);
@@ -336,9 +352,9 @@ static size_t return_peers_for_torrent_tcp(struct ot_workstruct *ws, ot_torrent
336 amount_v6 += (amount_left * percent_v6) / SCALE; 352 amount_v6 += (amount_left * percent_v6) / SCALE;
337 353
338 /* Integer division rounding can leave out a peer */ 354 /* Integer division rounding can leave out a peer */
339 if (amount_v4 + amount_v6 < amount && amount_v6 < torrent->peer_list6->peer_count) 355 if (amount_v4 + amount_v6 < amount && amount_v6 < count6)
340 ++amount_v6; 356 ++amount_v6;
341 if (amount_v4 + amount_v6 < amount && amount_v4 < torrent->peer_list4->peer_count) 357 if (amount_v4 + amount_v6 < amount && amount_v4 < count4)
342 ++amount_v4; 358 ++amount_v4;
343 } 359 }
344 360
@@ -347,18 +363,18 @@ static size_t return_peers_for_torrent_tcp(struct ot_workstruct *ws, ot_torrent
347 363
348 if (amount_v4) { 364 if (amount_v4) {
349 fmt_append(&r, r_end, PEERS_BENCODED4 "%zd:", OT_PEER_COMPARE_SIZE4 * amount_v4); 365 fmt_append(&r, r_end, PEERS_BENCODED4 "%zd:", OT_PEER_COMPARE_SIZE4 * amount_v4);
350 if (amount_v4 == torrent->peer_list4->peer_count) 366 if (amount_v4 == count4)
351 r += return_peers_all(torrent->peer_list4, OT_PEER_SIZE4, r); 367 r += return_peers_all(&peer_list->peers4, OT_PEER_SIZE4, count4, r);
352 else 368 else
353 r += return_peers_selection(ws, torrent->peer_list4, OT_PEER_SIZE4, amount_v4, r); 369 r += return_peers_selection(ws, &peer_list->peers4, OT_PEER_SIZE4, amount_v4, count4, r);
354 } 370 }
355 371
356 if (amount_v6) { 372 if (amount_v6) {
357 fmt_append(&r, r_end, PEERS_BENCODED6 "%zd:", OT_PEER_COMPARE_SIZE6 * amount_v6); 373 fmt_append(&r, r_end, PEERS_BENCODED6 "%zd:", OT_PEER_COMPARE_SIZE6 * amount_v6);
358 if (amount_v6 == torrent->peer_list6->peer_count) 374 if (amount_v6 == count6)
359 r += return_peers_all(torrent->peer_list6, OT_PEER_SIZE6, r); 375 r += return_peers_all(&peer_list->peers6, OT_PEER_SIZE6, count6, r);
360 else 376 else
361 r += return_peers_selection(ws, torrent->peer_list6, OT_PEER_SIZE6, amount_v6, r); 377 r += return_peers_selection(ws, &peer_list->peers6, OT_PEER_SIZE6, amount_v6, count6, r);
362 } 378 }
363 379
364 fmt_append(&r, r_end, "e"); 380 fmt_append(&r, r_end, "e");
@@ -384,23 +400,25 @@ size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply) {
384 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash); 400 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash);
385 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch); 401 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
386 402
387 if (!exactmatch) { 403 uint32_t seeders = 0, completed = 0, leechers = 0;
388 memset(reply, 0, 12); 404 char *r = reply;
389 } else {
390 uint32_t *r = (uint32_t *)reply;
391 405
406 if (exactmatch) {
392 if (clean_single_torrent(torrent)) { 407 if (clean_single_torrent(torrent)) {
393 vector_remove_torrent(torrents_list, torrent); 408 vector_remove_torrent(torrents_list, torrent);
394 memset(reply, 0, 12);
395 delta_torrentcount = -1; 409 delta_torrentcount = -1;
396 } else { 410 } else {
397 r[0] = htonl(torrent->peer_list6->seed_count + torrent->peer_list4->seed_count); 411 seeders = torrent_seed_count(torrent);
398 r[1] = htonl(torrent->peer_list6->down_count + torrent->peer_list4->down_count); 412 completed = torrent->down_count;
399 r[2] = htonl(torrent->peer_list6->peer_count + torrent->peer_list4->peer_count - torrent->peer_list6->seed_count - torrent->peer_list4->seed_count); 413 leechers = torrent_peer_count(torrent) - torrent_seed_count(torrent);
400 } 414 }
401 } 415 }
402 mutex_bucket_unlock_by_hash(hash, delta_torrentcount); 416 mutex_bucket_unlock_by_hash(hash, delta_torrentcount);
403 return 12; 417
418 pack_uint32(&r, seeders);
419 pack_uint32(&r, completed);
420 pack_uint32(&r, leechers);
421 return r - reply;
404} 422}
405 423
406/* Fetches scrape info for a specific torrent */ 424/* Fetches scrape info for a specific torrent */
@@ -423,9 +441,9 @@ void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char
423 } else { 441 } else {
424 fmt_append(reply, reply_end, "20:"); 442 fmt_append(reply, reply_end, "20:");
425 fmt_bytes(reply, reply_end, hash, sizeof(ot_hash)); 443 fmt_bytes(reply, reply_end, hash, sizeof(ot_hash));
426 fmt_append(reply, reply_end, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee", 444 size_t seed_count = torrent_seed_count(torrent);
427 torrent->peer_list6->seed_count + torrent->peer_list4->seed_count, torrent->peer_list6->down_count + torrent->peer_list4->down_count, 445 size_t peer_count = torrent_peer_count(torrent);
428 torrent->peer_list6->peer_count + torrent->peer_list4->peer_count - torrent->peer_list6->seed_count - torrent->peer_list4->seed_count); 446 fmt_append(reply, reply_end, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee", seed_count, (size_t)torrent->down_count, peer_count - seed_count);
429 } 447 }
430 } 448 }
431 mutex_bucket_unlock_by_hash(*hash, delta_torrentcount); 449 mutex_bucket_unlock_by_hash(*hash, delta_torrentcount);
@@ -434,12 +452,10 @@ void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char
434 fmt_append(reply, reply_end, "ee"); 452 fmt_append(reply, reply_end, "ee");
435} 453}
436 454
437static ot_peerlist dummy_list;
438size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) { 455size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) {
439 int exactmatch; 456 int exactmatch;
440 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash); 457 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash);
441 ot_torrent *torrent = vector_binary_search(ws->hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch); 458 ot_torrent *torrent = vector_binary_search(ws->hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
442 ot_peerlist *peer_list = &dummy_list;
443 size_t peer_size; /* initialized in next line */ 459 size_t peer_size; /* initialized in next line */
444 ot_peer const *peer_src = peer_from_peer6(&ws->peer, &peer_size); 460 ot_peer const *peer_src = peer_from_peer6(&ws->peer, &peer_size);
445 size_t peer_count = 0, seed_count = 0; 461 size_t peer_count = 0, seed_count = 0;
@@ -451,19 +467,13 @@ size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) {
451 } 467 }
452#endif 468#endif
453 469
454 if (exactmatch) { 470 if (exactmatch && torrent->peer_list) {
455 peer_list = peer_size == OT_PEER_SIZE6 ? torrent->peer_list6 : torrent->peer_list4; 471 ot_vector *family = peer_size == OT_PEER_SIZE6 ? &torrent->peer_list->peers6 : &torrent->peer_list->peers4;
456 switch (vector_remove_peer(&peer_list->peers, peer_src, peer_size)) { 472 if (vector_remove_peer(family, peer_src, peer_size) == 2)
457 case 2: 473 torrent->peer_list->seed_count--;
458 peer_list->seed_count--; /* Intentional fallthrough */
459 case 1:
460 peer_list->peer_count--; /* Intentional fallthrough */
461 default:
462 break;
463 }
464 474
465 peer_count = torrent->peer_list6->peer_count + torrent->peer_list4->peer_count; 475 peer_count = torrent_peer_count(torrent);
466 seed_count = torrent->peer_list6->seed_count + torrent->peer_list4->seed_count; 476 seed_count = torrent_seed_count(torrent);
467 } 477 }
468 478
469 if (proto == FLAG_TCP) { 479 if (proto == FLAG_TCP) {
@@ -477,10 +487,11 @@ size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) {
477 487
478 /* Handle UDP reply */ 488 /* Handle UDP reply */
479 if (proto == FLAG_UDP) { 489 if (proto == FLAG_UDP) {
480 ((uint32_t *)ws->reply)[2] = htonl(OT_CLIENT_REQUEST_INTERVAL_RANDOM); 490 char *r = ws->reply;
481 ((uint32_t *)ws->reply)[3] = htonl(peer_count - seed_count); 491 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
482 ((uint32_t *)ws->reply)[4] = htonl(seed_count); 492 pack_uint32(&r, peer_count - seed_count);
483 ws->reply_size = 20; 493 pack_uint32(&r, seed_count);
494 ws->reply_size = r - ws->reply;
484 } 495 }
485 496
486 mutex_bucket_unlock_by_hash(*ws->hash, 0); 497 mutex_bucket_unlock_by_hash(*ws->hash, 0);
@@ -563,7 +574,6 @@ void trackerlogic_init(void) {
563 clean_init(); 574 clean_init();
564 fullscrape_init(); 575 fullscrape_init();
565 accesslist_init(); 576 accesslist_init();
566 livesync_init();
567 stats_init(); 577 stats_init();
568} 578}
569 579
@@ -576,8 +586,14 @@ int workstruct_init(struct ot_workstruct *ws, size_t inbuf_size) {
576#ifdef _DEBUG_HTTPERROR 586#ifdef _DEBUG_HTTPERROR
577 ws->debugbuf = malloc(G_DEBUGBUF_SIZE); 587 ws->debugbuf = malloc(G_DEBUGBUF_SIZE);
578#endif 588#endif
579 if (!ws->inbuf || !ws->outbuf) 589 if (!ws->inbuf || !ws->outbuf) {
590 free(ws->inbuf);
591 free(ws->outbuf);
592#ifdef _DEBUG_HTTPERROR
593 free(ws->debugbuf);
594#endif
580 return -1; 595 return -1;
596 }
581 597
582 /* Picking which peers to hand out starts here, so two workers seeded alike 598 /* Picking which peers to hand out starts here, so two workers seeded alike
583 would hand out alike */ 599 would hand out alike */
@@ -599,24 +615,21 @@ void workstruct_deinit(struct ot_workstruct *ws) {
599} 615}
600 616
601void trackerlogic_deinit(void) { 617void trackerlogic_deinit(void) {
602 int delta_torrentcount = 0;
603 size_t bucket, j; 618 size_t bucket, j;
604 619
605 /* Stop the background workers first */ 620 clean_deinit();
606 stats_deinit(); 621 stats_deinit();
607 livesync_deinit();
608 accesslist_deinit(); 622 accesslist_deinit();
609 fullscrape_deinit(); 623 fullscrape_deinit();
610 clean_deinit();
611 624
612 /* Free all torrents... */ 625 /* Free all torrents... */
613 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) { 626 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
614 ot_vector *torrents_list = mutex_bucket_lock(bucket); 627 ot_vector *torrents_list = mutex_bucket_lock(bucket);
628 int delta_torrentcount = 0;
615 if (torrents_list->size) { 629 if (torrents_list->size) {
616 for (j = 0; j < torrents_list->size; ++j) { 630 for (j = 0; j < torrents_list->size; ++j) {
617 ot_torrent *torrent = ((ot_torrent *)(torrents_list->data)) + j; 631 ot_torrent *torrent = ((ot_torrent *)(torrents_list->data)) + j;
618 free_peerlist(torrent->peer_list6); 632 free_peerlist(torrent->peer_list);
619 free_peerlist(torrent->peer_list4);
620 delta_torrentcount -= 1; 633 delta_torrentcount -= 1;
621 } 634 }
622 free(torrents_list->data); 635 free(torrents_list->data);
diff --git a/src/trackerlogic.h b/src/trackerlogic.h
index 692b6af..a05c790 100644
--- a/src/trackerlogic.h
+++ b/src/trackerlogic.h
@@ -4,10 +4,12 @@
4#ifndef OT_TRACKERLOGIC_H__ 4#ifndef OT_TRACKERLOGIC_H__
5#define OT_TRACKERLOGIC_H__ 5#define OT_TRACKERLOGIC_H__
6 6
7#include <arpa/inet.h>
7#include <signal.h> 8#include <signal.h>
8#include <stdatomic.h> 9#include <stdatomic.h>
9#include <stdint.h> 10#include <stdint.h>
10#include <stdlib.h> 11#include <stdlib.h>
12#include <string.h>
11#include <sys/time.h> 13#include <sys/time.h>
12#include <sys/types.h> 14#include <sys/types.h>
13#include <time.h> 15#include <time.h>
@@ -39,12 +41,20 @@ typedef struct {
39#define OT_CLIENT_TIMEOUT_SEND (60 * 15) 41#define OT_CLIENT_TIMEOUT_SEND (60 * 15)
40#define OT_CLIENT_REQUEST_INTERVAL (60 * 30) 42#define OT_CLIENT_REQUEST_INTERVAL (60 * 30)
41#define OT_CLIENT_REQUEST_VARIATION (60 * 6) 43#define OT_CLIENT_REQUEST_VARIATION (60 * 6)
44#define OT_CLIENT_REJECT_INTERVAL (60 * 120)
42 45
43#define OT_TORRENT_TIMEOUT_HOURS 24 46#define OT_TORRENT_TIMEOUT_HOURS 24
44#define OT_TORRENT_TIMEOUT (60 * OT_TORRENT_TIMEOUT_HOURS) 47#define OT_TORRENT_TIMEOUT (60 * OT_TORRENT_TIMEOUT_HOURS)
45 48
49/* How long a torrent kept only for its download count, with no peers in either
50 family, is held, in minutes. Defaults to OT_TORRENT_TIMEOUT and is lowered by
51 tracker.empty_torrent_timeout. */
52extern ot_time g_empty_torrent_timeout;
53
46#define OT_CLIENT_REQUEST_INTERVAL_RANDOM \ 54#define OT_CLIENT_REQUEST_INTERVAL_RANDOM \
47 (OT_CLIENT_REQUEST_INTERVAL - OT_CLIENT_REQUEST_VARIATION / 2 + (int)(nrand48(ws->rand48_state) % OT_CLIENT_REQUEST_VARIATION)) 55 (OT_CLIENT_REQUEST_INTERVAL - OT_CLIENT_REQUEST_VARIATION / 2 + (int)(nrand48(ws->rand48_state) % OT_CLIENT_REQUEST_VARIATION))
56#define OT_CLIENT_REJECT_INTERVAL_RANDOM \
57 (OT_CLIENT_REJECT_INTERVAL - OT_CLIENT_REQUEST_VARIATION / 2 + (int)(nrand48(ws->rand48_state) % OT_CLIENT_REQUEST_VARIATION))
48 58
49/* If WANT_MODEST_FULLSCRAPES is on, ip addresses may not 59/* If WANT_MODEST_FULLSCRAPES is on, ip addresses may not
50 fullscrape more frequently than this amount in seconds */ 60 fullscrape more frequently than this amount in seconds */
@@ -61,10 +71,10 @@ typedef struct {
61#define OT_PEER_TIMEOUT 45 71#define OT_PEER_TIMEOUT 45
62 72
63/* We maintain a list of 1024 pointers to sorted list of ot_torrent structs 73/* We maintain a list of 1024 pointers to sorted list of ot_torrent structs
64 Sort key is, of course, its hash */ 74 Sort key is, of course, its hash.
65/* Set from the Makefile, 8 to 16. More buckets means shorter vectors and a 75 Can be tweked from the Makefile, sensible values are between 8 in 16. More
66 cheaper insert, which only pays for a tracker carrying millions of 76 buckets means shorter vectors and a cheaper insert, which only pays for a
67 torrents; see DESIGN. */ 77 tracker carrying millions of torrents. Consult the DESIGN document. */
68#ifndef OT_BUCKET_COUNT_BITS 78#ifndef OT_BUCKET_COUNT_BITS
69#define OT_BUCKET_COUNT_BITS 10 79#define OT_BUCKET_COUNT_BITS 10
70#endif 80#endif
@@ -76,12 +86,12 @@ typedef struct {
76 on startup */ 86 on startup */
77#define RANDOMTORRENTS (1024 * 1024 * 1) 87#define RANDOMTORRENTS (1024 * 1024 * 1)
78 88
79#if defined(CLOCK_REALTIME_COARSE) 89#if defined(CLOCK_MONOTONIC_COARSE)
80#define OT_CLOCK_CHEAP CLOCK_REALTIME_COARSE /* Linux */ 90#define OT_CLOCK_CHEAP CLOCK_MONOTONIC_COARSE /* Linux and FreeBSD */
81#elif defined(CLOCK_REALTIME_FAST) 91#elif defined(CLOCK_MONOTONIC_FAST)
82#define OT_CLOCK_CHEAP CLOCK_REALTIME_FAST /* the BSDs */ 92#define OT_CLOCK_CHEAP CLOCK_MONOTONIC_FAST /* the other BSDs */
83#else 93#else
84#define OT_CLOCK_CHEAP CLOCK_REALTIME /* macOS and whatever else */ 94#define OT_CLOCK_CHEAP CLOCK_MONOTONIC /* macOS and whatever else */
85#endif 95#endif
86 96
87static inline ot_time time_now_seconds(void) { 97static inline ot_time time_now_seconds(void) {
@@ -95,6 +105,35 @@ static inline ot_time time_now_minutes(void) { return time_now_seconds() / 60; }
95/* For the deadlines the tracker sets on itself, which read better as the 105/* For the deadlines the tracker sets on itself, which read better as the
96 span they allow than as an addition to the current second */ 106 span they allow than as an addition to the current second */
97static inline ot_time time_future_seconds(int span) { return time_now_seconds() + span; } 107static inline ot_time time_future_seconds(int span) { return time_now_seconds() + span; }
108
109/* How long ago a stamp was taken. */
110_Static_assert((ot_time)-1 < 0, "ot_time has to be signed for time_since_* to clamp");
111
112static inline ot_time time_since_seconds(ot_time then) {
113 ot_time now = time_now_seconds();
114 return now > then ? now - then : 0;
115}
116
117static inline ot_time time_since_minutes(ot_time then) {
118 ot_time now = time_now_minutes();
119 return now > then ? now - then : 0;
120}
121
122/* Has a deadline the tracker set on itself gone by? */
123static inline int time_is_past(ot_time deadline) { return time_now_seconds() > deadline; }
124
125/* The wall clock, which the state file uses and nothing else does: it has to
126 survive a restart, and the clock above counts from boot. */
127static inline ot_time time_wall_minutes(void) { return time(NULL) / 60; }
128
129/* Appends a 32 bit value in network byte order to a binary reply and
130 advances the cursor. The caller has made sure of the room. */
131static inline void pack_uint32(char **cursor, uint32_t value) {
132 value = htonl(value);
133 memcpy(*cursor, &value, sizeof(value));
134 *cursor += sizeof(value);
135}
136
98/* Cleared from the interrupt handler and read by every worker */ 137/* Cleared from the interrupt handler and read by every worker */
99extern _Atomic int g_opentracker_running; 138extern _Atomic int g_opentracker_running;
100 139
@@ -141,23 +180,40 @@ struct ot_peerlist;
141typedef struct ot_peerlist ot_peerlist; 180typedef struct ot_peerlist ot_peerlist;
142typedef struct { 181typedef struct {
143 ot_hash hash; 182 ot_hash hash;
144 ot_peerlist *peer_list6; 183 ot_peerlist *peer_list; /* NULL until the torrent has a peer in either family */
145 ot_peerlist *peer_list4; 184 uint32_t base; /* epoch minutes, when the torrent was last cleaned */
185 uint32_t down_count; /* completed events */
146} ot_torrent; 186} ot_torrent;
147 187
148#include "ot_vector.h" 188#include "ot_vector.h"
149 189
150struct ot_peerlist { 190struct ot_peerlist {
151 ot_time base; 191 uint32_t seed_count;
152 size_t seed_count; 192 /* each family's peers: a normal vector, or a pointer to ot_vector[] buckets
153 size_t peer_count; 193 when data != NULL and space == 0 (size then holds the bucket count) */
154 size_t down_count; 194 ot_vector peers6;
155 /* normal peers vector or 195 ot_vector peers4;
156 pointer to ot_vector[32] buckets if data != NULL and space == 0
157 */
158 ot_vector peers;
159}; 196};
160#define OT_PEERLIST_HASBUCKETS(peer_list) ((peer_list)->peers.size > (peer_list)->peers.space) 197
198/* A peer vector becomes a bucket list of peer vectors, marker is size > space (usually 0) */
199#define OT_VECTOR_HASBUCKETS(v) ((v)->size > (v)->space)
200
201/* Peers in one family: a plain vector's size is the count, a bucket list's is
202 the sum of its buckets. O(1) for the small torrents that dominate a table. */
203static inline size_t vector_peer_count(const ot_vector *v) {
204 const ot_vector *b;
205 size_t n, total = 0;
206 if (!OT_VECTOR_HASBUCKETS(v))
207 return v->size;
208 b = (const ot_vector *)v->data;
209 for (n = 0; n < v->size; ++n)
210 total += b[n].size;
211 return total;
212}
213static inline size_t torrent_peer_count(const ot_torrent *t) {
214 return t->peer_list ? vector_peer_count(&t->peer_list->peers6) + vector_peer_count(&t->peer_list->peers4) : 0;
215}
216static inline uint32_t torrent_seed_count(const ot_torrent *t) { return t->peer_list ? t->peer_list->seed_count : 0; }
161 217
162/* The http replies the tracker counts when it has to refuse a request. */ 218/* The http replies the tracker counts when it has to refuse a request. */
163enum { 219enum {
@@ -175,7 +231,7 @@ enum {
175}; 231};
176 232
177/* One statistic. Used when workers report stats to their workstruct */ 233/* One statistic. Used when workers report stats to their workstruct */
178typedef _Atomic unsigned long long ot_counter; 234typedef _Atomic unsigned long ot_counter;
179 235
180/* What each thread counts for itself. The two runs at the end are indexed by 236/* What each thread counts for itself. The two runs at the end are indexed by
181 the http error code and by the age in minutes of a renewed peer */ 237 the http error code and by the age in minutes of a renewed peer */
@@ -237,6 +293,9 @@ struct ot_workstruct {
237 uint16_t rand48_state[3]; 293 uint16_t rand48_state[3];
238 294
239 int keep_alive; 295 int keep_alive;
296
297 /* Set when a request path gave the connection to a worker thread. */
298 int handed_off;
240}; 299};
241 300
242/* Everything a thread that serves requests needs for itself. Set up and torn 301/* Everything a thread that serves requests needs for itself. Set up and torn
@@ -269,7 +328,7 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
269size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws); 328size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws);
270void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char **reply, const char *reply_end); 329void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char **reply, const char *reply_end);
271size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply); 330size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply);
272void add_torrent_from_saved_state(ot_hash const hash, ot_time base, size_t down_count); 331void add_torrent_from_saved_state(ot_hash const hash, ot_time age, size_t down_count);
273#ifdef _DEBUG_RANDOMTORRENTS 332#ifdef _DEBUG_RANDOMTORRENTS
274void trackerlogic_add_random_torrents(size_t amount); 333void trackerlogic_add_random_torrents(size_t amount);
275#endif 334#endif
@@ -279,5 +338,6 @@ void iterate_all_torrents(int (*for_each)(ot_torrent *torrent, uintptr_t data),
279 338
280/* Helper, before it moves to its own object */ 339/* Helper, before it moves to its own object */
281void free_peerlist(ot_peerlist *peer_list); 340void free_peerlist(ot_peerlist *peer_list);
341void free_peer_vector(ot_vector *peer_vector);
282 342
283#endif 343#endif
diff --git a/tests/integration/harness.py b/tests/integration/harness.py
index 10aa6de..f3cd0fa 100644
--- a/tests/integration/harness.py
+++ b/tests/integration/harness.py
@@ -77,7 +77,7 @@ def free_port(attempts=50):
77class Tracker: 77class Tracker:
78 """One tracker process, listening on loopback.""" 78 """One tracker process, listening on loopback."""
79 79
80 def __init__(self, extra_config="", files=None): 80 def __init__(self, extra_config="", files=None, extra_args=()):
81 self.port = free_port() 81 self.port = free_port()
82 # Only used by a config that asks for live sync, but allocated either 82 # Only used by a config that asks for live sync, but allocated either
83 # way so {livesync_port} always resolves. 83 # way so {livesync_port} always resolves.
@@ -99,7 +99,8 @@ class Tracker:
99 # where LeakSanitizer exists and off where it does not. Asking for it 99 # where LeakSanitizer exists and off where it does not. Asking for it
100 # by name makes the tracker refuse to start on macOS and FreeBSD. 100 # by name makes the tracker refuse to start on macOS and FreeBSD.
101 environment = dict(os.environ, ASAN_OPTIONS="abort_on_error=0") 101 environment = dict(os.environ, ASAN_OPTIONS="abort_on_error=0")
102 self.process = subprocess.Popen([TRACKER, "-f", self.config], stdout=self.log, stderr=self.log, env=environment) 102 argv = [TRACKER, "-f", self.config] + [str(a) for a in extra_args]
103 self.process = subprocess.Popen(argv, stdout=self.log, stderr=self.log, env=environment)
103 self._wait_for_port() 104 self._wait_for_port()
104 except BaseException: 105 except BaseException:
105 self._cleanup() 106 self._cleanup()
@@ -134,6 +135,11 @@ class Tracker:
134 self.log.seek(0) 135 self.log.seek(0)
135 return self.log.read().decode("utf-8", "replace") 136 return self.log.read().decode("utf-8", "replace")
136 137
138 def reload(self):
139 """SIGHUP makes the accesslist reader re-read its files, which also
140 empties the dynamic add/delete changesets."""
141 os.kill(self.process.pid, signal.SIGHUP)
142
137 def stop(self): 143 def stop(self):
138 """Returns anything the tracker complained about on the way out. 144 """Returns anything the tracker complained about on the way out.
139 145
diff --git a/tests/integration/test_accesslist.py b/tests/integration/test_accesslist.py
index 41ff654..3ed8ddf 100644
--- a/tests/integration/test_accesslist.py
+++ b/tests/integration/test_accesslist.py
@@ -5,10 +5,12 @@ entry, and the file parser has to cope with the shapes an operator actually
5produces: an empty file, and a last line with no newline after it. 5produces: an empty file, and a last line with no newline after it.
6""" 6"""
7 7
8import os
8import struct 9import struct
10import time
9import unittest 11import unittest
10 12
11from harness import TrackerTestCase 13from harness import Tracker, TrackerTestCase
12 14
13BLOCKED = b"\xb1" * 20 15BLOCKED = b"\xb1" * 20
14ALLOWED = b"\xa1" * 20 16ALLOWED = b"\xa1" * 20
@@ -37,10 +39,11 @@ class Blacklist(TrackerTestCase):
37 self.assertNotIn(b"failure reason", answer) 39 self.assertNotIn(b"failure reason", answer)
38 self.assertEqual(answer[b"complete"], 1) 40 self.assertEqual(answer[b"complete"], 1)
39 41
40 def test_the_block_is_an_error_packet_over_udp(self): 42 def test_the_block_is_an_empty_announce_over_udp(self):
41 """BEP 15 has an error action, which is what a refusal should use. 43 """An empty swarm with a long interval, not an error. BEP 15 binds a
42 It used to answer the announce header with no body behind it, a 44 client to the interval and says nothing about what to do with an
43 packet too short for any client to read.""" 45 error, so an error puts the client on its own retry schedule, which
46 starts in the tens of seconds."""
44 sock, connection_id = self.tracker.udp_connect() 47 sock, connection_id = self.tracker.udp_connect()
45 sock.close() 48 sock.close()
46 request = struct.pack( 49 request = struct.pack(
@@ -48,10 +51,13 @@ class Blacklist(TrackerTestCase):
48 ) 51 )
49 answer = self.tracker.udp_raw(request) 52 answer = self.tracker.udp_raw(request)
50 self.assertIsNotNone(answer) 53 self.assertIsNotNone(answer)
51 action, transaction = struct.unpack(">II", answer[:8]) 54 self.assertEqual(len(answer), 20, "header and counts, no peers behind them")
52 self.assertEqual(action, 3, "action 3 is the error packet") 55 action, transaction, interval, leechers, seeders = struct.unpack(">IIIII", answer)
56 self.assertEqual(action, 1, "action 1 is the announce packet")
53 self.assertEqual(transaction, 7) 57 self.assertEqual(transaction, 7)
54 self.assertIn(b"not authorized", answer[8:]) 58 self.assertEqual((leechers, seeders), (0, 0))
59 self.assertGreaterEqual(interval, 60 * 60, "far enough out to be worth the trouble")
60 self.assertLessEqual(interval, 60 * 60 * 6, "not so far out that a client clamps it")
55 61
56 def test_a_blocked_hash_is_not_stored_when_it_arrives_over_udp(self): 62 def test_a_blocked_hash_is_not_stored_when_it_arrives_over_udp(self):
57 sock, connection_id = self.tracker.udp_connect() 63 sock, connection_id = self.tracker.udp_connect()
@@ -96,5 +102,27 @@ class MissingBlacklist(TrackerTestCase):
96 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1) 102 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1)
97 103
98 104
105class ListIsInPlaceBeforeTheStateFile(TrackerTestCase):
106 """The loader used to run in a thread of its own, so a state file read at
107 startup was checked against a list that was still empty."""
108
109 config = "access.blacklist {dir}/blacklist\n"
110 files = {"blacklist": listing(BLOCKED)}
111
112 def test_a_blacklisted_torrent_in_a_state_file_is_not_restored(self):
113 touched = int(time.time()) // 60 - 5
114 path = os.path.join(self.tracker.dir, "state")
115 with open(path, "w") as handle:
116 handle.write("%s:%d:7\n%s:%d:7\n" % (BLOCKED.hex(), touched, ALLOWED.hex(), touched))
117
118 restarted = Tracker(self.config, self.files, extra_args=["-l", path])
119 try:
120 self.assertNotIn(BLOCKED, restarted.scrape(BLOCKED)[b"files"], "the blacklist was not in place when the state file was read")
121 self.assertIn(ALLOWED, restarted.scrape(ALLOWED)[b"files"], "the state file was not read at all")
122 restarted.stop()
123 finally:
124 restarted._cleanup()
125
126
99if __name__ == "__main__": 127if __name__ == "__main__":
100 unittest.main() 128 unittest.main()
diff --git a/tests/integration/test_announce.py b/tests/integration/test_announce.py
index ffbc07b..2d21417 100644
--- a/tests/integration/test_announce.py
+++ b/tests/integration/test_announce.py
@@ -118,9 +118,24 @@ class AnnounceRejects(TrackerTestCase):
118 def test_a_port_out_of_range_is_rejected(self): 118 def test_a_port_out_of_range_is_rejected(self):
119 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=65536&left=0") 119 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=65536&left=0")
120 120
121 def test_a_negative_port_is_rejected(self):
122 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=-1&left=0")
123
121 def test_a_port_that_is_not_a_number_is_rejected(self): 124 def test_a_port_that_is_not_a_number_is_rejected(self):
122 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0") 125 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0")
123 126
127 def test_an_ip_that_fills_the_reply_buffer_is_refused(self):
128 """The value is decoded into the reply buffer and then terminated, so
129 the longest one that fits has to leave room for the terminator. 8096
130 bytes is what lies between where it is decoded and the buffer's end."""
131 connection = self.tracker.connect()
132 try:
133 connection.sock.sendall(b"GET /a?ip=" + b"1" * 8096 + b"\n\n")
134 status, _, _ = connection.reply()
135 self.assertTrue(status.startswith(b"HTTP/1.0 400"), status)
136 finally:
137 connection.close()
138
124 def test_two_info_hashes_are_rejected(self): 139 def test_two_info_hashes_are_rejected(self):
125 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0") 140 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0")
126 141
diff --git a/tests/integration/test_concurrency.py b/tests/integration/test_concurrency.py
index 1374852..528992d 100644
--- a/tests/integration/test_concurrency.py
+++ b/tests/integration/test_concurrency.py
@@ -148,7 +148,7 @@ class ConcurrentWorkerTasks(TrackerTestCase):
148 148
149 def poll(index): 149 def poll(index):
150 for _ in range(10): 150 for _ in range(10):
151 for mode in ("everything", "top100", "peer", "torr", "s24s"): 151 for mode in ("everything", "top100", "peer", "torr"):
152 self.tracker.stats(mode) 152 self.tracker.stats(mode)
153 153
154 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)] 154 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)]
diff --git a/tests/integration/test_config.py b/tests/integration/test_config.py
index 2f6bdc4..fe5cf9d 100644
--- a/tests/integration/test_config.py
+++ b/tests/integration/test_config.py
@@ -49,3 +49,24 @@ class AListenLineThatDoesNotParse(unittest.TestCase):
49 49
50 def test_so_does_an_option_it_does_not_know(self): 50 def test_so_does_an_option_it_does_not_know(self):
51 self.assertIn("want an address", self.refuses("listen.tcp 127.0.0.1:7999 wokers=2\n")) 51 self.assertIn("want an address", self.refuses("listen.tcp 127.0.0.1:7999 wokers=2\n"))
52
53
54class EmptyTorrentTimeout(TrackerTestCase):
55 config = "tracker.empty_torrent_timeout 60\n"
56
57 def test_the_tracker_accepts_the_option_and_serves(self):
58 self.assertEqual(self.tracker.announce(self.hash_for("emptyto"))[b"complete"], 1)
59 self.assertNotIn("Unhandled line", self.tracker.output())
60 self.assertNotIn("Parse error", self.tracker.output())
61
62
63class EmptyTorrentTimeoutThatDoesNotParse(unittest.TestCase):
64 def test_a_non_numeric_value_warns_but_the_tracker_serves(self):
65 """A scalar that will not parse warns and is ignored, unlike a listen
66 line, which stops the tracker."""
67 tracker = Tracker("tracker.empty_torrent_timeout later\n")
68 try:
69 self.assertEqual(tracker.announce(b"emptytobad\0\0\0\0\0\0\0\0\0\0")[b"complete"], 1)
70 self.assertIn("Parse error", tracker.output())
71 finally:
72 tracker._cleanup()
diff --git a/tests/integration/test_dynamic_accesslist.py b/tests/integration/test_dynamic_accesslist.py
index 7fa5fde..2072f5e 100644
--- a/tests/integration/test_dynamic_accesslist.py
+++ b/tests/integration/test_dynamic_accesslist.py
@@ -40,6 +40,24 @@ class DynamicAccesslist(TrackerTestCase):
40 time.sleep(0.05) 40 time.sleep(0.05)
41 return False 41 return False
42 42
43 def test_a_hash_added_after_a_reload_is_blocked(self):
44 """A reload leaves the add changeset an empty list rather than an
45 absent one. Adding against it walked a null array; the hash must be
46 blocked and the tracker must stay up."""
47 OTHER = bytes(range(21, 41))
48 self.feed("add.fifo", BLOCKED)
49 self.assertTrue(self.wait_for(BLOCKED, blocked=True), "the first hash was never blocked")
50
51 # The reload empties the add changeset, which unblocks the first hash.
52 # Wait for that before adding the second, so it lands on the empty list
53 # the bug walked, not on the changeset before the reload has cleared it.
54 self.tracker.reload()
55 self.assertTrue(self.wait_for(BLOCKED, blocked=False), "the reload never emptied the changeset")
56
57 self.feed("add.fifo", OTHER)
58 self.assertTrue(self.wait_for(OTHER, blocked=True), "the hash added after the reload was never blocked")
59 # tearDown's stop() surfaces any sanitizer complaint on the way out.
60
43 def test_a_hash_can_be_blocked_and_released_while_running(self): 61 def test_a_hash_can_be_blocked_and_released_while_running(self):
44 self.assertNotIn(b"failure reason", self.tracker.announce(BLOCKED)) 62 self.assertNotIn(b"failure reason", self.tracker.announce(BLOCKED))
45 63
diff --git a/tests/integration/test_fullscrape.py b/tests/integration/test_fullscrape.py
index be7b502..45b3ffb 100644
--- a/tests/integration/test_fullscrape.py
+++ b/tests/integration/test_fullscrape.py
@@ -8,6 +8,7 @@ so these also exercise the chunked transfer the ordinary replies never take.
8 8
9import gzip 9import gzip
10import struct 10import struct
11import time
11import unittest 12import unittest
12 13
13from harness import TrackerTestCase, bdecode 14from harness import TrackerTestCase, bdecode
@@ -78,13 +79,14 @@ class FullScrape(TrackerTestCase):
78 escaped = line.rsplit(b":", 2)[0] 79 escaped = line.rsplit(b":", 2)[0]
79 self.assertIn(b"%", escaped, "these hashes are mostly unprintable bytes") 80 self.assertIn(b"%", escaped, "these hashes are mostly unprintable bytes")
80 81
81 def test_the_state_dump_carries_a_base_time_rather_than_a_peer_count(self): 82 def test_the_state_dump_carries_a_stamp_rather_than_a_peer_count(self):
82 """What a restart reads back, so its second column is the torrent's 83 """What a restart reads back. The second column is the minute the
83 own clock and not a count of anybody.""" 84 torrent was last touched and not a count of anybody, by the wall
85 clock, which is the only one two runs of the tracker agree on."""
84 entries = self.entries_from_lines(self.scrape_all("/stats?mode=statedump")) 86 entries = self.entries_from_lines(self.scrape_all("/stats?mode=statedump"))
85 self.assertIn(self.seeding.hex().upper().encode(), entries) 87 self.assertIn(self.seeding.hex().upper().encode(), entries)
86 base, completed = entries[self.seeding.hex().upper().encode()] 88 stamp, completed = entries[self.seeding.hex().upper().encode()]
87 self.assertGreater(int(base), 0) 89 self.assertAlmostEqual(int(stamp), int(time.time()) // 60, delta=1, msg="announced a moment ago")
88 self.assertEqual(int(completed), 0) 90 self.assertEqual(int(completed), 0)
89 91
90 # ------------------------------------------------------------ shape 92 # ------------------------------------------------------------ shape
diff --git a/tests/integration/test_keepalive.py b/tests/integration/test_keepalive.py
index 01f02a5..f9aa468 100644
--- a/tests/integration/test_keepalive.py
+++ b/tests/integration/test_keepalive.py
@@ -7,6 +7,7 @@ the request has moved on, so whether to keep the connection has to be
7remembered on the connection itself. 7remembered on the connection itself.
8""" 8"""
9 9
10import time
10import unittest 11import unittest
11import urllib.parse 12import urllib.parse
12 13
@@ -106,6 +107,40 @@ class KeepAlive(TrackerTestCase):
106 finally: 107 finally:
107 c.close() 108 c.close()
108 109
110 def test_a_tiny_split_request_does_not_overread(self):
111 """A request that arrives in pieces and completes as a buffer shorter
112 than the dispatch literals (\"GET /\" etc.) used to read past the
113 exactly sized buffer. It must be rejected without a sanitizer hit."""
114 c = self.tracker.connect()
115 try:
116 c.sock.sendall(b"\r\n")
117 time.sleep(0.05)
118 c.sock.sendall(b"\r\n") # completes as a 4-byte buffer
119 time.sleep(0.1)
120 finally:
121 c.close()
122 # the tracker must still answer; tearDown's stop() surfaces any sanitizer abort
123 answer = self.tracker.announce(self.hash_for("after-tiny"), port=6881, left=0)
124 self.assertNotIn(b"failure reason", answer, "the tracker stopped serving after a tiny request")
125
126 def test_a_split_request_answered_by_a_worker_does_not_spin(self):
127 """A reply that a worker produces does not go through the send path,
128 so the request stays in the buffer the read loop is reading. The loop
129 used to find the same request again on every pass, queue a task for
130 it, and never hand the thread back to the event loop."""
131 for path in ("/stats", "/scrape"):
132 c = self.tracker.connect()
133 try:
134 c.sock.sendall(("GET %s HTTP/1.1\r\nConnection: keep-alive\r\n" % path).encode())
135 time.sleep(0.2)
136 c.sock.sendall(b"\r\n")
137 self.assertIn(b"200", c.reply()[0], "%s was not answered" % path)
138 finally:
139 c.close()
140
141 answer = self.tracker.announce(self.hash_for("after-" + path), port=6881, left=0)
142 self.assertNotIn(b"failure reason", answer, "the tracker stopped serving after %s" % path)
143
109 144
110if __name__ == "__main__": 145if __name__ == "__main__":
111 unittest.main() 146 unittest.main()
diff --git a/tests/integration/test_livesync.py b/tests/integration/test_livesync.py
index f4cb2db..e146d93 100644
--- a/tests/integration/test_livesync.py
+++ b/tests/integration/test_livesync.py
@@ -72,6 +72,19 @@ class LiveSyncIn(TrackerTestCase):
72 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)), 72 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)),
73 "scrape says %r" % (self.counts(info_hash),)) 73 "scrape says %r" % (self.counts(info_hash),))
74 74
75 def test_many_v6_announces_do_not_overflow_the_send_buffer(self):
76 """The outgoing peer buffer is filled by announces to a clustered
77 tracker. The flush watermark used sizeof(ot_peer) (== 1), so a v6
78 record could be appended past the 1480-byte buffer onto the adjacent
79 fill field, which then drove an oversized stack copy. Well past the
80 old overflow point (~37 v6 peers) the tracker must still be alive."""
81 last = None
82 for i in range(80):
83 last = self.tracker.announce(self.hash_for("flood-%d" % i),
84 ip="2001:db8::%x" % (i + 1), port=7000 + i, left=1)
85 self.assertIn(b"complete", last, "the tracker stopped answering mid-flood")
86 # tearDown's stop() surfaces any sanitizer complaint on the way out.
87
75 def test_one_packet_carries_several_torrents(self): 88 def test_one_packet_carries_several_torrents(self):
76 hashes = [self.hash_for("sync-many-%d" % i) for i in range(4)] 89 hashes = [self.hash_for("sync-many-%d" % i) for i in range(4)]
77 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (5 + i), 6881, FLAG_SEEDING)) 90 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (5 + i), 6881, FLAG_SEEDING))
diff --git a/tests/integration/test_statefile.py b/tests/integration/test_statefile.py
new file mode 100644
index 0000000..a3c8d59
--- /dev/null
+++ b/tests/integration/test_statefile.py
@@ -0,0 +1,97 @@
1"""The state dump and the -l switch that reads it back.
2
3The second column is the minute a torrent was last touched, by the wall
4clock, which is what the file has recorded for years and the only clock two
5runs of the tracker agree on.
6"""
7
8import os
9import time
10import unittest
11
12from harness import Tracker, TrackerTestCase
13
14
15class StateFileRoundTrip(TrackerTestCase):
16 def dump(self):
17 return self.tracker.get("/stats?mode=statedump")
18
19 def test_a_dumped_torrent_comes_back_with_its_completed_count(self):
20 info_hash = self.hash_for("state-rt")
21 self.tracker.announce(info_hash, port=6001, left=0, event="completed")
22 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"downloaded"], 1)
23
24 path = os.path.join(self.tracker.dir, "state")
25 with open(path, "wb") as handle:
26 handle.write(self.dump())
27
28 restarted = Tracker(extra_args=["-l", path])
29 try:
30 files = restarted.scrape(info_hash)[b"files"]
31 self.assertIn(info_hash, files, "the torrent did not survive the restart")
32 entry = files[info_hash]
33 self.assertEqual(entry[b"downloaded"], 1, "the completed count did not survive")
34 self.assertEqual(entry[b"complete"], 0, "no peers are carried over, only the torrent")
35 self.assertEqual(entry[b"incomplete"], 0)
36 complaints = restarted.stop()
37 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
38 finally:
39 restarted._cleanup()
40
41 def test_a_torrent_older_than_the_tracker_would_keep_is_not_loaded(self):
42 """An age past the torrent timeout would be cleaned away on the first
43 sweep, so it is never built in the first place."""
44 info_hash = self.hash_for("state-stale")
45 path = os.path.join(self.tracker.dir, "stale")
46 with open(path, "w") as handle:
47 handle.write("%s:%d:7\n" % (info_hash.hex(), 24 * 60 + 1))
48
49 restarted = Tracker(extra_args=["-l", path])
50 try:
51 self.assertNotIn(info_hash, restarted.scrape(info_hash)[b"files"])
52 restarted.stop()
53 finally:
54 restarted._cleanup()
55
56
57class StateFileWithNonsenseStamps(TrackerTestCase):
58 """The column is read as unsigned and handed on as a signed ot_time. A
59 value at or above 2^63 arrived negative, cleared the timeout check, and
60 put the torrent's base in the future, where the cleaner never reaches it.
61 At exactly 2^63 the subtraction itself overflowed."""
62
63 def stamps(self):
64 now = int(time.time()) // 60
65 return {
66 "overflow": 2**63,
67 "minus-one": 2**64 - 1,
68 "int64-max": 2**63 - 1,
69 "in-the-future": now + 60,
70 "past-timeout": now - (24 * 60 + 1),
71 }
72
73 def test_no_stamp_outside_the_timeout_builds_a_torrent(self):
74 stamps = self.stamps()
75 lines = ["%s:%d:7" % (self.hash_for(name).hex(), stamp) for name, stamp in stamps.items()]
76 lines.append("%s:%d:7" % (self.hash_for("honest").hex(), int(time.time()) // 60 - 5))
77
78 path = os.path.join(self.tracker.dir, "nonsense")
79 with open(path, "w") as handle:
80 handle.write("\n".join(lines) + "\n")
81
82 restarted = Tracker(extra_args=["-l", path])
83 try:
84 for name, stamp in stamps.items():
85 self.assertNotIn(self.hash_for(name), restarted.scrape(self.hash_for(name))[b"files"],
86 "the line stamped %d was loaded" % stamp)
87 self.assertIn(self.hash_for("honest"), restarted.scrape(self.hash_for("honest"))[b"files"],
88 "the state file was not read at all")
89 self.assertEqual(restarted.torrent_count(), 1)
90 complaints = restarted.stop()
91 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
92 finally:
93 restarted._cleanup()
94
95
96if __name__ == "__main__":
97 unittest.main()
diff --git a/tests/integration/test_stats.py b/tests/integration/test_stats.py
index 088d8a1..46ca39b 100644
--- a/tests/integration/test_stats.py
+++ b/tests/integration/test_stats.py
@@ -5,9 +5,7 @@ every one of them and, where the number means something, that it moves when
5the thing it counts happens. 5the thing it counts happens.
6""" 6"""
7 7
8import ipaddress
9import re 8import re
10import socket
11import unittest 9import unittest
12import urllib.error 10import urllib.error
13import xml.etree.ElementTree 11import xml.etree.ElementTree
@@ -18,7 +16,7 @@ from harness import TrackerTestCase
18# and belong to test_fullscrape; "woodpeckers" sits behind a 16# and belong to test_fullscrape; "woodpeckers" sits behind a
19# feature flag this build does not set. 17# feature flag this build does not set.
20MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"] 18MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"]
21TEXT_MODES = ["herr", "s24s", "top10", "top100", "renew"] 19TEXT_MODES = ["herr", "top10", "top100", "renew"]
22 20
23 21
24class StatsShape(TrackerTestCase): 22class StatsShape(TrackerTestCase):
@@ -144,39 +142,5 @@ class StatsTop(TrackerTestCase):
144 self.assertIn(heading, body) 142 self.assertIn(heading, body)
145 143
146 144
147class StatsNetworks(TrackerTestCase):
148 def source_address(self):
149 """Which address the tracker sees us from is not ours to choose: a
150 FreeBSD jail relocates a loopback connection to the jail's own
151 address, so ask the socket rather than assume 127.0.0.1."""
152 probe = socket.create_connection(("127.0.0.1", self.tracker.port), timeout=5)
153 try:
154 return probe.getsockname()[0]
155 finally:
156 probe.close()
157
158 def test_the_slash24_report_names_the_announcing_network(self):
159 source = self.source_address()
160 self.tracker.announce(self.hash_for("s24"), port=6001, left=0)
161 body = self.tracker.stats("s24s")
162 self.assertIn(b"Networks, limit /28:", body)
163 self.assertIn(b"Networks, limit /24:", body)
164
165 # The prefix is the first three address bytes of a v4 peer, left
166 # aligned in a sixteen byte buffer and then printed by the v6
167 # formatter, so 127.0.0.0/24 reads as "7f00::" rather than as the
168 # network an operator asked about. Pinned as it is, not blessed.
169 prefix = socket.inet_aton(source)[:3] + b"\0" * 13
170 self.assertIn(str(ipaddress.IPv6Address(prefix)).encode(), body)
171
172 def test_the_report_counts_one_network_per_announcing_address(self):
173 for port in (6001, 6002, 6003):
174 self.tracker.announce(self.hash_for("s24count"), port=port, left=0)
175 lines = [line for line in self.tracker.stats("s24s").splitlines() if b":" in line and b"limit" not in line]
176 self.assertEqual(len(lines), 2, "one line under each of the two limits")
177 for line in lines:
178 self.assertEqual(int(line.split(b":")[0]), 3, "three peers from the one network")
179
180
181if __name__ == "__main__": 145if __name__ == "__main__":
182 unittest.main() 146 unittest.main()
diff --git a/tests/integration/test_udp.py b/tests/integration/test_udp.py
index 1cb2389..8a255ec 100644
--- a/tests/integration/test_udp.py
+++ b/tests/integration/test_udp.py
@@ -9,7 +9,7 @@ import socket
9import struct 9import struct
10import unittest 10import unittest
11 11
12from harness import TrackerTestCase 12from harness import Tracker, TrackerTestCase
13 13
14MAGIC = 0x41727101980 14MAGIC = 0x41727101980
15 15
@@ -44,6 +44,17 @@ class UdpProtocol(TrackerTestCase):
44 self.assertEqual(action, 3, "action 3 is the error packet") 44 self.assertEqual(action, 3, "action 3 is the error packet")
45 self.assertIn(b"Connection ID missmatch", answer[8:]) 45 self.assertIn(b"Connection ID missmatch", answer[8:])
46 46
47 def test_a_wrong_connection_id_is_not_answered_with_more_than_was_sent(self):
48 """The sender's address is unverified at this point, so the error
49 must not be a way to throw bytes at somebody else."""
50 scrape = struct.pack(">QII", 0, 2, 3) + self.hash_for("udpbadscrape")
51 answer = self.tracker.udp_raw(scrape)
52 self.assertIsNotNone(answer, "a whole scrape is long enough to be told")
53 self.assertLessEqual(len(answer), len(scrape))
54 self.assertIsNone(self.tracker.udp_raw(scrape[:16]))
55 self.assertIsNone(self.tracker.udp_raw(scrape[: len(answer) - 1]))
56 self.assertIsNotNone(self.tracker.udp_raw(scrape[: len(answer)]))
57
47 def test_a_packet_shorter_than_the_header_is_ignored(self): 58 def test_a_packet_shorter_than_the_header_is_ignored(self):
48 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15)) 59 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15))
49 60
@@ -148,6 +159,28 @@ class UdpScrape(TrackerTestCase):
148 finally: 159 finally:
149 sock.close() 160 sock.close()
150 161
162 def test_a_hash_cut_short_is_not_scraped(self):
163 """What follows the last whole hash is not a hash, and the bytes that
164 would complete it are not the client's."""
165 info_hash = self.hash_for("udpcut")
166 sock, connection_id = self.tracker.udp_connect()
167 try:
168 sock.sendto(
169 struct.pack(">QII", connection_id, 2, 3) + info_hash + b"\x00" * 7, ("127.0.0.1", self.tracker.port)
170 )
171 self.assertEqual(len(sock.recv(2048)), 8 + 12)
172 finally:
173 sock.close()
174
175 def test_a_scrape_answers_no_more_hashes_than_the_protocol_allows(self):
176 sock, connection_id = self.tracker.udp_connect()
177 try:
178 hashes = b"".join(self.hash_for("udpmany%d" % n) for n in range(80))
179 sock.sendto(struct.pack(">QII", connection_id, 2, 4) + hashes, ("127.0.0.1", self.tracker.port))
180 self.assertEqual(len(sock.recv(2048)), 8 + 12 * 74)
181 finally:
182 sock.close()
183
151 184
152class UdpWorkersConfiguredAfterTheListener(TrackerTestCase): 185class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
153 """The harness writes its listen lines first, so this directive lands 186 """The harness writes its listen lines first, so this directive lands
@@ -166,3 +199,20 @@ class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
166 199
167if __name__ == "__main__": 200if __name__ == "__main__":
168 unittest.main() 201 unittest.main()
202
203
204class UdpAddressAlreadyTaken(TrackerTestCase):
205 def test_a_second_tracker_on_the_same_udp_address_says_so(self):
206 """Linux lets it start all the same, and from then on the two take
207 each other's packets. FreeBSD refuses the bind that follows, and the
208 warning is then what explains the refusal."""
209 try:
210 second = Tracker("listen.udp 127.0.0.1:%d\n" % self.tracker.port)
211 except AssertionError as refused:
212 said = str(refused)
213 else:
214 said = second.output()
215 second.stop()
216 second._cleanup()
217 self.assertIn("is already in use", said)
218 self.assertNotIn("is already in use", self.tracker.output())
diff --git a/tests/runner.c b/tests/runner.c
index ae2565b..2398991 100644
--- a/tests/runner.c
+++ b/tests/runner.c
@@ -27,6 +27,7 @@ static const struct module modules[] = {{"ot_urlencoded", test_urlencoded},
27 {"ot_socket", test_socket}, 27 {"ot_socket", test_socket},
28 {"ot_mutex", test_mutex}, 28 {"ot_mutex", test_mutex},
29 {"trackerlogic", test_trackerlogic}, 29 {"trackerlogic", test_trackerlogic},
30 {"clean", test_clean},
30 {"ot_workqueue", test_workqueue}, 31 {"ot_workqueue", test_workqueue},
31 {"ot_batch", test_batch}, 32 {"ot_batch", test_batch},
32 {"ot_fdstate", test_fdstate}, 33 {"ot_fdstate", test_fdstate},
diff --git a/tests/stubs.c b/tests/stubs.c
index f7ac679..b8ab174 100644
--- a/tests/stubs.c
+++ b/tests/stubs.c
@@ -26,16 +26,11 @@ long io_trywrite(long d, const char *buf, long len) {
26/* trackerlogic.c is under test, and starting it up starts every module it 26/* trackerlogic.c is under test, and starting it up starts every module it
27 leans on. None of them is driven by these tests, so they are answered here 27 leans on. None of them is driven by these tests, so they are answered here
28 rather than linked in and left to run threads of their own. */ 28 rather than linked in and left to run threads of their own. */
29void clean_init(void) {} 29/* ot_clean.c is in the unit build for t_clean, so its thread control is the
30void clean_deinit(void) {} 30 real thing and only the stats hook it calls is stubbed here. */
31int clean_single_torrent(ot_torrent *torrent) {
32 (void)torrent;
33 return 0;
34}
35void fullscrape_init(void) {} 31void fullscrape_init(void) {}
36void fullscrape_deinit(void) {} 32void fullscrape_deinit(void) {}
37void livesync_init(void) {} 33void stats_cleanup(void) {}
38void livesync_deinit(void) {}
39void livesync_tell(struct ot_workstruct *ws) { (void)ws; } 34void livesync_tell(struct ot_workstruct *ws) { (void)ws; }
40void stats_init(void) {} 35void stats_init(void) {}
41void stats_deinit(void) {} 36void stats_deinit(void) {}
diff --git a/tests/t_clean.c b/tests/t_clean.c
new file mode 100644
index 0000000..ce17bc3
--- /dev/null
+++ b/tests/t_clean.c
@@ -0,0 +1,222 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#include <arpa/inet.h>
5#include <signal.h>
6#include <pthread.h>
7#include <string.h>
8
9#include "ot_clean.h"
10#include "ot_mutex.h"
11#include "trackerlogic.h"
12#include "test.h"
13
14/* A clock stepped backwards used to leave the torrent's base in the future, so
15 the span the cleaner works from came out negative. It was then added to a
16 peer's age and stored in the single byte that age lives in, where -1 reads
17 as 255 and the next pass threw the whole swarm away. */
18
19static void announce(struct ot_workstruct *ws, ot_hash *hash, uint8_t last_octet, int seeding) {
20 static const uint8_t v4mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
21
22 /* The peer list is written into the reply, which workstruct_init leaves
23 for its caller to point somewhere */
24 ws->reply = ws->outbuf;
25
26 memset(&ws->peer, 0, sizeof(ws->peer));
27 memcpy(&ws->peer, v4mapped, sizeof(v4mapped));
28 ((uint8_t *)&ws->peer)[15] = last_octet;
29 OT_SETPORT(&ws->peer, &(uint16_t){6881});
30 if (seeding)
31 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;
32 ws->hash = hash;
33 add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, 0);
34}
35
36/* A distinct v4 peer addressed by two octets, to build swarms past 256 */
37static size_t announce_wide(struct ot_workstruct *ws, ot_hash *hash, unsigned int which, size_t amount) {
38 static const uint8_t v4mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
39
40 ws->reply = ws->outbuf;
41 memset(&ws->peer, 0, sizeof(ws->peer));
42 memcpy(&ws->peer, v4mapped, sizeof(v4mapped));
43 ((uint8_t *)&ws->peer)[14] = (uint8_t)(which >> 8);
44 ((uint8_t *)&ws->peer)[15] = (uint8_t)which;
45 OT_SETPORT(&ws->peer, &(uint16_t){6881});
46 ws->hash = hash;
47 return add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, amount);
48}
49
50static size_t peers_in(ot_hash *hash) {
51 char reply[1024];
52 size_t len = return_udp_scrape_for_torrent(*hash, reply);
53 uint32_t seeders, leechers;
54
55 if (len < 12)
56 return 0;
57 memcpy(&seeders, reply, 4);
58 memcpy(&leechers, reply + 8, 4);
59 return (size_t)ntohl(seeders) + (size_t)ntohl(leechers);
60}
61
62static ot_torrent *torrent_of(ot_hash *hash) {
63 ot_vector *bucket = mutex_bucket_lock_by_hash(*hash);
64 ot_torrent *t = (ot_torrent *)bucket->data;
65 ot_torrent *found = NULL;
66 size_t i;
67
68 for (i = 0; i < bucket->size; ++i)
69 if (!memcmp(t[i].hash, hash, sizeof(ot_hash)))
70 found = t + i;
71 mutex_bucket_unlock_by_hash(*hash, 0);
72 return found;
73}
74
75/* What a clock stepped back by `minutes` leaves behind */
76static void step_clock_back(ot_torrent *torrent, int minutes) {
77 torrent->base += minutes;
78}
79
80/* What the next minute of a well behaved clock looks like */
81static void age_by_a_minute(ot_torrent *torrent) {
82 torrent->base -= 1;
83}
84
85static void case_a_clock_that_went_back_keeps_the_swarm(void) {
86 struct ot_workstruct ws;
87 ot_hash hash;
88 ot_torrent *torrent;
89
90 test_case("a swarm survives the clock being stepped backwards");
91 memset(hash, 0x31, sizeof(hash));
92 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
93
94 announce(&ws, &hash, 1, 1);
95 announce(&ws, &hash, 2, 0);
96 CHECK_INT(peers_in(&hash), 2);
97
98 torrent = torrent_of(&hash);
99 CHECK(torrent != NULL);
100 step_clock_back(torrent, 5);
101
102 /* The pass that sees the step keeps everybody either way: unclamped it
103 writes a negative span into each peer's age byte, where it reads as 251
104 rather than as a removal. */
105 CHECK_INT(clean_single_torrent(torrent), 0);
106 CHECK_INT(peers_in(&hash), 2);
107
108 /* A minute later, and this is where a poisoned age byte took the swarm:
109 251 plus one minute is past any timeout. */
110 age_by_a_minute(torrent);
111 CHECK_INT(clean_single_torrent(torrent), 0);
112 CHECK_INT(peers_in(&hash), 2);
113
114 workstruct_deinit(&ws);
115}
116
117static void case_an_idle_swarm_still_ages_out(void) {
118 struct ot_workstruct ws;
119 ot_hash hash;
120 ot_torrent *torrent;
121
122 test_case("a swarm nobody touched is still cleaned away");
123 memset(hash, 0x32, sizeof(hash));
124 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
125
126 announce(&ws, &hash, 3, 1);
127 CHECK_INT(peers_in(&hash), 1);
128
129 torrent = torrent_of(&hash);
130 CHECK(torrent != NULL);
131 step_clock_back(torrent, -OT_PEER_TIMEOUT);
132
133 CHECK_INT(clean_single_torrent(torrent), 0);
134 CHECK_INT(peers_in(&hash), 0);
135
136 workstruct_deinit(&ws);
137}
138
139static void case_empty_torrent_timeout_bounds_a_counter_only_torrent(void) {
140 struct ot_workstruct ws;
141 ot_hash hash;
142 ot_torrent *torrent;
143 ot_time saved = g_empty_torrent_timeout;
144
145 test_case("the empty torrent timeout bounds a counter-only torrent's life");
146 memset(hash, 0x33, sizeof(hash));
147 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
148
149 announce(&ws, &hash, 7, 1);
150 torrent = torrent_of(&hash);
151 CHECK(torrent != NULL);
152 torrent->down_count = 1; /* one completed download to remember it by */
153
154 /* Age the only peer out: the torrent falls empty but keeps its count */
155 step_clock_back(torrent, -OT_PEER_TIMEOUT);
156 CHECK_INT(clean_single_torrent(torrent), 0);
157 CHECK_INT(peers_in(&hash), 0);
158
159 /* Carry it a little past a short empty-torrent timeout */
160 step_clock_back(torrent, -10);
161
162 /* The default, matching the torrent timeout, still holds it for the count */
163 g_empty_torrent_timeout = OT_TORRENT_TIMEOUT;
164 CHECK_INT(clean_single_torrent(torrent), 0);
165
166 /* A timeout it has now exceeded lets the next sweep drop it */
167 g_empty_torrent_timeout = OT_PEER_TIMEOUT + 5;
168 CHECK_INT(clean_single_torrent(torrent), 1);
169
170 g_empty_torrent_timeout = saved;
171 workstruct_deinit(&ws);
172}
173
174static void case_a_bucketed_swarm_survives_clean_and_serves(void) {
175 struct ot_workstruct ws;
176 ot_hash hash;
177 ot_torrent *torrent;
178 unsigned int i;
179 const unsigned int n = 600; /* past OT_PEER_BUCKET_MINCOUNT (512) */
180
181 test_case("a swarm large enough to be bucketed cleans, splits and serves without loss");
182 memset(hash, 0x34, sizeof(hash));
183 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
184
185 for (i = 0; i < n; ++i)
186 announce_wide(&ws, &hash, i, 0);
187 CHECK_INT(peers_in(&hash), n);
188
189 torrent = torrent_of(&hash);
190 CHECK(torrent != NULL);
191 CHECK(torrent->peer_list != NULL);
192
193 /* A clean with a minute elapsed splits the flat vector into buckets */
194 step_clock_back(torrent, -1);
195 CHECK_INT(clean_single_torrent(torrent), 0);
196 CHECK(torrent->peer_list != NULL);
197 CHECK_INT(OT_VECTOR_HASBUCKETS(&torrent->peer_list->peers4), 1);
198 CHECK_INT(peers_in(&hash), n);
199
200 /* Serve a selection back, which walks the bucket list */
201 CHECK(announce_wide(&ws, &hash, 1, 200) > 0);
202 CHECK_INT(peers_in(&hash), n);
203
204 workstruct_deinit(&ws);
205}
206
207void test_clean(void) {
208 sigset_t hup;
209
210 /* accesslist_deinit sends SIGHUP to its reader, trackerlogic_init starts
211 the accesslist, and the test process must not take it */
212 sigemptyset(&hup);
213 sigaddset(&hup, SIGHUP);
214 pthread_sigmask(SIG_BLOCK, &hup, NULL);
215
216 trackerlogic_init();
217 case_a_clock_that_went_back_keeps_the_swarm();
218 case_an_idle_swarm_still_ages_out();
219 case_empty_torrent_timeout_bounds_a_counter_only_torrent();
220 case_a_bucketed_swarm_survives_clean_and_serves();
221 trackerlogic_deinit();
222}
diff --git a/tests/t_socket.c b/tests/t_socket.c
index 8e917a3..6f07f95 100644
--- a/tests/t_socket.c
+++ b/tests/t_socket.c
@@ -342,6 +342,24 @@ static void case_bind_failure(void) {
342 CHECK_INT(next_descriptor(), before); 342 CHECK_INT(next_descriptor(), before);
343} 343}
344 344
345/* The holder binds the way the tracker does, which lets a second socket in
346 beside it, and that is what the probe is there to see through. */
347static void case_a_taken_udp_address_is_noticed(void) {
348 char ip[16];
349 uint16_t port;
350 int holder;
351
352 test_case("a udp address somebody holds is reported as taken");
353 holder = socket_udp_bind(ip_loopback, 0, SOCKET_SHARED);
354 CHECK(holder != -1);
355 bound_address(holder, ip, &port);
356 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 1);
357
358 test_case("and as free again once it is let go");
359 close(holder);
360 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 0);
361}
362
345#ifdef WANT_SYNC_LIVE 363#ifdef WANT_SYNC_LIVE
346/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs 364/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs
347 with a single byte, so ask how much was written. */ 365 with a single byte, so ask how much was written. */
@@ -391,6 +409,7 @@ void test_socket(void) {
391 case_deferred_accept(); 409 case_deferred_accept();
392 case_connect_refused(); 410 case_connect_refused();
393 case_bind_failure(); 411 case_bind_failure();
412 case_a_taken_udp_address_is_noticed();
394#ifdef WANT_SYNC_LIVE 413#ifdef WANT_SYNC_LIVE
395 case_mcast_sender(); 414 case_mcast_sender();
396#endif 415#endif
diff --git a/tests/t_urlencoded.c b/tests/t_urlencoded.c
index 3b3e6c2..9935c1c 100644
--- a/tests/t_urlencoded.c
+++ b/tests/t_urlencoded.c
@@ -21,7 +21,7 @@ static void case_path(void) {
21 ssize_t n; 21 ssize_t n;
22 22
23 test_case("path stops at the question mark"); 23 test_case("path stops at the question mark");
24 n = urlencoded_parse(&p, dest, SCAN_PATH); 24 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
25 CHECK_INT(n, 9); 25 CHECK_INT(n, 9);
26 dest[n] = 0; 26 dest[n] = 0;
27 CHECK_STR(dest, "/announce"); 27 CHECK_STR(dest, "/announce");
@@ -35,22 +35,22 @@ static void case_param_and_value(void) {
35 ssize_t n; 35 ssize_t n;
36 36
37 test_case("parameter stops at '=', value stops at '&'"); 37 test_case("parameter stops at '=', value stops at '&'");
38 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_PARAM); 38 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
39 CHECK_INT(n, 9); 39 CHECK_INT(n, 9);
40 dest[n] = 0; 40 dest[n] = 0;
41 CHECK_STR(dest, "info_hash"); 41 CHECK_STR(dest, "info_hash");
42 42
43 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 43 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
44 CHECK_INT(n, 3); 44 CHECK_INT(n, 3);
45 dest[n] = 0; 45 dest[n] = 0;
46 CHECK_STR(dest, "abc"); 46 CHECK_STR(dest, "abc");
47 47
48 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_PARAM); 48 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
49 CHECK_INT(n, 4); 49 CHECK_INT(n, 4);
50 dest[n] = 0; 50 dest[n] = 0;
51 CHECK_STR(dest, "port"); 51 CHECK_STR(dest, "port");
52 52
53 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 53 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
54 CHECK_INT(n, 2); 54 CHECK_INT(n, 2);
55 dest[n] = 0; 55 dest[n] = 0;
56 CHECK_STR(dest, "80"); 56 CHECK_STR(dest, "80");
@@ -63,7 +63,7 @@ static void case_percent_decoding(void) {
63 ssize_t n; 63 ssize_t n;
64 64
65 test_case("percent escapes decode"); 65 test_case("percent escapes decode");
66 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 66 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
67 CHECK_INT(n, 3); 67 CHECK_INT(n, 3);
68 CHECK_MEM(dest, "ABC", 3); 68 CHECK_MEM(dest, "ABC", 3);
69} 69}
@@ -77,7 +77,7 @@ static void case_binary_info_hash(void) {
77 ssize_t n; 77 ssize_t n;
78 78
79 test_case("twenty byte binary value survives decoding"); 79 test_case("twenty byte binary value survives decoding");
80 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 80 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
81 CHECK_INT(n, 20); 81 CHECK_INT(n, 20);
82 CHECK_MEM(dest, want, 20); 82 CHECK_MEM(dest, want, 20);
83} 83}
@@ -88,7 +88,7 @@ static void case_in_place(void) {
88 ssize_t n; 88 ssize_t n;
89 89
90 test_case("decoding in place over the source is safe"); 90 test_case("decoding in place over the source is safe");
91 n = urlencoded_parse(&p, query, SCAN_SEARCHPATH_VALUE); 91 n = urlencoded_parse(&p, query, query + sizeof(query), SCAN_SEARCHPATH_VALUE);
92 CHECK_INT(n, 2); 92 CHECK_INT(n, 2);
93 CHECK_MEM(query, "AB", 2); 93 CHECK_MEM(query, "AB", 2);
94} 94}
@@ -100,7 +100,7 @@ static void case_bad_escape(void) {
100 ssize_t n; 100 ssize_t n;
101 101
102 test_case("a non hexadecimal escape is a parse error"); 102 test_case("a non hexadecimal escape is a parse error");
103 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 103 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
104 CHECK_INT(n, -1); 104 CHECK_INT(n, -1);
105} 105}
106 106
@@ -111,7 +111,7 @@ static void case_truncated_escape(void) {
111 ssize_t n; 111 ssize_t n;
112 112
113 test_case("an escape cut short by the terminator is a parse error"); 113 test_case("an escape cut short by the terminator is a parse error");
114 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 114 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
115 CHECK_INT(n, -1); 115 CHECK_INT(n, -1);
116} 116}
117 117
@@ -123,11 +123,11 @@ static void case_terminator(void) {
123 ssize_t n; 123 ssize_t n;
124 124
125 test_case("a hard terminator before any output reports end of input"); 125 test_case("a hard terminator before any output reports end of input");
126 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_PARAM); 126 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
127 CHECK_INT(n, -2); 127 CHECK_INT(n, -2);
128 128
129 p = space; 129 p = space;
130 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_PARAM); 130 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
131 CHECK_INT(n, -2); 131 CHECK_INT(n, -2);
132} 132}
133 133
@@ -138,10 +138,10 @@ static void case_terminator_after_output(void) {
138 ssize_t n; 138 ssize_t n;
139 139
140 test_case("a hard terminator after output is left for the next call"); 140 test_case("a hard terminator after output is left for the next call");
141 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 141 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
142 CHECK_INT(n, 3); 142 CHECK_INT(n, 3);
143 CHECK_INT(*p, 0); 143 CHECK_INT(*p, 0);
144 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 144 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
145 CHECK_INT(n, -2); 145 CHECK_INT(n, -2);
146} 146}
147 147
@@ -157,14 +157,14 @@ static void case_separators_are_contextual(void) {
157 ssize_t n; 157 ssize_t n;
158 158
159 test_case("a question mark is literal inside a value"); 159 test_case("a question mark is literal inside a value");
160 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 160 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
161 CHECK_INT(n, 3); 161 CHECK_INT(n, 3);
162 dest[n] = 0; 162 dest[n] = 0;
163 CHECK_STR(dest, "a?b"); 163 CHECK_STR(dest, "a?b");
164 164
165 test_case("an equals sign is literal inside a value"); 165 test_case("an equals sign is literal inside a value");
166 p = equals; 166 p = equals;
167 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 167 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
168 CHECK_INT(n, 3); 168 CHECK_INT(n, 3);
169 dest[n] = 0; 169 dest[n] = 0;
170 CHECK_STR(dest, "a=b"); 170 CHECK_STR(dest, "a=b");
@@ -177,7 +177,7 @@ static void case_ampersand_in_path(void) {
177 ssize_t n; 177 ssize_t n;
178 178
179 test_case("an ampersand in a path is a parse error"); 179 test_case("an ampersand in a path is a parse error");
180 n = urlencoded_parse(&p, dest, SCAN_PATH); 180 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
181 CHECK_INT(n, -1); 181 CHECK_INT(n, -1);
182} 182}
183 183
@@ -188,7 +188,7 @@ static void case_raw_high_byte(void) {
188 ssize_t n; 188 ssize_t n;
189 189
190 test_case("an undecoded byte above ASCII is a parse error"); 190 test_case("an undecoded byte above ASCII is a parse error");
191 n = urlencoded_parse(&p, dest, SCAN_SEARCHPATH_VALUE); 191 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
192 CHECK_INT(n, -1); 192 CHECK_INT(n, -1);
193} 193}
194 194
@@ -215,15 +215,15 @@ static void case_find_keywords(void) {
215 char *p = match; 215 char *p = match;
216 216
217 test_case("a known keyword returns its value"); 217 test_case("a known keyword returns its value");
218 CHECK_INT(urlencoded_match_keyword(keywords, &p, SCAN_SEARCHPATH_PARAM), 2); 218 CHECK_INT(urlencoded_match_keyword(keywords, &p, match + sizeof(match), SCAN_SEARCHPATH_PARAM), 2);
219 219
220 test_case("an unknown keyword returns -3"); 220 test_case("an unknown keyword returns -3");
221 p = nomatch; 221 p = nomatch;
222 CHECK_INT(urlencoded_match_keyword(keywords, &p, SCAN_SEARCHPATH_PARAM), -3); 222 CHECK_INT(urlencoded_match_keyword(keywords, &p, nomatch + sizeof(nomatch), SCAN_SEARCHPATH_PARAM), -3);
223 223
224 test_case("a prefix of a keyword does not match it"); 224 test_case("a prefix of a keyword does not match it");
225 p = prefix; 225 p = prefix;
226 CHECK_INT(urlencoded_match_keyword(keywords, &p, SCAN_SEARCHPATH_PARAM), -3); 226 CHECK_INT(urlencoded_match_keyword(keywords, &p, prefix + sizeof(prefix), SCAN_SEARCHPATH_PARAM), -3);
227} 227}
228 228
229/* The encoding direction. Which bytes survive unescaped is fixed by what 229/* The encoding direction. Which bytes survive unescaped is fixed by what
@@ -313,10 +313,30 @@ static void case_fmt_decoder_disagrees_on_dollar(void) {
313 dest[n] = 0; 313 dest[n] = 0;
314 CHECK_STR(dest, "a$b"); 314 CHECK_STR(dest, "a$b");
315 315
316 got = urlencoded_parse(&p, scanned, SCAN_SEARCHPATH_VALUE); 316 got = urlencoded_parse(&p, scanned, scanned + sizeof(scanned), SCAN_SEARCHPATH_VALUE);
317 CHECK_INT(got, -1); 317 CHECK_INT(got, -1);
318} 318}
319 319
320static void case_value_stops_at_dest_end(void) {
321 /* A value that decodes to more than the destination holds is a parse error,
322 not a write past the buffer. (ip= used to overflow ws->outbuf this way.) */
323 char query[] = "AAAAAAAAAA&x=1"; /* ten A's then a terminator */
324 char dest[4];
325 char *p = query;
326 test_case("a value longer than the destination returns -1");
327 CHECK_INT((int)urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE), -1);
328}
329
330static void case_keyword_with_decoded_nul_does_not_match(void) {
331 /* A percent-encoded NUL used to make a value match a shorter keyword and
332 then index the keyword past its end. */
333 static const ot_keywords keywords[] = {{"port", 1}, {NULL, -3}};
334 char query[] = "port%00xxxx=1";
335 char *p = query;
336 test_case("a keyword followed by a decoded NUL does not match the keyword");
337 CHECK_INT(urlencoded_match_keyword(keywords, &p, query + sizeof(query), SCAN_SEARCHPATH_PARAM), -3);
338}
339
320void test_urlencoded(void) { 340void test_urlencoded(void) {
321 case_path(); 341 case_path();
322 case_param_and_value(); 342 case_param_and_value();
@@ -332,6 +352,8 @@ void test_urlencoded(void) {
332 case_raw_high_byte(); 352 case_raw_high_byte();
333 case_skipvalue(); 353 case_skipvalue();
334 case_find_keywords(); 354 case_find_keywords();
355 case_value_stops_at_dest_end();
356 case_keyword_with_decoded_nul_does_not_match();
335 case_fmt_passes_safe_bytes(); 357 case_fmt_passes_safe_bytes();
336 case_fmt_escapes_the_rest(); 358 case_fmt_escapes_the_rest();
337 case_fmt_hex_is_lower_case(); 359 case_fmt_hex_is_lower_case();
diff --git a/tests/t_vector.c b/tests/t_vector.c
index f0a9bf7..42ce31a 100644
--- a/tests/t_vector.c
+++ b/tests/t_vector.c
@@ -200,17 +200,16 @@ static void case_insert_compare_prefix(void) {
200 into the first address byte, so the peers are distinct but arrive in no 200 into the first address byte, so the peers are distinct but arrive in no
201 particular order: a list generated in ascending order would come back 201 particular order: a list generated in ascending order would come back
202 sorted whether or not vector_redistribute_buckets sorted it. */ 202 sorted whether or not vector_redistribute_buckets sorted it. */
203static void build_flat_peerlist(ot_peerlist *peer_list, size_t count) { 203static void build_flat_vector(ot_vector *peers, size_t count) {
204 size_t i; 204 size_t i;
205 205
206 memset(peer_list, 0, sizeof(*peer_list)); 206 memset(peers, 0, sizeof(*peers));
207 peer_list->peers.data = malloc(count * OT_PEER_SIZE4); 207 peers->data = malloc(count * OT_PEER_SIZE4);
208 peer_list->peers.size = count; 208 peers->size = count;
209 peer_list->peers.space = count; 209 peers->space = count;
210 peer_list->peer_count = count;
211 210
212 for (i = 0; i < count; ++i) { 211 for (i = 0; i < count; ++i) {
213 uint8_t *peer = (uint8_t *)peer_list->peers.data + i * OT_PEER_SIZE4; 212 uint8_t *peer = (uint8_t *)peers->data + i * OT_PEER_SIZE4;
214 213
215 memset(peer, 0, OT_PEER_SIZE4); 214 memset(peer, 0, OT_PEER_SIZE4);
216 peer[0] = (uint8_t)i; 215 peer[0] = (uint8_t)i;
@@ -222,19 +221,19 @@ static void build_flat_peerlist(ot_peerlist *peer_list, size_t count) {
222 221
223static void case_redistribute_holds_every_peer(void) { 222static void case_redistribute_holds_every_peer(void) {
224 const size_t count = 513; 223 const size_t count = 513;
225 ot_peerlist peer_list; 224 ot_vector peers;
226 size_t bucket, total_size = 0, empty = 0, largest = 0; 225 size_t bucket, total_size = 0, empty = 0, largest = 0;
227 ot_vector *buckets; 226 ot_vector *buckets;
228 227
229 test_case("a peer list past the threshold is split into buckets"); 228 test_case("a peer list past the threshold is split into buckets");
230 build_flat_peerlist(&peer_list, count); 229 build_flat_vector(&peers, count);
231 CHECK(peer_list.peers.data != NULL); 230 CHECK(peers.data != NULL);
232 vector_redistribute_buckets(&peer_list, OT_PEER_SIZE4); 231 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
233 CHECK_INT(OT_PEERLIST_HASBUCKETS(&peer_list), 1); 232 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
234 CHECK_INT(peer_list.peers.size, 16); 233 CHECK_INT(peers.size, 16);
235 234
236 buckets = peer_list.peers.data; 235 buckets = peers.data;
237 for (bucket = 0; bucket < peer_list.peers.size; ++bucket) { 236 for (bucket = 0; bucket < peers.size; ++bucket) {
238 total_size += buckets[bucket].size; 237 total_size += buckets[bucket].size;
239 if (!buckets[bucket].size) 238 if (!buckets[bucket].size)
240 ++empty; 239 ++empty;
@@ -252,23 +251,23 @@ static void case_redistribute_holds_every_peer(void) {
252 CHECK_INT(empty, 0); 251 CHECK_INT(empty, 0);
253 CHECK(largest < count / 2); 252 CHECK(largest < count / 2);
254 253
255 vector_clean_list(peer_list.peers.data, peer_list.peers.size); 254 vector_clean_list(peers.data, peers.size);
256} 255}
257 256
258static void case_redistribute_sorts_each_bucket(void) { 257static void case_redistribute_sorts_each_bucket(void) {
259 const size_t count = 1000; 258 const size_t count = 1000;
260 ot_peerlist peer_list; 259 ot_vector peers;
261 size_t bucket, i, out_of_order = 0; 260 size_t bucket, i, out_of_order = 0;
262 ot_vector *buckets; 261 ot_vector *buckets;
263 262
264 test_case("every bucket comes back sorted, so bsearch can be used on it"); 263 test_case("every bucket comes back sorted, so bsearch can be used on it");
265 build_flat_peerlist(&peer_list, count); 264 build_flat_vector(&peers, count);
266 CHECK(peer_list.peers.data != NULL); 265 CHECK(peers.data != NULL);
267 vector_redistribute_buckets(&peer_list, OT_PEER_SIZE4); 266 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
268 CHECK_INT(OT_PEERLIST_HASBUCKETS(&peer_list), 1); 267 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
269 268
270 buckets = peer_list.peers.data; 269 buckets = peers.data;
271 for (bucket = 0; bucket < peer_list.peers.size; ++bucket) 270 for (bucket = 0; bucket < peers.size; ++bucket)
272 for (i = 1; i < buckets[bucket].size; ++i) { 271 for (i = 1; i < buckets[bucket].size; ++i) {
273 const uint8_t *prev = (uint8_t *)buckets[bucket].data + (i - 1) * OT_PEER_SIZE4; 272 const uint8_t *prev = (uint8_t *)buckets[bucket].data + (i - 1) * OT_PEER_SIZE4;
274 const uint8_t *next = (uint8_t *)buckets[bucket].data + i * OT_PEER_SIZE4; 273 const uint8_t *next = (uint8_t *)buckets[bucket].data + i * OT_PEER_SIZE4;
@@ -278,19 +277,19 @@ static void case_redistribute_sorts_each_bucket(void) {
278 } 277 }
279 CHECK_INT(out_of_order, 0); 278 CHECK_INT(out_of_order, 0);
280 279
281 vector_clean_list(peer_list.peers.data, peer_list.peers.size); 280 vector_clean_list(peers.data, peers.size);
282} 281}
283 282
284static void case_redistribute_below_threshold(void) { 283static void case_redistribute_below_threshold(void) {
285 ot_peerlist peer_list; 284 ot_vector peers;
286 285
287 test_case("a small peer list is left flat"); 286 test_case("a small peer list is left flat");
288 build_flat_peerlist(&peer_list, 100); 287 build_flat_vector(&peers, 100);
289 CHECK(peer_list.peers.data != NULL); 288 CHECK(peers.data != NULL);
290 vector_redistribute_buckets(&peer_list, OT_PEER_SIZE4); 289 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, 100);
291 CHECK_INT(OT_PEERLIST_HASBUCKETS(&peer_list), 0); 290 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 0);
292 CHECK_INT(peer_list.peers.size, 100); 291 CHECK_INT(peers.size, 100);
293 free(peer_list.peers.data); 292 free(peers.data);
294} 293}
295 294
296void test_vector(void) { 295void test_vector(void) {
diff --git a/tests/t_workqueue.c b/tests/t_workqueue.c
index c454e5b..660d882 100644
--- a/tests/t_workqueue.c
+++ b/tests/t_workqueue.c
@@ -6,6 +6,7 @@
6#include <string.h> 6#include <string.h>
7 7
8/* Opentracker */ 8/* Opentracker */
9#include "ot_fdstate.h"
9#include "ot_workqueue.h" 10#include "ot_workqueue.h"
10#include "test.h" 11#include "test.h"
11 12
@@ -96,10 +97,61 @@ static void case_cancelled_task_is_not_handed_out(void) {
96 workqueue_canceltask(48); 97 workqueue_canceltask(48);
97} 98}
98 99
100/* Tasks are filed under a descriptor number, and the number is handed to the
101 next connection the moment this one closes. */
102
103static void case_cancel_takes_every_task_of_the_socket(void) {
104 ot_tasktype asked;
105
106 test_case("cancelling a socket leaves none of its tasks behind");
107 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_ASCII), 0);
108 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_BINARY), 0);
109 CHECK_INT(workqueue_pushtask(50, TASK_FULLSCRAPE), 0);
110 workqueue_canceltask(49);
111
112 asked = TASK_FULLSCRAPE;
113 CHECK(workqueue_poptask(&asked) != 0);
114 CHECK_INT(asked, TASK_FULLSCRAPE);
115 workqueue_canceltask(50);
116}
117
118static void case_result_names_the_connection_that_asked(void) {
119 ot_tasktype asked = TASK_STATS;
120 ot_taskid taskid;
121 struct iovec *iovector;
122 size_t iovec_entries;
123 int is_partial;
124 uint32_t asked_under, answered_under = ~0u;
125
126 CHECK_INT(fdstate_init(), 0);
127 asked_under = fdstate_open(51, NULL, 0);
128
129 test_case("a result comes back with the generation its task was pushed under");
130 CHECK_INT(workqueue_pushtask(51, TASK_STATS_PEERS), 0);
131 taskid = workqueue_poptask(&asked);
132 CHECK(taskid != 0);
133
134 /* The connection goes away without cancelling and the number is reused */
135 fdstate_close(51);
136 fdstate_open(51, NULL, 0);
137
138 CHECK_INT(workqueue_pushresult(taskid, 0, NULL), 0);
139 CHECK_INT(workqueue_popresult(&iovec_entries, &iovector, &is_partial, &answered_under), 51);
140 CHECK_INT(answered_under, asked_under);
141
142 test_case("which is no longer the one the descriptor carries");
143 CHECK(fdstate_generation(51) != answered_under);
144
145 fdstate_close(51);
146 fdstate_deinit();
147}
148
99void test_workqueue(void) { 149void test_workqueue(void) {
100 case_task_goes_to_its_own_class(); 150 case_task_goes_to_its_own_class();
101 case_flags_survive_the_queue(); 151 case_flags_survive_the_queue();
102 case_classes_do_not_cross(); 152 case_classes_do_not_cross();
103 case_every_task_gets_its_own_id(); 153 case_every_task_gets_its_own_id();
104 case_cancelled_task_is_not_handed_out(); 154 case_cancelled_task_is_not_handed_out();
155 case_cancel_takes_every_task_of_the_socket();
156 case_result_names_the_connection_that_asked();
105} 157}
diff --git a/tests/test.h b/tests/test.h
index 82ec178..9b569c7 100644
--- a/tests/test.h
+++ b/tests/test.h
@@ -86,6 +86,7 @@ void test_ip(void);
86void test_socket(void); 86void test_socket(void);
87void test_mutex(void); 87void test_mutex(void);
88void test_trackerlogic(void); 88void test_trackerlogic(void);
89void test_clean(void);
89void test_workqueue(void); 90void test_workqueue(void);
90void test_batch(void); 91void test_batch(void);
91void test_fdstate(void); 92void test_fdstate(void);