summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.clang-format246
-rw-r--r--.gitignore16
-rw-r--r--DEDICATION2
-rw-r--r--DESIGN292
-rw-r--r--Makefile122
-rw-r--r--Mk/gzip.mk4
-rw-r--r--Mk/proxy.mk25
-rw-r--r--Mk/release.mk28
-rw-r--r--Mk/tests.mk87
-rw-r--r--Mk/zstd.mk3
-rw-r--r--README12
-rw-r--r--README_v61
-rw-r--r--man1/opentracker.1134
-rw-r--r--man5/opentracker.conf.5166
-rw-r--r--opentracker.c670
-rw-r--r--opentracker.conf.sample131
-rw-r--r--opentracker.xcodeproj/project.pbxproj320
-rw-r--r--ot_accesslist.c313
-rw-r--r--ot_accesslist.h79
-rw-r--r--ot_clean.c139
-rw-r--r--ot_clean.h19
-rw-r--r--ot_fullscrape.c249
-rw-r--r--ot_fullscrape.h22
-rw-r--r--ot_http.c635
-rw-r--r--ot_http.h29
-rw-r--r--ot_iovec.c76
-rw-r--r--ot_iovec.h19
-rw-r--r--ot_livesync.c216
-rw-r--r--ot_mutex.c336
-rw-r--r--ot_mutex.h75
-rw-r--r--ot_stats.c773
-rw-r--r--ot_stats.h52
-rw-r--r--ot_sync.c166
-rw-r--r--ot_sync.h24
-rw-r--r--ot_udp.c215
-rw-r--r--ot_udp.h12
-rw-r--r--ot_vector.c266
-rw-r--r--ot_vector.h34
-rw-r--r--proxy.c844
-rw-r--r--scan_urlencoded_query.c143
-rw-r--r--src/opentracker.c473
-rw-r--r--src/ot_accesslist.c607
-rw-r--r--src/ot_accesslist.h78
-rw-r--r--src/ot_batch.c156
-rw-r--r--src/ot_batch.h46
-rw-r--r--src/ot_buf.c39
-rw-r--r--src/ot_buf.h25
-rw-r--r--src/ot_clean.c208
-rw-r--r--src/ot_clean.h28
-rw-r--r--src/ot_config.c612
-rw-r--r--src/ot_config.h33
-rw-r--r--src/ot_event.c356
-rw-r--r--src/ot_event.h47
-rw-r--r--src/ot_fdstate.c202
-rw-r--r--src/ot_fdstate.h62
-rw-r--r--src/ot_fmt.c40
-rw-r--r--src/ot_fmt.h19
-rw-r--r--src/ot_fullscrape.c467
-rw-r--r--src/ot_fullscrape.h23
-rw-r--r--src/ot_hex.c56
-rw-r--r--src/ot_hex.h27
-rw-r--r--src/ot_http.c831
-rw-r--r--src/ot_http.h53
-rw-r--r--src/ot_iovec.c87
-rw-r--r--src/ot_iovec.h18
-rw-r--r--src/ot_ip.c199
-rw-r--r--src/ot_ip.h31
-rw-r--r--src/ot_livesync.c271
-rw-r--r--src/ot_livesync.h (renamed from ot_livesync.h)32
-rw-r--r--src/ot_mutex.c70
-rw-r--r--src/ot_mutex.h21
-rw-r--r--src/ot_random.c51
-rw-r--r--src/ot_random.h17
-rw-r--r--src/ot_rijndael.c (renamed from ot_rijndael.c)2
-rw-r--r--src/ot_rijndael.h (renamed from ot_rijndael.h)4
-rw-r--r--src/ot_scan.c65
-rw-r--r--src/ot_scan.h25
-rw-r--r--src/ot_socket.c318
-rw-r--r--src/ot_socket.h58
-rw-r--r--src/ot_stats.c826
-rw-r--r--src/ot_stats.h40
-rw-r--r--src/ot_tcp.c202
-rw-r--r--src/ot_tcp.h24
-rw-r--r--src/ot_udp.c272
-rw-r--r--src/ot_udp.h17
-rw-r--r--src/ot_urlencoded.c172
-rw-r--r--src/ot_urlencoded.h (renamed from scan_urlencoded_query.h)26
-rw-r--r--src/ot_vector.c292
-rw-r--r--src/ot_vector.h39
-rw-r--r--src/ot_worker.c73
-rw-r--r--src/ot_worker.h37
-rw-r--r--src/ot_workqueue.c248
-rw-r--r--src/ot_workqueue.h73
-rw-r--r--src/proxy.c871
-rw-r--r--src/trackerlogic.c643
-rw-r--r--src/trackerlogic.h343
-rw-r--r--tests/accept_filter_probe.py110
-rw-r--r--tests/http_load.c148
-rw-r--r--tests/integration/.gitignore2
-rw-r--r--tests/integration/harness.py366
-rw-r--r--tests/integration/test_accesslist.py128
-rw-r--r--tests/integration/test_announce.py144
-rw-r--r--tests/integration/test_concurrency.py209
-rw-r--r--tests/integration/test_config.py72
-rw-r--r--tests/integration/test_dualstack.py89
-rw-r--r--tests/integration/test_dynamic_accesslist.py68
-rw-r--r--tests/integration/test_expiry.py44
-rw-r--r--tests/integration/test_fullscrape.py148
-rw-r--r--tests/integration/test_keepalive.py146
-rw-r--r--tests/integration/test_livesync.py240
-rw-r--r--tests/integration/test_shutdown.py58
-rw-r--r--tests/integration/test_statefile.py97
-rw-r--r--tests/integration/test_stats.py146
-rw-r--r--tests/integration/test_tcpworkers.py67
-rw-r--r--tests/integration/test_udp.py218
-rw-r--r--tests/integration/test_version.py36
-rw-r--r--tests/runner.c115
-rw-r--r--tests/stubs.c48
-rw-r--r--tests/sync_daemon.pl (renamed from sync_daemon.pl)0
-rw-r--r--tests/syscount.c144
-rw-r--r--tests/t_accesslist.c120
-rw-r--r--tests/t_batch.c346
-rw-r--r--tests/t_buf.c203
-rw-r--r--tests/t_clean.c222
-rw-r--r--tests/t_event.c289
-rw-r--r--tests/t_fdstate.c230
-rw-r--r--tests/t_fmt.c106
-rw-r--r--tests/t_hex.c126
-rw-r--r--tests/t_iovec.c122
-rw-r--r--tests/t_ip.c215
-rw-r--r--tests/t_mutex.c136
-rw-r--r--tests/t_random.c112
-rw-r--r--tests/t_scan.c210
-rw-r--r--tests/t_socket.c416
-rw-r--r--tests/t_trackerlogic.c241
-rw-r--r--tests/t_urlencoded.c363
-rw-r--r--tests/t_vector.c308
-rw-r--r--tests/t_workqueue.c157
-rw-r--r--tests/test.c56
-rw-r--r--tests/test.h96
-rw-r--r--tests/testsuite2.sh22
-rw-r--r--tests/udp_load.c202
-rw-r--r--tests/udp_modes.c240
-rw-r--r--tests/udp_modes.py139
-rw-r--r--tests/udp_scaling.py159
-rw-r--r--tests/udp_wake_probe.c121
-rw-r--r--trackerlogic.c457
-rw-r--r--trackerlogic.h172
148 files changed, 18896 insertions, 6483 deletions
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..cf3c715
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,246 @@
1---
2Language: Cpp
3# BasedOnStyle: LLVM
4AccessModifierOffset: -2
5AlignAfterOpenBracket: Align
6AlignArrayOfStructures: None
7AlignConsecutiveAssignments:
8 Enabled: true
9 AcrossEmptyLines: true
10 AcrossComments: true
11 AlignCompound: true
12 AlignFunctionPointers: false
13 PadOperators: true
14AlignConsecutiveBitFields:
15 Enabled: false
16 AcrossEmptyLines: true
17 AcrossComments: true
18 AlignCompound: false
19 AlignFunctionPointers: false
20 PadOperators: false
21AlignConsecutiveDeclarations:
22 Enabled: true
23 AcrossEmptyLines: true
24 AcrossComments: true
25 AlignCompound: true
26 AlignFunctionPointers: false
27 PadOperators: true
28AlignConsecutiveMacros:
29 Enabled: true
30 AcrossEmptyLines: true
31 AcrossComments: true
32 AlignCompound: true
33 AlignFunctionPointers: false
34 PadOperators: false
35AlignConsecutiveShortCaseStatements:
36 Enabled: true
37 AcrossEmptyLines: true
38 AcrossComments: true
39 AlignCaseColons: false
40AlignEscapedNewlines: Right
41AlignOperands: Align
42AlignTrailingComments:
43 Kind: Always
44 OverEmptyLines: 0
45AllowAllArgumentsOnNextLine: true
46AllowAllParametersOfDeclarationOnNextLine: true
47AllowBreakBeforeNoexceptSpecifier: Never
48AllowShortBlocksOnASingleLine: Never
49AllowShortCaseLabelsOnASingleLine: false
50AllowShortCompoundRequirementOnASingleLine: true
51AllowShortEnumsOnASingleLine: true
52AllowShortFunctionsOnASingleLine: All
53AllowShortIfStatementsOnASingleLine: Never
54AllowShortLambdasOnASingleLine: All
55AllowShortLoopsOnASingleLine: false
56AlwaysBreakAfterDefinitionReturnType: None
57AlwaysBreakAfterReturnType: None
58AlwaysBreakBeforeMultilineStrings: false
59AlwaysBreakTemplateDeclarations: MultiLine
60AttributeMacros:
61 - __capability
62BinPackArguments: true
63BinPackParameters: true
64BitFieldColonSpacing: Both
65BraceWrapping:
66 AfterCaseLabel: false
67 AfterClass: false
68 AfterControlStatement: Never
69 AfterEnum: false
70 AfterExternBlock: false
71 AfterFunction: false
72 AfterNamespace: false
73 AfterObjCDeclaration: false
74 AfterStruct: false
75 AfterUnion: false
76 BeforeCatch: false
77 BeforeElse: false
78 BeforeLambdaBody: false
79 BeforeWhile: false
80 IndentBraces: false
81 SplitEmptyFunction: true
82 SplitEmptyRecord: true
83 SplitEmptyNamespace: true
84BreakAdjacentStringLiterals: true
85BreakAfterAttributes: Leave
86BreakAfterJavaFieldAnnotations: false
87BreakArrays: true
88BreakBeforeBinaryOperators: None
89BreakBeforeConceptDeclarations: Always
90BreakBeforeBraces: Attach
91BreakBeforeInlineASMColon: OnlyMultiline
92BreakBeforeTernaryOperators: true
93BreakConstructorInitializers: BeforeColon
94BreakInheritanceList: BeforeColon
95BreakStringLiterals: false
96ColumnLimit: 160
97CommentPragmas: '^ IWYU pragma:'
98CompactNamespaces: false
99ConstructorInitializerIndentWidth: 4
100ContinuationIndentWidth: 4
101Cpp11BracedListStyle: true
102DerivePointerAlignment: false
103DisableFormat: false
104EmptyLineAfterAccessModifier: Never
105EmptyLineBeforeAccessModifier: LogicalBlock
106ExperimentalAutoDetectBinPacking: false
107FixNamespaceComments: true
108ForEachMacros:
109 - foreach
110 - Q_FOREACH
111 - BOOST_FOREACH
112IfMacros:
113 - KJ_IF_MAYBE
114IncludeBlocks: Preserve
115IncludeCategories:
116 - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
117 Priority: 2
118 SortPriority: 0
119 CaseSensitive: false
120 - Regex: '^(<|"(gtest|gmock|isl|json)/)'
121 Priority: 3
122 SortPriority: 0
123 CaseSensitive: false
124 - Regex: '.*'
125 Priority: 1
126 SortPriority: 0
127 CaseSensitive: false
128IncludeIsMainRegex: '(Test)?$'
129IncludeIsMainSourceRegex: ''
130IndentAccessModifiers: false
131IndentCaseBlocks: false
132IndentCaseLabels: false
133IndentExternBlock: AfterExternBlock
134IndentGotoLabels: true
135IndentPPDirectives: None
136IndentRequiresClause: true
137IndentWidth: 2
138IndentWrappedFunctionNames: false
139InsertBraces: false
140InsertNewlineAtEOF: false
141InsertTrailingCommas: None
142IntegerLiteralSeparator:
143 Binary: 0
144 BinaryMinDigits: 0
145 Decimal: 0
146 DecimalMinDigits: 0
147 Hex: 0
148 HexMinDigits: 0
149JavaScriptQuotes: Leave
150JavaScriptWrapImports: true
151KeepEmptyLinesAtTheStartOfBlocks: true
152KeepEmptyLinesAtEOF: false
153LambdaBodyIndentation: Signature
154LineEnding: DeriveLF
155MacroBlockBegin: ''
156MacroBlockEnd: ''
157MaxEmptyLinesToKeep: 1
158NamespaceIndentation: None
159ObjCBinPackProtocolList: Auto
160ObjCBlockIndentWidth: 2
161ObjCBreakBeforeNestedBlockParam: true
162ObjCSpaceAfterProperty: false
163ObjCSpaceBeforeProtocolList: true
164PackConstructorInitializers: BinPack
165PenaltyBreakAssignment: 2
166PenaltyBreakBeforeFirstCallParameter: 19
167PenaltyBreakComment: 300
168PenaltyBreakFirstLessLess: 120
169PenaltyBreakOpenParenthesis: 0
170PenaltyBreakScopeResolution: 500
171PenaltyBreakString: 1000
172PenaltyBreakTemplateDeclaration: 10
173PenaltyExcessCharacter: 1000000
174PenaltyIndentedWhitespace: 0
175PenaltyReturnTypeOnItsOwnLine: 60
176PointerAlignment: Right
177PPIndentWidth: -1
178QualifierAlignment: Leave
179ReferenceAlignment: Pointer
180ReflowComments: true
181RemoveBracesLLVM: false
182RemoveParentheses: Leave
183RemoveSemicolon: false
184RequiresClausePosition: OwnLine
185RequiresExpressionIndentation: OuterScope
186SeparateDefinitionBlocks: Leave
187ShortNamespaceLines: 1
188SkipMacroDefinitionBody: false
189SortIncludes: CaseSensitive
190SortJavaStaticImport: Before
191SortUsingDeclarations: LexicographicNumeric
192SpaceAfterCStyleCast: false
193SpaceAfterLogicalNot: false
194SpaceAfterTemplateKeyword: true
195SpaceAroundPointerQualifiers: Default
196SpaceBeforeAssignmentOperators: true
197SpaceBeforeCaseColon: false
198SpaceBeforeCpp11BracedList: false
199SpaceBeforeCtorInitializerColon: true
200SpaceBeforeInheritanceColon: true
201SpaceBeforeJsonColon: false
202SpaceBeforeParens: ControlStatements
203SpaceBeforeParensOptions:
204 AfterControlStatements: true
205 AfterForeachMacros: true
206 AfterFunctionDefinitionName: false
207 AfterFunctionDeclarationName: false
208 AfterIfMacros: true
209 AfterOverloadedOperator: false
210 AfterPlacementOperator: true
211 AfterRequiresInClause: false
212 AfterRequiresInExpression: false
213 BeforeNonEmptyParentheses: false
214SpaceBeforeRangeBasedForLoopColon: true
215SpaceBeforeSquareBrackets: false
216SpaceInEmptyBlock: false
217SpacesBeforeTrailingComments: 1
218SpacesInAngles: Never
219SpacesInContainerLiterals: true
220SpacesInLineCommentPrefix:
221 Minimum: 1
222 Maximum: -1
223SpacesInParens: Never
224SpacesInParensOptions:
225 InCStyleCasts: false
226 InConditionalStatements: false
227 InEmptyParentheses: false
228 Other: false
229SpacesInSquareBrackets: false
230Standard: Latest
231StatementAttributeLikeMacros:
232 - Q_EMIT
233StatementMacros:
234 - Q_UNUSED
235 - QT_REQUIRE_VERSION
236TabWidth: 8
237UseTab: Never
238VerilogBreakBetweenInstancePorts: true
239WhitespaceSensitiveMacros:
240 - BOOST_PP_STRINGIZE
241 - CF_SWIFT_NAME
242 - NS_SWIFT_NAME
243 - PP_STRINGIZE
244 - STRINGIZE
245...
246
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b4ad7cd
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
1*.dSYM
2*.o
3opentracker
4opentracker.debug
5opentracker.integration
6opentracker.tsan
7opentracker.livesync
8proxy
9proxy.debug
10tests/runner
11tests/runner.poll
12tests/runner.sanitize
13.buildstamp
14.tarball-version
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
new file mode 100644
index 0000000..7933223
--- /dev/null
+++ b/DESIGN
@@ -0,0 +1,292 @@
1opentracker design notes
2========================
3
4Decisions that cost measurement to reach, and the alternatives that were
5tried and rejected.
6
7What the tracker is optimised for
8---------------------------------
9
10UDP carries most of the traffic. An HTTP request costs about ten times a UDP
11announce, 26 microseconds of tracker CPU against 2.5. Nearly all of that is
12the kernel setting up and tearing down a connection rather than tracker
13code.
14
15A connection carries one request and closes. Keep-alive works and is rarely
16asked for.
17
18Statistics are approximate on purpose. Counters are per thread and summed
19when read, so a /stats read can under-report once.
20
21
22Decisions
23---------
24
25One UDP socket per worker, where the kernel spreads datagrams over a group
26bound to one address. Cost per datagram then stays flat as workers are added,
270.71 to 0.72 microseconds from one worker to eight. Sharing one socket grows
28it eightfold over the same range, 0.71 to 6.07.
29
30listen.udp.workers defaults to 1. One worker beats none by 19 to 37 per cent
31everywhere, because a blocking read costs one system call where the event
32loop costs two. Beyond one the gain depends on the kernel balancing, so
33raising it is the operator's decision.
34
35A thread parked in a blocking read is woken by a signal, not by closing or
36shutting down its socket:
37
38 mechanism Linux FreeBSD macOS
39 close() blocked blocked 0 ms
40 shutdown(SHUT_RD) 1 ms 1 ms blocked
41 SO_RCVTIMEO works works works
42 pthread_kill 1 ms 1 ms 1 ms
43
44Only the signal works everywhere. A receive timeout also works, but wakes
45every 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
47495 over thirty seconds.
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
52Each binary is built in one compiler invocation. Without object files a build
53cannot link objects compiled with different FEATURES, which was a real
54failure mode. It costs incremental rebuilds, 0.075 seconds becoming 1.56.
55
56A socket is read or written, never both. http_interest_set replaces an
57add-and-drop pair so that the invariant cannot be broken by accident, and the
58event layer hears about a change once instead of twice.
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
67Accept waits until the client's request has arrived: TCP_DEFER_ACCEPT on
68Linux, the accf_data filter on FreeBSD. Measured against a flood of silent
69connections, the filter serves more requests than no filter, not fewer, so it
70is not the denial of service vector that FreeBSD-SA-02:26 once described.
71
72
73The torrent table is split into 2^OT_BUCKET_COUNT_BITS buckets, 1024 by
74default, set from the Makefile. Inserting a torrent opens a slot in a sorted
75vector, so the bytes moved grow with the bucket's occupancy. Insert cost per
76torrent, Linux:
77
78 2^10 2^12 2^14 2^16
79 200k 466 ns 439 ns
80 1M 834 ns 579 ns 529 ns
81 4M 2348 ns 1163 ns 770 ns 674 ns
82
83Re-announcing an existing torrent moves by under ten per cent over the same
84range, so the cost is paid while the torrent population is built and not in
85steady state. Below a few hundred thousand torrents there is nothing to win.
862^14 captures most of the gain for two per cent more resident memory.
87
88The cleaner's wake rate does not follow the bucket count. A cap of ten wakes
89a second sets the sleep, and a wake cleans as many buckets as it must to
90finish a sweep in OT_CLEAN_INTERVAL_MINUTES. At the default bucket count that
91is one bucket every 117 ms.
92
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
238Paths not taken
239---------------
240
241A keyed hash for the bucket index. Info hashes are SHA-1 output and already
242uniform, so it changes no distribution. It would buy resistance to deliberate
243bucket flooding and cost the ordering a full scrape depends on: buckets are
244ordered by hash prefix and sorted within, so walking them emits the sorted
245dictionary bencode wants, with no sort and no copy.
246
247Cache line padding for the per-bucket locks and vector headers. The
248contention it was meant to remove is not there. On glibc, where a 48-byte
249mutex straddles a line, padding gains 3 to 8 per cent, but gains as much at
250one thread where no false sharing can exist, and scaling from one to eight
251threads is identical either way. On FreeBSD, where eight 8-byte mutexes share
252a line and the risk should be highest, padding is 15 per cent slower at one
253thread and neutral to 6 per cent slower at four and eight.
254
255accf_http, the HTTP-aware accept filter. It duplicates a parser the tracker
256has anyway, puts more kernel code in the path, and holds a connection that
257sends "GET /" and stops, which accf_data hands straight over.
258
259recvmmsg and sendmmsg. No measurable gain on either FreeBSD machine, between
260-4 and +10 per cent, and they do not exist on Darwin.
261
262Link time optimisation. It cuts .text by 13 per cent, 93,497 bytes to 81,630,
263and changes throughput not at all. A tracker waits on memory and system
264calls, not on instruction fetch: the announce path is 6.6 KB of code against
265a 32 KB instruction cache at worst.
266
267A directory for object files. bmake has no pattern rules and the Makefile
268builds under FreeBSD's make today. Building each binary in one invocation
269clears the objects out of the tree without giving that up.
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
277
278
279Platform differences that cost us code
280--------------------------------------
281
282SO_REUSEPORT means three different things. Linux spreads datagrams over the
283group. FreeBSD permits the bind and needs SO_REUSEPORT_LB to spread. Darwin
284hands every datagram to whichever socket bound last, so a group there starves
285all but one reader.
286
287Waking a blocked reader differs per kernel. see the table above.
288
289Deferring accept is TCP_DEFER_ACCEPT, or accf_data, or nothing.
290
291make is bmake on FreeBSD and GNU make elsewhere, and the Makefile has to
292build under both.
diff --git a/Makefile b/Makefile
index da2c8f1..15828bb 100644
--- a/Makefile
+++ b/Makefile
@@ -1,37 +1,20 @@
1# $Id$ 1PREFIX?=/usr/local
2
3CC?=gcc
4
5# Linux flavour
6# PREFIX?=/opt/diet
7# LIBOWFAT_HEADERS=$(PREFIX)/include
8# LIBOWFAT_LIBRARY=$(PREFIX)/lib
9
10# BSD flavour
11# PREFIX?=/usr/local
12# LIBOWFAT_HEADERS=$(PREFIX)/include/libowfat
13# LIBOWFAT_LIBRARY=$(PREFIX)/lib
14
15# Debug flavour
16PREFIX?=..
17LIBOWFAT_HEADERS=$(PREFIX)/libowfat
18LIBOWFAT_LIBRARY=$(PREFIX)/libowfat
19
20BINDIR?=$(PREFIX)/bin 2BINDIR?=$(PREFIX)/bin
3MANDIR?=$(PREFIX)/share/man
4STRIP?=strip
21 5
22#FEATURES+=-DWANT_V6 6#FEATURES+=-DWANT_V4_ONLY
23
24#FEATURES+=-DWANT_ACCESSLIST_BLACK 7#FEATURES+=-DWANT_ACCESSLIST_BLACK
25#FEATURES+=-DWANT_ACCESSLIST_WHITE 8#FEATURES+=-DWANT_ACCESSLIST_WHITE
9#FEATURES+=-DWANT_DYNAMIC_ACCESSLIST
26 10
27#FEATURES+=-DWANT_SYNC_LIVE 11#FEATURES+=-DWANT_SYNC_LIVE
28#FEATURES+=-DWANT_IP_FROM_QUERY_STRING 12#FEATURES+=-DWANT_IP_FROM_QUERY_STRING
29#FEATURES+=-DWANT_COMPRESSION_GZIP 13#FEATURES+=-DWANT_KEEPALIVE
30#FEATURES+=-DWANT_COMPRESSION_GZIP_ALWAYS 14
31#FEATURES+=-DWANT_LOG_NETWORKS
32#FEATURES+=-DWANT_RESTRICT_STATS 15#FEATURES+=-DWANT_RESTRICT_STATS
16#FEATURES+=-DWANT_RESTRICT_FULLSCRAPE
33#FEATURES+=-DWANT_IP_FROM_PROXY 17#FEATURES+=-DWANT_IP_FROM_PROXY
34#FEATURES+=-DWANT_FULLLOG_NETWORKS
35#FEATURES+=-DWANT_LOG_NUMWANT 18#FEATURES+=-DWANT_LOG_NUMWANT
36#FEATURES+=-DWANT_MODEST_FULLSCRAPES 19#FEATURES+=-DWANT_MODEST_FULLSCRAPES
37#FEATURES+=-DWANT_SPOT_WOODPECKER 20#FEATURES+=-DWANT_SPOT_WOODPECKER
@@ -39,49 +22,74 @@ BINDIR?=$(PREFIX)/bin
39#FEATURES+=-DWANT_DEV_RANDOM 22#FEATURES+=-DWANT_DEV_RANDOM
40FEATURES+=-DWANT_FULLSCRAPE 23FEATURES+=-DWANT_FULLSCRAPE
41 24
25# Buckets the torrent table is split into, as a power of two, 8 to 16. More
26# buckets make inserting a new torrent cheaper and cost memory, which is worth
27# it for a tracker carrying millions of torrents and not for one carrying
28# thousands. DESIGN has the measurements.
29FEATURES+=-DOT_BUCKET_COUNT_BITS=10
30
42#FEATURES+=-D_DEBUG_HTTPERROR 31#FEATURES+=-D_DEBUG_HTTPERROR
32#FEATURES+=-D_DEBUG_RANDOMTORRENTS
43 33
44OPTS_debug=-D_DEBUG -g -ggdb # -pg -fprofile-arcs -ftest-coverage 34# Compression support, off unless included. Each file carries a second switch
45OPTS_production=-O3 35# to compress even where the client did not ask.
36include Mk/gzip.mk
37#include Mk/zstd.mk
46 38
47CFLAGS+=-I$(LIBOWFAT_HEADERS) -Wall -pipe -Wextra #-ansi -pedantic 39# arc4random is part of libc on the BSDs, on macOS and on glibc 2.36 and
48LDFLAGS+=-L$(LIBOWFAT_LIBRARY) -lowfat -pthread -lpthread -lz 40# newer. On an older glibc or on musl it comes from libbsd instead.
41#OT_LDLIBS+=-lbsd
49 42
50BINARY =opentracker 43CFLAGS?=-O3
51HEADERS=trackerlogic.h scan_urlencoded_query.h ot_mutex.h ot_stats.h ot_vector.h ot_clean.h ot_udp.h ot_iovec.h ot_fullscrape.h ot_accesslist.h ot_http.h ot_livesync.h ot_rijndael.h
52SOURCES=opentracker.c trackerlogic.c scan_urlencoded_query.c ot_mutex.c ot_stats.c ot_vector.c ot_clean.c ot_udp.c ot_iovec.c ot_fullscrape.c ot_accesslist.c ot_http.c ot_livesync.c ot_rijndael.c
53SOURCES_proxy=proxy.c ot_vector.c ot_mutex.c
54 44
55OBJECTS = $(SOURCES:%.c=%.o) 45OT_CFLAGS+=-Wall -Wextra -Wwrite-strings -pipe -pthread
56OBJECTS_debug = $(SOURCES:%.c=%.debug.o)
57OBJECTS_proxy = $(SOURCES_proxy:%.c=%.o)
58OBJECTS_proxy_debug = $(SOURCES_proxy:%.c=%.debug.o)
59 46
60.SUFFIXES: .debug.o .o .c 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
49OT_LDFLAGS+=-pthread
61 50
62all: $(BINARY) $(BINARY).debug 51OPTS_debug=-D_DEBUG -g -ggdb
52
53COMPILE=$(CPPFLAGS) $(OT_CFLAGS) $(FEATURES)
54LINK=$(LDFLAGS) $(OT_LDFLAGS) $(LDLIBS) $(OT_LDLIBS)
55
56BINARY=opentracker
57HEADERS=src/trackerlogic.h src/ot_urlencoded.h src/ot_batch.h src/ot_buf.h src/ot_event.h src/ot_fdstate.h src/ot_fmt.h src/ot_hex.h src/ot_ip.h src/ot_config.h src/ot_scan.h src/ot_socket.h src/ot_tcp.h src/ot_worker.h src/ot_workqueue.h src/ot_mutex.h src/ot_random.h src/ot_stats.h src/ot_vector.h src/ot_clean.h src/ot_udp.h src/ot_iovec.h src/ot_fullscrape.h src/ot_accesslist.h src/ot_http.h src/ot_livesync.h src/ot_rijndael.h
58SOURCES=src/opentracker.c src/trackerlogic.c src/ot_urlencoded.c src/ot_batch.c src/ot_buf.c src/ot_event.c src/ot_fdstate.c src/ot_fmt.c src/ot_hex.c src/ot_ip.c src/ot_config.c src/ot_scan.c src/ot_socket.c src/ot_tcp.c src/ot_worker.c src/ot_workqueue.c src/ot_mutex.c src/ot_random.c src/ot_stats.c src/ot_vector.c src/ot_clean.c src/ot_udp.c src/ot_iovec.c src/ot_fullscrape.c src/ot_accesslist.c src/ot_http.c src/ot_livesync.c src/ot_rijndael.c
59BINARIES=$(BINARY) $(BINARY).debug
60
61# Everything is built in one go from sources, so there are no object files to
62# carry a flag change over into the next build. The stamp holds the flags the
63# last build used, which covers FEATURES passed in the environment and a moved
64# HEAD. It is only written when they differ.
65BUILDSTAMP=.buildstamp
66BUILDDEPS=Makefile $(BUILDSTAMP)
63 67
64CFLAGS_production = $(CFLAGS) $(OPTS_production) $(FEATURES) 68all: $(BINARY) $(BINARY).debug
65CFLAGS_debug = $(CFLAGS) $(OPTS_debug) $(FEATURES)
66 69
67$(BINARY): $(OBJECTS) $(HEADERS) 70$(BINARY): $(SOURCES) $(HEADERS) $(BUILDDEPS)
68 $(CC) -o $@ $(OBJECTS) $(LDFLAGS) 71 $(CC) -o $@ $(CFLAGS) $(COMPILE) $(HARDENING) $(SOURCES) $(LINK) $(HARDENING_LD)
69 strip $@ 72 $(STRIP) $@
70$(BINARY).debug: $(OBJECTS_debug) $(HEADERS)
71 $(CC) -o $@ $(OBJECTS_debug) $(LDFLAGS)
72proxy: $(OBJECTS_proxy) $(HEADERS)
73 $(CC) -o $@ $(OBJECTS_proxy) $(CFLAGS_production) $(LDFLAGS)
74proxy.debug: $(OBJECTS_proxy_debug) $(HEADERS)
75 $(CC) -o $@ $(OBJECTS_proxy_debug) $(LDFLAGS)
76 73
77.c.debug.o : $(HEADERS) 74$(BINARY).debug: $(SOURCES) $(HEADERS) $(BUILDDEPS)
78 $(CC) -c -o $@ $(CFLAGS_debug) $(<:.debug.o=.c) 75 $(CC) -o $@ $(OPTS_debug) $(COMPILE) $(HARDENING) $(SOURCES) $(LINK) $(HARDENING_LD)
79 76
80.c.o : $(HEADERS) 77$(BUILDSTAMP): FORCE
81 $(CC) -c -o $@ $(CFLAGS_production) $< 78 @echo "$(CFLAGS) $(COMPILE) $(HARDENING) $(LINK) $(HARDENING_LD)" | cmp -s - $@ 2>/dev/null || echo "$(CFLAGS) $(COMPILE) $(HARDENING) $(LINK) $(HARDENING_LD)" > $@
82 79
83clean: 80clean:
84 rm -rf opentracker opentracker.debug *.o *~ 81 rm -rf $(BINARIES) $(BINARIES:=.dSYM) $(BUILDSTAMP) *.o *~ src/*.o src/*~
82
83install: $(BINARY)
84 install -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)/man1 $(DESTDIR)$(MANDIR)/man5
85 install -m 755 $(BINARY) $(DESTDIR)$(BINDIR)
86 install -m 644 man1/opentracker.1 $(DESTDIR)$(MANDIR)/man1
87 install -m 644 man5/opentracker.conf.5 $(DESTDIR)$(MANDIR)/man5
88
89FORCE:
90
91.PHONY: all clean install FORCE
85 92
86install: 93include Mk/tests.mk
87 install -m 755 opentracker $(BINDIR) 94include Mk/release.mk
95include Mk/proxy.mk
diff --git a/Mk/gzip.mk b/Mk/gzip.mk
new file mode 100644
index 0000000..3ae53b3
--- /dev/null
+++ b/Mk/gzip.mk
@@ -0,0 +1,4 @@
1FEATURES+=-DWANT_COMPRESSION_GZIP
2#FEATURES+=-DWANT_COMPRESSION_GZIP_ALWAYS
3
4OT_LDLIBS+=-lz
diff --git a/Mk/proxy.mk b/Mk/proxy.mk
new file mode 100644
index 0000000..64d18dc
--- /dev/null
+++ b/Mk/proxy.mk
@@ -0,0 +1,25 @@
1# The proxy relays sync traffic between trackers and between multicast domains
2# that cannot reach each other. It does not build; see the note at the top of
3# proxy.c. Scheduled for v1.1.0, when these rules come back.
4#
5# LIBOWFAT_HEADERS=$(PREFIX)/libowfat
6# LIBOWFAT_LIBRARY=$(PREFIX)/libowfat
7# CFLAGS_libowfat=-I$(LIBOWFAT_HEADERS)
8# LDFLAGS_libowfat=-L$(LIBOWFAT_LIBRARY) -lowfat
9#
10# SOURCES_proxy=src/proxy.c src/ot_batch.c src/ot_fdstate.c src/ot_vector.c src/ot_mutex.c src/ot_random.c src/ot_scan.c src/ot_ip.c src/ot_socket.c
11# CFLAGS_proxy=$(CFLAGS_production) $(CFLAGS_libowfat) -DWANT_SYNC_LIVE
12# CFLAGS_proxy_debug=$(CFLAGS_debug) $(CFLAGS_libowfat) -DWANT_SYNC_LIVE
13#
14# BINARIES+=proxy proxy.debug
15#
16# proxy: $(SOURCES_proxy) $(HEADERS) $(BUILDDEPS)
17# $(CC) -o $@ $(CFLAGS_proxy) $(SOURCES_proxy) $(LDFLAGS) $(LDFLAGS_libowfat)
18# proxy.debug: $(SOURCES_proxy) $(HEADERS) $(BUILDDEPS)
19# $(CC) -o $@ $(CFLAGS_proxy_debug) $(SOURCES_proxy) $(LDFLAGS) $(LDFLAGS_libowfat)
20
21proxy proxy.debug:
22 @echo "$@ is out of service until v1.1.0, see the note at the top of proxy.c"
23 @false
24
25.PHONY: proxy proxy.debug
diff --git a/Mk/release.mk b/Mk/release.mk
new file mode 100644
index 0000000..507a989
--- /dev/null
+++ b/Mk/release.mk
@@ -0,0 +1,28 @@
1# .tarball-version is what dist wrote into the tarball
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
4# is to it. Between releases there is no tag and the version is the commit.
5VERSION=2.2.1
6
7TARBALL_VERSION=test -r .tarball-version && read v < .tarball-version && echo "$$v"
8HAVE_GIT=command -v git >/dev/null && test -d .git
9GIT_VERSION=`sh -c '$(TARBALL_VERSION) || { $(HAVE_GIT) && git describe --tags --match "v*" --always --dirty 2>/dev/null; }'`
10OT_TAG=`sh -c '$(TARBALL_VERSION) || { $(HAVE_GIT) && git describe --tags --match "v*" --exact-match 2>/dev/null; }'`
11
12OT_CFLAGS+=-DOT_VERSION=\"$(VERSION)\" -DGIT_VERSION=\"$(GIT_VERSION)\" -DOT_TAG=\"$(OT_TAG)\"
13
14# Roll a release: tag it v$(VERSION), then make dist. The tarball is HEAD by
15# construction, so the working tree it was rolled from does not enter into it.
16DISTNAME=opentracker-$(VERSION)
17
18dist:
19 @test "`git describe --tags --match 'v*' --exact-match 2>/dev/null`" = "v$(VERSION)" || \
20 { echo "HEAD must carry the tag v$(VERSION). Tag the release, or correct VERSION."; exit 1; }
21 rm -rf $(DISTNAME) $(DISTNAME).tar.gz
22 git archive --format=tar --prefix=$(DISTNAME)/ HEAD | tar -xf -
23 git describe --tags --match "v*" --always > $(DISTNAME)/.tarball-version
24 tar -czf $(DISTNAME).tar.gz $(DISTNAME)
25 tar -cjf $(DISTNAME).tar.bz2 $(DISTNAME)
26 rm -rf $(DISTNAME)
27
28.PHONY: dist
diff --git a/Mk/tests.mk b/Mk/tests.mk
new file mode 100644
index 0000000..22ea69e
--- /dev/null
+++ b/Mk/tests.mk
@@ -0,0 +1,87 @@
1BUILDDEPS+=Mk/tests.mk
2
3# The modules under test are compiled straight into the test binary, so a test
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.
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_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/ot_clean.c src/trackerlogic.c
9TEST_HEADERS=tests/test.h $(HEADERS)
10
11# A test binary is not a production binary, so it is built with the features
12# the tests need to reach.
13FEATURES_test=$(FEATURES) -DWANT_ACCESSLIST_BLACK -DWANT_SYNC_LIVE
14CFLAGS_test=-Isrc -g -O1 $(CPPFLAGS) $(OT_CFLAGS) $(FEATURES_test)
15
16# clang over $(CC) because the two toolchains do not check the same things.
17CC_sanitize?=clang
18CFLAGS_sanitize=$(CFLAGS_test) -fsanitize=address,undefined -fno-omit-frame-pointer
19LDFLAGS_sanitize=$(LINK) -fsanitize=address,undefined
20
21# Black box tests drive the real binary over the wire, so they cover the event
22# loop and the parsers working together. The client timeout is cut right down
23# so a test can reach the expiry sweep; tests/integration/test_expiry.py
24# mirrors these two numbers.
25PYTHON?=python3
26FEATURES_integration=$(FEATURES) -DWANT_IP_FROM_QUERY_STRING -DWANT_ACCESSLIST_BLACK -DWANT_DYNAMIC_ACCESSLIST -DWANT_KEEPALIVE -DOT_CLIENT_TIMEOUT=5 -DOT_CLIENT_TIMEOUT_CHECKINTERVAL=1
27CFLAGS_integration=$(OPTS_debug) $(CPPFLAGS) $(OT_CFLAGS) $(FEATURES_integration) -fsanitize=address,undefined -fno-omit-frame-pointer
28LDFLAGS_integration=$(LINK) -fsanitize=address,undefined
29CFLAGS_tsan=$(OPTS_debug) $(CPPFLAGS) $(OT_CFLAGS) $(FEATURES_integration) -fsanitize=thread -fno-omit-frame-pointer
30LDFLAGS_tsan=$(LINK) -fsanitize=thread
31
32# Live sync is a compile time feature, so reaching it from a black box test
33# needs a binary of its own. tests/integration/test_livesync.py skips itself
34# against a build without it, which is what -v is for.
35FEATURES_livesync=$(FEATURES_integration) -DWANT_SYNC_LIVE
36CFLAGS_livesync=$(OPTS_debug) $(CPPFLAGS) $(OT_CFLAGS) $(FEATURES_livesync) -fsanitize=address,undefined -fno-omit-frame-pointer
37
38BINARIES+=$(TESTBIN) $(TESTBIN).poll $(TESTBIN).sanitize opentracker.integration opentracker.tsan opentracker.livesync
39
40$(TESTBIN): $(TEST_SOURCES) $(TEST_UNITS) $(TEST_HEADERS) $(BUILDDEPS)
41 $(CC) -o $@ $(CFLAGS_test) $(TEST_SOURCES) $(TEST_UNITS)
42
43$(TESTBIN).poll: $(TEST_SOURCES) $(TEST_UNITS) $(TEST_HEADERS) $(BUILDDEPS)
44 $(CC) -o $@ $(CFLAGS_test) -DOT_EVENT_FORCE_POLL $(TEST_SOURCES) $(TEST_UNITS)
45
46$(TESTBIN).sanitize: $(TEST_SOURCES) $(TEST_UNITS) $(TEST_HEADERS) $(BUILDDEPS)
47 $(CC_sanitize) -o $@ $(CFLAGS_sanitize) $(TEST_SOURCES) $(TEST_UNITS) $(LDFLAGS_sanitize)
48
49opentracker.integration: $(SOURCES) $(HEADERS) $(BUILDDEPS)
50 $(CC) -o $@ $(CFLAGS_integration) $(SOURCES) $(LDFLAGS_integration)
51
52opentracker.tsan: $(SOURCES) $(HEADERS) $(BUILDDEPS)
53 $(CC) -o $@ $(CFLAGS_tsan) $(SOURCES) $(LDFLAGS_tsan)
54
55opentracker.livesync: $(SOURCES) $(HEADERS) $(BUILDDEPS)
56 $(CC) -o $@ $(CFLAGS_livesync) $(SOURCES) $(LDFLAGS_integration)
57
58check: $(TESTBIN) $(BINARY)
59 ./$(TESTBIN)
60
61check-poll: $(TESTBIN).poll
62 ./$(TESTBIN).poll ot_event
63
64check-sanitize: $(TESTBIN).sanitize
65 ./$(TESTBIN).sanitize
66
67check-integration: opentracker.integration
68 OPENTRACKER=./opentracker.integration $(PYTHON) -m unittest discover -s tests/integration
69
70check-tsan: opentracker.tsan
71 OPENTRACKER=./opentracker.tsan $(PYTHON) -m unittest discover -s tests/integration
72
73# The whole suite against a build that has live sync, which is also the only
74# way the live sync tests stop skipping.
75check-livesync: opentracker.livesync
76 OPENTRACKER=./opentracker.livesync $(PYTHON) -m unittest discover -s tests/integration
77
78# Cheapest first, so a quick failure comes back quickly.
79check-all:
80 $(MAKE) check
81 $(MAKE) check-poll
82 $(MAKE) check-sanitize
83 $(MAKE) check-integration
84 $(MAKE) check-livesync
85 $(MAKE) check-tsan
86
87.PHONY: check check-poll check-sanitize check-integration check-livesync check-tsan check-all
diff --git a/Mk/zstd.mk b/Mk/zstd.mk
new file mode 100644
index 0000000..8c1fc40
--- /dev/null
+++ b/Mk/zstd.mk
@@ -0,0 +1,3 @@
1FEATURES+=-DWANT_COMPRESSION_ZSTD
2#FEATURES+=-DWANT_COMPRESSION_ZSTD_ALWAYS
3OT_LDLIBS+=-lzstd
diff --git a/README b/README
index bb8a06e..c84c4e9 100644
--- a/README
+++ b/README
@@ -1,14 +1,8 @@
1This is opentracker. An open bittorrent tracker. 1This is opentracker. An open bittorrent tracker.
2 2
3You need libowfat (http://www.fefe.de/libowfat/).
4
5Steps to go: 3Steps to go:
6 4
7cvs -d :pserver:cvs@cvs.fefe.de:/cvs -z9 co libowfat 5git clone git://erdgeist.org/opentracker
8cd libowfat
9make
10cd ..
11cvs -d:pserver:anoncvs@cvs.erdgeist.org:/home/cvsroot co opentracker
12cd opentracker 6cd opentracker
13make 7make
14./opentracker 8./opentracker
@@ -24,7 +18,3 @@ sysctl kern.ipc.somaxconn=1024
24sysctl kern.ipc.nmbclusters=32768 18sysctl kern.ipc.nmbclusters=32768
25sysctl net.inet.tcp.msl=10000 19sysctl net.inet.tcp.msl=10000
26sysctl kern.maxfiles=10240 20sysctl kern.maxfiles=10240
27
28License information:
29
30Although the libowfat library is under GPL, Felix von Leitner agreed that the compiled binary may be distributed under the same beer ware license as the source code for opentracker. However, we like to hear from happy customers.
diff --git a/README_v6 b/README_v6
deleted file mode 100644
index 7fac79a..0000000
--- a/README_v6
+++ /dev/null
@@ -1 +0,0 @@
1IPv6 is implemented in opentracker now. You can chose whether your tracker runs in v4 or v6 mode in Makefile. YMMV.
diff --git a/man1/opentracker.1 b/man1/opentracker.1
new file mode 100644
index 0000000..10f4afc
--- /dev/null
+++ b/man1/opentracker.1
@@ -0,0 +1,134 @@
1.Dd 2026-11-10
2.Dt opentracker 1
3.Os Unix
4.Sh NAME
5.Nm opentracker
6.Nd a free and open bittorrent tracker
7.Sh SYNOPSIS
8.Nm
9.Op Fl f Ar config
10.Op Fl i Ar ip-select
11.Op Fl p Ar port-bind-tcp
12.Op Fl P Ar port-bind-udp
13.Op Fl A Ar blessed-ip
14.Op Fl r Ar redirect-url
15.Op Fl d Ar chdir
16.Op Fl u Ar user
17.Op Fl w| Fl b accesslist
18.Op Fl v
19.Sh DESCRIPTION
20.Nm
21is a bittorrent tracker that implements announce and scrape actions over the
22UDP and the plain http protocol, aiming for minimal resource usage.
23.Pp
24When invoked with parameters, it binds to TCP and UDP port 6969 on all
25interfaces. The recommended way to configure opentracker is by providing a
26config file using the
27.Op Fl f Ar config
28option. See
29.Xr opentracker.conf 5
30for details.
31.Pp
32.Sh OPTIONS
33The following options are available:
34.Bl -tag -width -indent=8
35.It Fl f Ar config
36Parse a config file with a list of options. Consecutive command options
37will override options from the config file. See
38.Xr opentracker.conf 5
39for details.
40.It Fl i Ar ip-select
41Select an ip address that will be used with the next
42.Op Fl p
43or
44.Op Fl P
45command to actually bind to this address. Setting this option without any bind
46options in the config file or
47.Op Fl p
48or
49.Op Fl P
50commands will limit opentracker to only bind to this address.
51.It Fl p Ar port-bind-tcp
52Bind to the TCP port on the last preceding ip address set with the
53.Op Fl i ip-select
54option or to all available addresses if none has been set. Can be given multiple
55times.
56.It Fl P Ar port-bind-udp
57Bind to the UDP port on the last preceding ip address set with the
58.Op Fl i ip-select
59option or to all available addresses if none has been set. Can be given multiple
60times.
61.It Fl A Ar blessed-ip
62Set an ip address in IPv4 or IPv6 or a net in CIDR notation to bless the network
63for access to restricted resources.
64.It Fl r Ar redirect-url
65Set the URL that
66.Nm
67will redirect users to when the / address is requested via HTTP.
68.It Fl d Ar chdir
69Sets the directory
70.Nm
71will
72.Xr chroot 2
73to if ran as root or
74.Xr chdir 2
75to if ran as unprivileged user. Note that any accesslist files need to be
76relative to and within that directory.
77.It Fl u Ar user
78User to run
79.Nm
80under after all operations that need privileges have finished.
81.It Fl w Ar accesslist | Fl b Ar accesslist
82If
83.Nm
84has been compiled with the
85.Sy WANT_ACCESSLIST_BLACK
86or
87.Sy WANT_ACCESSLIST_WHITE
88options, this option sets the location of the accesslist.
89.It Fl v
90Report the version, the event mechanism in use and the feature flags this
91binary was built with.
92.El
93.Sh EXAMPLES
94Start
95.Nm
96bound on UDP and TCP ports 6969 on IPv6 localhost.
97.Dl # ./opentracker -i ::1 -p 6969 -P 6969
98.Pp
99Start
100.Nm
101bound on UDP port 6868 and TCP port 6868 on IPv4 localhost and allow
102privileged access from the network 192.168/16 while redirecting
103HTTP clients accessing the root directory, which is not covered by the
104bittorrent tracker protocol, to https://my-trackersite.com/.
105.Dl # ./opentracker -i 192.168.0.4 -p 6868 -P 6969 -A 192.168/16 -r https://my-trackersite.com/
106The announce URLs are http://192.168.0.4:6868/announce and
107udp://192.168.0.4:6868/announce respectively.
108.Sh FILES
109.Bl -tag -width indent
110.It Pa opentracker.conf
111The
112.Nm
113config file.
114.El
115.Sh SEE ALSO
116.Xr opentracker.conf 5
117.Pp
118opentracker documentation
119.Lk https://erdgeist.org/arts/software/opentracker
120.Pp
121Bittorrent tracker protocol
122.Lk http://www.bittorrent.org/beps/bep_0015.html
123.Sh AUTHOR
124.An Dirk Engling
125.Aq Mt erdgeist@erdgeist.org .
126.Sh LICENSE
127This software is released under the Beerware License:
128.Pp
129Permission is hereby granted, free of charge, to any person obtaining a copy of this software
130and associated documentation files (the "Software"), to deal in the Software with the following
131terms and conditions:
132.Pp
133If you meet the author(s) someday, and you think this software is worth it, you can buy them
134a beer in return.
diff --git a/man5/opentracker.conf.5 b/man5/opentracker.conf.5
new file mode 100644
index 0000000..cc4c942
--- /dev/null
+++ b/man5/opentracker.conf.5
@@ -0,0 +1,166 @@
1.Dd 2026-10-28
2.Dt opentracker.conf 5
3.Os Unix
4.Sh NAME
5.Nm opentracker.conf
6.Nd configuration file for opentracker
7.Sh SYNOPSIS
8.Nm
9.Sh DESCRIPTION
10The
11.Nm
12configuration file specifies various options for configuring the behavior of the opentracker program.
13.Pp
14Lines starting with '#' are comments and are ignored. Options are specified as 'keyword value' pairs.
15.Pp
16The following options are available:
17.Pp
18.Bl -tag -width ".It access.proxy" -compact
19.It listen.tcp_udp Ar address
20Specifies an address opentracker will listen on for both TCP and UDP connections. If none are specified, opentracker listens on 0.0.0.0:6969 by default. Can be added more than once.
21.Pp
22.It listen.tcp Ar address
23Specifies the address opentracker will listen on for TCP connections. Can be added more than once.
24.Pp
25.It listen.udp Ar address
26Specifies the address opentracker will listen on for UDP connections. Can be added more than once.
27.Pp
28A listen statement may carry options after the address, as in
29.Dl listen.udp 10.0.0.5:6969 workers=4 shared
30where
31.Cm workers Ns = Ns Ar count
32sets the worker count for that socket alone and is ignored for TCP, and
33.Cm shared
34permits another process to bind the same address.
35.Pp
36.It listen.udp.workers Ar threads
37Specifies how many threads will be spawned to handle UDP requests, for every
38listen statement that does not carry a
39.Cm workers
40option of its own. Defaults to 1. A count of 0 serves UDP from the event loop,
41in the thread that also serves TCP. See
42.Sx TUNING
43before raising it.
44.Pp
45.It listen.tcp.workers Ar threads
46Specifies how many threads accept and answer HTTP connections, for every
47listen statement that does not carry a
48.Cm workers
49option of its own. Defaults to 0, which serves them from the event loop. See
50.Sx TUNING
51before raising it.
52.Pp
53.It listen.shared Ar boolean
54Permits another process to bind the same address, for every listen statement
55that does not carry a
56.Cm shared
57option of its own. Defaults to 0, and is useful only where a second tracker is
58deliberately run on the same address.
59.Pp
60.It access.whitelist Ar path/to/whitelist
61Specifies the path to the whitelist file containing all torrent hashes that opentracker will serve. Use this option if opentracker runs in a non-open mode.
62.Pp
63.It access.blacklist Ar path/to/blacklist
64Specifies the path to the blacklist file containing all torrent hashes that opentracker will not serve. Use this option if opentracker was compiled to allow blacklisting.
65.Pp
66.It access.fifo_add Ar path/to/adder.fifo
67Specifies the path to the FIFO (named pipe) used for dynamic changesets to accesslists. Info hashes written to this FIFO will be added to the main accesslist file.
68.Pp
69.It access.fifo_delete Ar path/to/deleter.fifo
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
72.It access.stats Ar ip_address_or_network
73Specifies the IP address or network in CIDR notation allowed to fetch stats from opentracker, in case they are restricted.
74.Pp
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.
77.Pp
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.
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
84.It livesync.cluster.listen Ar ip_address:port
85Specifies the IP address and port opentracker will listen on for incoming live
86sync packets to keep a cluster of opentrackers synchronized. Every member of a
87cluster has to agree on the port, which is also the one packets are sent to.
88.Pp
89.It livesync.cluster.group Ar ip_address
90Specifies the multicast group a cluster talks in. For reaosns of backwards
91comaptibility with legacy trackers, it defaults to 224.0.23.5, which,
92technically sits in a range IANA assigns on request.
93
94A cluster of its own is better served by an address out of 239.192.0.0/14,
95which RFC 2365 sets aside for private use. Packets carry a ttl of 1 either
96way and never leave the local link. Must be a valid mulitcast address from
97.Pa 224.0.0.0/4
98.
99.Pp
100.It livesync.cluster.node_ip Ar ip_address
101Specifies one trusted IP address for sync between trackers running in a cluster. Can be added more than once.
102.Pp
103.It tracker.rootdir Ar path
104Specifies the directory opentracker will chroot/chdir to. All black/white list files must be located in this directory.
105.Pp
106.It tracker.user Ar username
107Specifies the user opentracker will setuid to after binding to potentially privileged ports.
108.Pp
109.It tracker.redirect_url Ar URL
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.
118.El
119.Sh TUNING
120A worker is a thread that blocks in a read until a datagram arrives. Where the
121kernel spreads arriving datagrams over a group of sockets bound to one address,
122opentracker binds one socket per worker and throughput rises with the worker
123count. Linux does so, and FreeBSD since 12.0. Where a kernel does not, every
124worker reads the same socket and they contend for its receive queue, so more
125than one worker costs throughput. opentracker asks at start up and binds a
126group only where the answer is yes.
127.Pp
128.Pa tests/udp_scaling.py
129in the source distribution sweeps the setting against a running tracker.
130Measure on the machine that will carry the traffic.
131.Pp
132A TCP worker accepts a connection and answers it on its own stack, without
133the event loop seeing it at all; only a connection it cannot finish is handed
134over. One worker serves less than none, because accepting leaves the event
135loop's thread without anything gained in return, so the setting is worth
136either 0 or at least 2.
137.Pa tests/http_load.c
138in the source distribution drives the tracker over HTTP to measure it.
139.Pp
140On FreeBSD the
141.Xr accf_data 9
142filter has the kernel hold a new connection until data arrives on it, so the
143tracker is woken once with the request already there. opentracker uses it
144wherever it is available; enable it with
145.Cm options ACCEPT_FILTER_DATA
146in the kernel or
147.Va kld_list Ns = Ns Qq accf_data
148in
149.Xr rc.conf 5 .
150.Sh EXAMPLES
151To specify the address opentracker will listen on for both TCP and UDP connections:
152.Dl listen.tcp_udp 0.0.0.0:6969
153.Pp
154To specify the address opentracker will listen on for TCP connections:
155.Dl listen.tcp 0.0.0.0
156.Pp
157To specify the address opentracker will listen on for UDP connections:
158.Dl listen.udp 0.0.0.0:6969
159.Pp
160.Sh SEE ALSO
161.Xr opentracker 1
162.Pp
163.Sh AUTHOR
164.An Dirk Engling
165.Aq Mt erdgeist@erdgeist.org
166.Pp
diff --git a/opentracker.c b/opentracker.c
deleted file mode 100644
index 09010c7..0000000
--- a/opentracker.c
+++ /dev/null
@@ -1,670 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3 Some of the stuff below is stolen from Fefes example libowfat httpd.
4
5 $Id$ */
6
7/* System */
8#include <stdlib.h>
9#include <string.h>
10#include <arpa/inet.h>
11#include <sys/socket.h>
12#include <unistd.h>
13#include <errno.h>
14#include <signal.h>
15#include <stdio.h>
16#include <pwd.h>
17#include <ctype.h>
18#include <pthread.h>
19#ifdef WANT_SYSLOGS
20#include <syslog.h>
21#endif
22
23/* Libowfat */
24#include "socket.h"
25#include "io.h"
26#include "iob.h"
27#include "byte.h"
28#include "scan.h"
29#include "ip6.h"
30
31/* Opentracker */
32#include "trackerlogic.h"
33#include "ot_mutex.h"
34#include "ot_http.h"
35#include "ot_udp.h"
36#include "ot_accesslist.h"
37#include "ot_stats.h"
38#include "ot_livesync.h"
39
40/* Globals */
41time_t g_now_seconds;
42char * g_redirecturl;
43uint32_t g_tracker_id;
44volatile int g_opentracker_running = 1;
45int g_self_pipe[2];
46
47static char * g_serverdir;
48static char * g_serveruser;
49static unsigned int g_udp_workers;
50
51static void panic( const char *routing ) __attribute__ ((noreturn));
52static void panic( const char *routine ) {
53 fprintf( stderr, "%s: %s\n", routine, strerror(errno) );
54 exit( 111 );
55}
56
57static void signal_handler( int s ) {
58 if( s == SIGINT ) {
59 /* Any new interrupt signal quits the application */
60 signal( SIGINT, SIG_DFL);
61
62 /* Tell all other threads to not acquire any new lock on a bucket
63 but cancel their operations and return */
64 g_opentracker_running = 0;
65
66 trackerlogic_deinit();
67
68#ifdef WANT_SYSLOGS
69 closelog();
70#endif
71
72 exit( 0 );
73 } else if( s == SIGALRM ) {
74 /* Maintain our copy of the clock. time() on BSDs is very expensive. */
75 g_now_seconds = time(NULL);
76 alarm(5);
77 }
78}
79
80static void defaul_signal_handlers( void ) {
81 sigset_t signal_mask;
82 sigemptyset(&signal_mask);
83 sigaddset (&signal_mask, SIGPIPE);
84 sigaddset (&signal_mask, SIGHUP);
85 sigaddset (&signal_mask, SIGINT);
86 sigaddset (&signal_mask, SIGALRM);
87 pthread_sigmask (SIG_BLOCK, &signal_mask, NULL);
88}
89
90static void install_signal_handlers( void ) {
91 struct sigaction sa;
92 sigset_t signal_mask;
93 sigemptyset(&signal_mask);
94
95 sa.sa_handler = signal_handler;
96 sigemptyset(&sa.sa_mask);
97 sa.sa_flags = SA_RESTART;
98 if ((sigaction(SIGINT, &sa, NULL) == -1) || (sigaction(SIGALRM, &sa, NULL) == -1) )
99 panic( "install_signal_handlers" );
100
101 sigaddset (&signal_mask, SIGINT);
102 sigaddset (&signal_mask, SIGALRM);
103 pthread_sigmask (SIG_UNBLOCK, &signal_mask, NULL);
104}
105
106static void usage( char *name ) {
107 fprintf( stderr, "Usage: %s [-i ip] [-p port] [-P port] [-r redirect] [-d dir] [-u user] [-A ip] [-f config] [-s livesyncport]"
108#ifdef WANT_ACCESSLIST_BLACK
109 " [-b blacklistfile]"
110#elif defined ( WANT_ACCESSLIST_WHITE )
111 " [-w whitelistfile]"
112#endif
113 "\n", name );
114}
115
116#define HELPLINE(opt,desc) fprintf(stderr, "\t%-10s%s\n",opt,desc)
117static void help( char *name ) {
118 usage( name );
119
120 HELPLINE("-f config","include and execute the config file");
121 HELPLINE("-i ip","specify ip to bind to (default: *, you may specify more than one)");
122 HELPLINE("-p port","specify tcp port to bind to (default: 6969, you may specify more than one)");
123 HELPLINE("-P port","specify udp port to bind to (default: 6969, you may specify more than one)");
124 HELPLINE("-r redirecturl","specify url where / should be redirected to (default none)");
125 HELPLINE("-d dir","specify directory to try to chroot to (default: \".\")");
126 HELPLINE("-u user","specify user under whose priviliges opentracker should run (default: \"nobody\")");
127 HELPLINE("-A ip","bless an ip address as admin address (e.g. to allow syncs from this address)");
128#ifdef WANT_ACCESSLIST_BLACK
129 HELPLINE("-b file","specify blacklist file.");
130#elif defined( WANT_ACCESSLIST_WHITE )
131 HELPLINE("-w file","specify whitelist file.");
132#endif
133
134 fprintf( stderr, "\nExample: ./opentracker -i 127.0.0.1 -p 6969 -P 6969 -f ./opentracker.conf -i 10.1.1.23 -p 2710 -p 80\n" );
135}
136#undef HELPLINE
137
138static size_t header_complete( char * request, ssize_t byte_count ) {
139 int i = 0, state = 0;
140
141 for( i=1; i < byte_count; i+=2 )
142 if( request[i] <= 13 ) {
143 i--;
144 for( state = 0 ; i < byte_count; ++i ) {
145 char c = request[i];
146 if( c == '\r' || c == '\n' )
147 state = ( state >> 2 ) | ( ( c << 6 ) & 0xc0 );
148 else
149 break;
150 if( state >= 0xa0 || state == 0x99 ) return i + 1;
151 }
152 }
153 return 0;
154}
155
156static void handle_dead( const int64 sock ) {
157 struct http_data* cookie=io_getcookie( sock );
158 if( cookie ) {
159 iob_reset( &cookie->batch );
160 array_reset( &cookie->request );
161 if( cookie->flag & STRUCT_HTTP_FLAG_WAITINGFORTASK )
162 mutex_workqueue_canceltask( sock );
163 free( cookie );
164 }
165 io_close( sock );
166}
167
168static void handle_read( const int64 sock, struct ot_workstruct *ws ) {
169 struct http_data* cookie = io_getcookie( sock );
170 ssize_t byte_count;
171
172 if( ( byte_count = io_tryread( sock, ws->inbuf, G_INBUF_SIZE ) ) <= 0 ) {
173 handle_dead( sock );
174 return;
175 }
176
177 /* If we get the whole request in one packet, handle it without copying */
178 if( !array_start( &cookie->request ) ) {
179 if( ( ws->header_size = header_complete( ws->inbuf, byte_count ) ) ) {
180 ws->request = ws->inbuf;
181 ws->request_size = byte_count;
182 http_handle_request( sock, ws );
183 } else
184 array_catb( &cookie->request, ws->inbuf, byte_count );
185 return;
186 }
187
188 array_catb( &cookie->request, ws->inbuf, byte_count );
189 if( array_failed( &cookie->request ) || array_bytes( &cookie->request ) > 8192 ) {
190 http_issue_error( sock, ws, CODE_HTTPERROR_500 );
191 return;
192 }
193
194 while( ( ws->header_size = header_complete( array_start( &cookie->request ), array_bytes( &cookie->request ) ) ) ) {
195 ws->request = array_start( &cookie->request );
196 ws->request_size = array_bytes( &cookie->request );
197 http_handle_request( sock, ws );
198#ifdef WANT_KEEPALIVE
199 if( !ws->keep_alive )
200#endif
201 return;
202 }
203}
204
205static void handle_write( const int64 sock ) {
206 struct http_data* cookie=io_getcookie( sock );
207 if( !cookie || ( iob_send( sock, &cookie->batch ) <= 0 ) )
208 handle_dead( sock );
209}
210
211static void handle_accept( const int64 serversocket ) {
212 struct http_data *cookie;
213 int64 sock;
214 ot_ip6 ip;
215 uint16 port;
216 tai6464 t;
217
218 while( ( sock = socket_accept6( serversocket, ip, &port, NULL ) ) != -1 ) {
219
220 /* Put fd into a non-blocking mode */
221 io_nonblock( sock );
222
223 if( !io_fd( sock ) ||
224 !( cookie = (struct http_data*)malloc( sizeof(struct http_data) ) ) ) {
225 io_close( sock );
226 continue;
227 }
228 memset(cookie, 0, sizeof( struct http_data ) );
229 memcpy(cookie->ip,ip,sizeof(ot_ip6));
230
231 io_setcookie( sock, cookie );
232 io_wantread( sock );
233
234 stats_issue_event( EVENT_ACCEPT, FLAG_TCP, (uintptr_t)ip);
235
236 /* That breaks taia encapsulation. But there is no way to take system
237 time this often in FreeBSD and libowfat does not allow to set unix time */
238 taia_uint( &t, 0 ); /* Clear t */
239 tai_unix( &(t.sec), (g_now_seconds + OT_CLIENT_TIMEOUT) );
240 io_timeout( sock, t );
241 }
242 io_eagain(serversocket);
243}
244
245static void * server_mainloop( void * args ) {
246 struct ot_workstruct ws;
247 time_t next_timeout_check = g_now_seconds + OT_CLIENT_TIMEOUT_CHECKINTERVAL;
248 struct iovec *iovector;
249 int iovec_entries;
250
251 (void)args;
252
253 /* Initialize our "thread local storage" */
254 ws.inbuf = malloc( G_INBUF_SIZE );
255 ws.outbuf = malloc( G_OUTBUF_SIZE );
256#ifdef _DEBUG_HTTPERROR
257 ws.debugbuf= malloc( G_DEBUGBUF_SIZE );
258#endif
259 if( !ws.inbuf || !ws.outbuf )
260 panic( "Initializing worker failed" );
261
262 for( ; ; ) {
263 int64 sock;
264
265 io_wait();
266
267 while( ( sock = io_canread( ) ) != -1 ) {
268 const void *cookie = io_getcookie( sock );
269 if( (intptr_t)cookie == FLAG_TCP )
270 handle_accept( sock );
271 else if( (intptr_t)cookie == FLAG_UDP )
272 handle_udp6( sock, &ws );
273 else if( (intptr_t)cookie == FLAG_SELFPIPE ) {
274 io_tryread( sock, ws.inbuf, G_INBUF_SIZE );
275 fprintf(stderr, "pipe\n");
276 } else
277 handle_read( sock, &ws );
278 }
279
280 while( ( sock = mutex_workqueue_popresult( &iovec_entries, &iovector ) ) != -1 )
281 http_sendiovecdata( sock, &ws, iovec_entries, iovector );
282
283 while( ( sock = io_canwrite( ) ) != -1 )
284 handle_write( sock );
285
286 if( g_now_seconds > next_timeout_check ) {
287 while( ( sock = io_timeouted() ) != -1 )
288 handle_dead( sock );
289 next_timeout_check = g_now_seconds + OT_CLIENT_TIMEOUT_CHECKINTERVAL;
290 }
291
292 livesync_ticker();
293
294 /* Enforce setting the clock */
295 signal_handler( SIGALRM );
296 }
297 return 0;
298}
299
300static int64_t ot_try_bind( ot_ip6 ip, uint16_t port, PROTO_FLAG proto ) {
301 int64 sock = proto == FLAG_TCP ? socket_tcp6( ) : socket_udp6( );
302
303#ifndef WANT_V6
304 if( !ip6_isv4mapped(ip) ) {
305 exerr( "V4 Tracker is V4 only!" );
306 }
307#else
308 if( ip6_isv4mapped(ip) ) {
309 exerr( "V6 Tracker is V6 only!" );
310 }
311#endif
312
313#ifdef _DEBUG
314 {
315 char *protos[] = {"TCP","UDP","UDP mcast"};
316 char _debug[512];
317 int off = snprintf( _debug, sizeof(_debug), "Binding socket type %s to address [", protos[proto] );
318 off += fmt_ip6c( _debug+off, ip);
319 snprintf( _debug + off, sizeof(_debug)-off, "]:%d...", port);
320 fputs( _debug, stderr );
321 }
322#endif
323
324 if( socket_bind6_reuse( sock, ip, port, 0 ) == -1 )
325 panic( "socket_bind6_reuse" );
326
327 if( ( proto == FLAG_TCP ) && ( socket_listen( sock, SOMAXCONN) == -1 ) )
328 panic( "socket_listen" );
329
330 if( !io_fd( sock ) )
331 panic( "io_fd" );
332
333 io_setcookie( sock, (void*)proto );
334
335 if( (proto == FLAG_UDP) && g_udp_workers ) {
336 io_block( sock );
337 udp_init( sock, g_udp_workers );
338 } else
339 io_wantread( sock );
340
341#ifdef _DEBUG
342 fputs( " success.\n", stderr);
343#endif
344
345 return sock;
346}
347
348char * set_config_option( char **option, char *value ) {
349#ifdef _DEBUG
350 fprintf( stderr, "Setting config option: %s\n", value );
351#endif
352 while( isspace(*value) ) ++value;
353 free( *option );
354 return *option = strdup( value );
355}
356
357static int scan_ip6_port( const char *src, ot_ip6 ip, uint16 *port ) {
358 const char *s = src;
359 int off, bracket = 0;
360 while( isspace(*s) ) ++s;
361 if( *s == '[' ) ++s, ++bracket; /* for v6 style notation */
362 if( !(off = scan_ip6( s, ip ) ) )
363 return 0;
364 s += off;
365 if( bracket && *s == ']' ) ++s;
366 if( *s == 0 || isspace(*s)) return s-src;
367 if( !ip6_isv4mapped(ip)){
368 if( *s != ':' && *s != '.' ) return 0;
369 if( !bracket && *(s) == ':' ) return 0;
370 s++;
371 } else {
372 if( *(s++) != ':' ) return 0;
373 }
374 if( !(off = scan_ushort (s, port ) ) )
375 return 0;
376 return off+s-src;
377}
378
379int parse_configfile( char * config_filename ) {
380 FILE * accesslist_filehandle;
381 char inbuf[512];
382 ot_ip6 tmpip;
383 int bound = 0;
384
385 accesslist_filehandle = fopen( config_filename, "r" );
386
387 if( accesslist_filehandle == NULL ) {
388 fprintf( stderr, "Warning: Can't open config file: %s.", config_filename );
389 return 0;
390 }
391
392 while( fgets( inbuf, sizeof(inbuf), accesslist_filehandle ) ) {
393 char *p = inbuf;
394 size_t strl;
395
396 /* Skip white spaces */
397 while(isspace(*p)) ++p;
398
399 /* Ignore comments and empty lines */
400 if((*p=='#')||(*p=='\n')||(*p==0)) continue;
401
402 /* consume trailing new lines and spaces */
403 strl = strlen(p);
404 while( strl && isspace(p[strl-1]))
405 p[--strl] = 0;
406
407 /* Scan for commands */
408 if(!byte_diff(p,15,"tracker.rootdir" ) && isspace(p[15])) {
409 set_config_option( &g_serverdir, p+16 );
410 } else if(!byte_diff(p,12,"tracker.user" ) && isspace(p[12])) {
411 set_config_option( &g_serveruser, p+13 );
412 } else if(!byte_diff(p,14,"listen.tcp_udp" ) && isspace(p[14])) {
413 uint16_t tmpport = 6969;
414 if( !scan_ip6_port( p+15, tmpip, &tmpport )) goto parse_error;
415 ot_try_bind( tmpip, tmpport, FLAG_TCP ); ++bound;
416 ot_try_bind( tmpip, tmpport, FLAG_UDP ); ++bound;
417 } else if(!byte_diff(p,10,"listen.tcp" ) && isspace(p[10])) {
418 uint16_t tmpport = 6969;
419 if( !scan_ip6_port( p+11, tmpip, &tmpport )) goto parse_error;
420 ot_try_bind( tmpip, tmpport, FLAG_TCP );
421 ++bound;
422 } else if(!byte_diff(p, 10, "listen.udp" ) && isspace(p[10])) {
423 uint16_t tmpport = 6969;
424 if( !scan_ip6_port( p+11, tmpip, &tmpport )) goto parse_error;
425 ot_try_bind( tmpip, tmpport, FLAG_UDP );
426 ++bound;
427 } else if(!byte_diff(p,18,"listen.udp.workers" ) && isspace(p[18])) {
428 char *value = p + 18;
429 while( isspace(*value) ) ++value;
430 scan_uint( value, &g_udp_workers );
431#ifdef WANT_ACCESSLIST_WHITE
432 } else if(!byte_diff(p, 16, "access.whitelist" ) && isspace(p[16])) {
433 set_config_option( &g_accesslist_filename, p+17 );
434#elif defined( WANT_ACCESSLIST_BLACK )
435 } else if(!byte_diff(p, 16, "access.blacklist" ) && isspace(p[16])) {
436 set_config_option( &g_accesslist_filename, p+17 );
437#endif
438#ifdef WANT_RESTRICT_STATS
439 } else if(!byte_diff(p, 12, "access.stats" ) && isspace(p[12])) {
440 if( !scan_ip6( p+13, tmpip )) goto parse_error;
441 accesslist_blessip( tmpip, OT_PERMISSION_MAY_STAT );
442#endif
443 } else if(!byte_diff(p, 17, "access.stats_path" ) && isspace(p[17])) {
444 set_config_option( &g_stats_path, p+18 );
445#ifdef WANT_IP_FROM_PROXY
446 } else if(!byte_diff(p, 12, "access.proxy" ) && isspace(p[12])) {
447 if( !scan_ip6( p+13, tmpip )) goto parse_error;
448 accesslist_blessip( tmpip, OT_PERMISSION_MAY_PROXY );
449#endif
450 } else if(!byte_diff(p, 20, "tracker.redirect_url" ) && isspace(p[20])) {
451 set_config_option( &g_redirecturl, p+21 );
452#ifdef WANT_SYNC_LIVE
453 } else if(!byte_diff(p, 24, "livesync.cluster.node_ip" ) && isspace(p[24])) {
454 if( !scan_ip6( p+25, tmpip )) goto parse_error;
455 accesslist_blessip( tmpip, OT_PERMISSION_MAY_LIVESYNC );
456 } else if(!byte_diff(p, 23, "livesync.cluster.listen" ) && isspace(p[23])) {
457 uint16_t tmpport = LIVESYNC_PORT;
458 if( !scan_ip6_port( p+24, tmpip, &tmpport )) goto parse_error;
459 livesync_bind_mcast( tmpip, tmpport );
460#endif
461 } else
462 fprintf( stderr, "Unhandled line in config file: %s\n", inbuf );
463 continue;
464 parse_error:
465 fprintf( stderr, "Parse error in config file: %s\n", inbuf);
466 }
467 fclose( accesslist_filehandle );
468 return bound;
469}
470
471void load_state(const char * const state_filename ) {
472 FILE * state_filehandle;
473 char inbuf[512];
474 ot_hash infohash;
475 unsigned long long base, downcount;
476 int consumed;
477
478 state_filehandle = fopen( state_filename, "r" );
479
480 if( state_filehandle == NULL ) {
481 fprintf( stderr, "Warning: Can't open config file: %s.", state_filename );
482 return;
483 }
484
485 /* We do ignore anything that is not of the form "^[:xdigit:]:\d+:\d+" */
486 while( fgets( inbuf, sizeof(inbuf), state_filehandle ) ) {
487 int i;
488 for( i=0; i<(int)sizeof(ot_hash); ++i ) {
489 int eger = 16 * scan_fromhex( inbuf[ 2*i ] ) + scan_fromhex( inbuf[ 1 + 2*i ] );
490 if( eger < 0 )
491 continue;
492 infohash[i] = eger;
493 }
494
495 if( i != (int)sizeof(ot_hash) ) continue;
496 i *= 2;
497
498 if( inbuf[ i++ ] != ':' || !( consumed = scan_ulonglong( inbuf+i, &base ) ) ) continue;
499 i += consumed;
500 if( inbuf[ i++ ] != ':' || !( consumed = scan_ulonglong( inbuf+i, &downcount ) ) ) continue;
501 add_torrent_from_saved_state( infohash, base, downcount );
502 }
503
504 fclose( state_filehandle );
505}
506
507int drop_privileges ( const char * const serveruser, const char * const serverdir ) {
508 struct passwd *pws = NULL;
509
510#ifdef _DEBUG
511 if( !geteuid() )
512 fprintf( stderr, "Dropping to user %s.\n", serveruser );
513 if( serverdir )
514 fprintf( stderr, "ch%s'ing to directory %s.\n", geteuid() ? "dir" : "root", serverdir );
515#endif
516
517 /* Grab pws entry before chrooting */
518 pws = getpwnam( serveruser );
519 endpwent();
520
521 if( geteuid() == 0 ) {
522 /* Running as root: chroot and drop privileges */
523 if( serverdir && chroot( serverdir ) ) {
524 fprintf( stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno) );
525 return -1;
526 }
527
528 if(chdir("/"))
529 panic("chdir() failed after chrooting: ");
530
531 /* If we can't find server user, revert to nobody's default uid */
532 if( !pws ) {
533 fprintf( stderr, "Warning: Could not get password entry for %s. Reverting to uid -2.\n", serveruser );
534 setegid( (gid_t)-2 ); setgid( (gid_t)-2 );
535 setuid( (uid_t)-2 ); seteuid( (uid_t)-2 );
536 }
537 else {
538 setegid( pws->pw_gid ); setgid( pws->pw_gid );
539 setuid( pws->pw_uid ); seteuid( pws->pw_uid );
540 }
541
542 if( geteuid() == 0 || getegid() == 0 )
543 panic("Still running with root privileges?!");
544 }
545 else {
546 /* Normal user, just chdir() */
547 if( serverdir && chdir( serverdir ) ) {
548 fprintf( stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno) );
549 return -1;
550 }
551 }
552
553 return 0;
554}
555
556int main( int argc, char **argv ) {
557 ot_ip6 serverip, tmpip;
558 int bound = 0, scanon = 1;
559 uint16_t tmpport;
560 char * statefile = 0;
561
562 memset( serverip, 0, sizeof(ot_ip6) );
563#ifndef WANT_V6
564 serverip[10]=serverip[11]=-1;
565 noipv6=1;
566#endif
567
568#ifdef WANT_DEV_RANDOM
569 srandomdev();
570#else
571 srandom( time(NULL) );
572#endif
573
574 while( scanon ) {
575 switch( getopt( argc, argv, ":i:p:A:P:d:u:r:s:f:l:v"
576#ifdef WANT_ACCESSLIST_BLACK
577"b:"
578#elif defined( WANT_ACCESSLIST_WHITE )
579"w:"
580#endif
581 "h" ) ) {
582 case -1 : scanon = 0; break;
583 case 'i':
584 if( !scan_ip6( optarg, serverip )) { usage( argv[0] ); exit( 1 ); }
585 break;
586#ifdef WANT_ACCESSLIST_BLACK
587 case 'b': set_config_option( &g_accesslist_filename, optarg); break;
588#elif defined( WANT_ACCESSLIST_WHITE )
589 case 'w': set_config_option( &g_accesslist_filename, optarg); break;
590#endif
591 case 'p':
592 if( !scan_ushort( optarg, &tmpport)) { usage( argv[0] ); exit( 1 ); }
593 ot_try_bind( serverip, tmpport, FLAG_TCP ); bound++; break;
594 case 'P':
595 if( !scan_ushort( optarg, &tmpport)) { usage( argv[0] ); exit( 1 ); }
596 ot_try_bind( serverip, tmpport, FLAG_UDP ); bound++; break;
597#ifdef WANT_SYNC_LIVE
598 case 's':
599 if( !scan_ushort( optarg, &tmpport)) { usage( argv[0] ); exit( 1 ); }
600 livesync_bind_mcast( serverip, tmpport); break;
601#endif
602 case 'd': set_config_option( &g_serverdir, optarg ); break;
603 case 'u': set_config_option( &g_serveruser, optarg ); break;
604 case 'r': set_config_option( &g_redirecturl, optarg ); break;
605 case 'l': statefile = optarg; break;
606 case 'A':
607 if( !scan_ip6( optarg, tmpip )) { usage( argv[0] ); exit( 1 ); }
608 accesslist_blessip( tmpip, 0xffff ); /* Allow everything for now */
609 break;
610 case 'f': bound += parse_configfile( optarg ); break;
611 case 'h': help( argv[0] ); exit( 0 );
612 case 'v': {
613 char buffer[8192];
614 stats_return_tracker_version( buffer );
615 fputs( buffer, stderr );
616 exit( 0 );
617 }
618 default:
619 case '?': usage( argv[0] ); exit( 1 );
620 }
621 }
622
623 /* Bind to our default tcp/udp ports */
624 if( !bound) {
625 ot_try_bind( serverip, 6969, FLAG_TCP );
626 ot_try_bind( serverip, 6969, FLAG_UDP );
627 }
628
629#ifdef WANT_SYSLOGS
630 openlog( "opentracker", 0, LOG_USER );
631 setlogmask(LOG_UPTO(LOG_INFO));
632#endif
633
634 if( drop_privileges( g_serveruser ? g_serveruser : "nobody", g_serverdir ) == -1 )
635 panic( "drop_privileges failed, exiting. Last error");
636
637 g_now_seconds = time( NULL );
638
639 /* Create our self pipe which allows us to interrupt mainloops
640 io_wait in case some data is available to send out */
641 if( pipe( g_self_pipe ) == -1 )
642 panic( "selfpipe failed: " );
643 if( !io_fd( g_self_pipe[0] ) )
644 panic( "selfpipe io_fd failed: " );
645 if( !io_fd( g_self_pipe[1] ) )
646 panic( "selfpipe io_fd failed: " );
647 io_setcookie( g_self_pipe[0], (void*)FLAG_SELFPIPE );
648 io_wantread( g_self_pipe[0] );
649
650 defaul_signal_handlers( );
651 /* Init all sub systems. This call may fail with an exit() */
652 trackerlogic_init( );
653
654 if( statefile )
655 load_state( statefile );
656
657 install_signal_handlers( );
658
659 if( !g_udp_workers )
660 udp_init( -1, 0 );
661
662 /* Kick off our initial clock setting alarm */
663 alarm(5);
664
665 server_mainloop( 0 );
666
667 return 0;
668}
669
670const char *g_version_opentracker_c = "$Source$: $Revision$\n";
diff --git a/opentracker.conf.sample b/opentracker.conf.sample
index db45122..da0b601 100644
--- a/opentracker.conf.sample
+++ b/opentracker.conf.sample
@@ -2,19 +2,13 @@
2# 2#
3 3
4# I) Address opentracker will listen on, using both, tcp AND udp family 4# I) Address opentracker will listen on, using both, tcp AND udp family
5# (note, that port 6969 is implicite if ommitted). 5# (note, that port 6969 is implicit if omitted).
6# 6#
7# If no listen option is given (here or on the command line), opentracker 7# If no listen option is given (here or on the command line), opentracker
8# listens on 0.0.0.0:6969 tcp and udp. 8# listens on 0.0.0.0:6969 tcp and udp.
9# 9#
10# The next variable determines if udp sockets are handled in the event 10# Addresses are collected while this file is read and bound afterwards,
11# loop (set it to 0, the default) or are handled in blocking reads in 11# so the order of the statements below does not matter.
12# dedicated worker threads. You have to set this value before the
13# listen.tcp_udp or listen.udp statements before it takes effect, but you
14# can re-set it for each listen statement. Normally you should keep it at
15# the top of the config file.
16#
17# listen.udp.workers 4
18# 12#
19# listen.tcp_udp 0.0.0.0 13# listen.tcp_udp 0.0.0.0
20# listen.tcp_udp 192.168.0.1:80 14# listen.tcp_udp 192.168.0.1:80
@@ -25,6 +19,37 @@
25# listen.tcp 0.0.0.0 19# listen.tcp 0.0.0.0
26# listen.udp 192.168.0.1:6969 20# listen.udp 192.168.0.1:6969
27# 21#
22# A listen statement takes options after the address:
23#
24# workers=<count> handle this socket in that many dedicated worker
25# threads instead of in the event loop. Defaults to 1
26# for udp and 0 for tcp.
27# shared allow another process to bind the same address and
28# let the kernel share the traffic. Only useful if you
29# deliberately run a second tracker there.
30#
31# listen.udp 10.0.0.5:6969 workers=4 shared
32#
33# The two statements below set defaults for every listen statement in
34# this file that does not name the option itself. They may appear
35# anywhere.
36#
37# listen.udp.workers 4
38# listen.tcp.workers 4
39# listen.shared 1
40#
41# Raising the worker count pays off where the kernel spreads arriving
42# datagrams over a group of sockets bound to one address. Linux does so
43# and FreeBSD has since 12.0, Darwin does not. opentracker asks at start
44# up and binds one socket per worker only where the answer is yes. Where
45# it is no, all workers read the one socket and contend for its receive
46# queue, which costs more than it returns. See the TUNING section of
47# opentracker.conf(5); tests/udp_scaling.py sweeps the setting on the
48# machine that will carry the traffic.
49#
50# A count of 0 answers udp from the event loop, in the thread that also
51# serves tcp, which is what opentracker did before.
52#
28# Note, that using 0.0.0.0 for udp sockets may yield surprising results. 53# Note, that using 0.0.0.0 for udp sockets may yield surprising results.
29# An answer packet sent on that socket will not necessarily have the 54# An answer packet sent on that socket will not necessarily have the
30# source address that the requesting client may expect, but any address 55# source address that the requesting client may expect, but any address
@@ -44,17 +69,70 @@
44# listing, so choose one of those options at compile time. File format 69# listing, so choose one of those options at compile time. File format
45# is straight forward: "<hex info hash>\n<hex info hash>\n..." 70# is straight forward: "<hex info hash>\n<hex info hash>\n..."
46# 71#
72# IIa) You can enable dynamic changesets to accesslists by enabling
73# WANT_DYNAMIC_ACCESSLIST.
74#
75# The suggested way to work with dynamic changeset lists is to keep a
76# main accesslist file that is loaded when opentracker (re)starts and
77# reloaded infrequently (hourly or daily).
78#
79# All changes to the accesslist (e.g. from a web frontend) should be
80# both appended to or removed from that file and sent to opentracker. By
81# keeping dynamic changeset lists, you can avoid reloading huge
82# accesslists whenever just a single entry is added or removed.
83#
84# Any info_hash (format see above) written to the fifo_add file will be
85# kept on a dynamic add-changeset, removed from the dynamic
86# delete-changeset and treated as if it was in the main accesslist file.
87# The semantic of the respective dynamic changeset depends on whether
88# WANT_ACCESSLIST_WHITE or WANT_ACCESSLIST_BLACK is enabled.
89#
90# access.fifo_add /var/run/opentracker/adder.fifo
91#
92# Any info_hash (format see above) written to the fifo_delete file will
93# be kept on a dynamic delete-changeset, removed from the dynamic
94# add-changeset and treated as if it was not in the main accesslist
95# file.
96#
97# access.fifo_delete /var/run/opentracker/deleter.fifo
98#
99# If you reload the accesslist by sending SIGHUP to the tracker process,
100# the dynamic lists are flushed, as opentracker assumes thoses lists are
101# merged into the main accesslist.
102#
103# NOTE: While you can have multiple writers sending lines to the fifos,
104# any writes larger than PIPE_BUF (see your limits.h, minimally 512
105# bytes but usually 4096) may be interleaved with data sent by other
106# writers. This can lead to unparsable lines of info_hashes.
107#
108# IIb)
47# If you do not want to grant anyone access to your stats, enable the 109# If you do not want to grant anyone access to your stats, enable the
48# WANT_RESTRICT_STATS option in Makefile and bless the ip addresses 110# WANT_RESTRICT_STATS option in Makefile and bless the ip addresses
49# allowed to fetch stats here. 111# or network allowed to fetch stats here.
50# 112#
51# access.stats 192.168.0.23 113# access.stats 192.168.0.23
114# access.stats 10.1.1.23
52# 115#
53# There is another way of hiding your stats. You can obfuscate the path 116# There is another way of hiding your stats. You can obfuscate the path
54# to them. Normally it is located at /stats but you can configure it to 117# to them. Normally it is located at /stats but you can configure it to
55# appear anywhere on your tracker. 118# appear anywhere on your tracker.
56# 119#
57# access.stats_path stats 120# access.stats_path stats
121#
122# If opentracker lives behind one or multiple reverse proxies,
123# every http connection appears to come from these proxies. In order to
124# take the X-Forwarded-For address instead, compile opentracker with the
125# WANT_IP_FROM_PROXY option and set your proxy addresses or networkss here.
126#
127# access.proxy 10.0.1.23
128# access.proxy 192.0.0.0/8
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#
58 136
59# 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
60# synchronized. This option tells opentracker which port to listen for 138# synchronized. This option tells opentracker which port to listen for
@@ -65,12 +143,22 @@
65# livesync.cluster.listen 192.168.0.1:9696 143# livesync.cluster.listen 192.168.0.1:9696
66# 144#
67# Note that two udp sockets will be opened. One on ip address 0.0.0.0 145# Note that two udp sockets will be opened. One on ip address 0.0.0.0
68# port 9696, that will join the multicast group 224.0.42.23 for incoming 146# port 9696, that will join the multicast group for incoming udp packets
69# udp packets and one on ip address 192.168.0.1 port 9696 for outgoing 147# and one on ip address 192.168.0.1 port 9696 for outgoing ones. Every
70# udp packets. 148# member of a cluster has to agree on the port as well as the group.
149#
150# The group a cluster talks in.
151#
152# livesync.cluster.group 239.192.23.5
153#
154# For reaosns of backwards comaptibility with legacy trackers, it
155# defaults to 224.0.23.5, which, technically sits in a range IANA
156# assigns on request.
157#
158# A cluster of your own is better served by an address out of
159# 239.192.0.0/14, which RFC 2365 sets aside for private use. Packets
160# carry a ttl of 1 either way, so they never leave the local link.
71# 161#
72# As of now one and only one ip address must be given, if opentracker
73# was built with the WANT_SYNC_LIVE feature.
74# 162#
75 163
76# IV) Sync between trackers running in a cluster is restricted to packets 164# IV) Sync between trackers running in a cluster is restricted to packets
@@ -81,12 +169,6 @@
81# livesync.cluster.node_ip 192.168.0.4 169# livesync.cluster.node_ip 192.168.0.4
82# livesync.cluster.node_ip 192.168.0.5 170# livesync.cluster.node_ip 192.168.0.5
83# livesync.cluster.node_ip 192.168.0.6 171# livesync.cluster.node_ip 192.168.0.6
84#
85# This is the admin ip address for old style (HTTP based) asynchronus
86# tracker syncing.
87#
88# batchsync.cluster.admin_ip 10.1.1.1
89#
90 172
91# V) Control privilege drop behaviour. 173# V) Control privilege drop behaviour.
92# Put in the directory opentracker will chroot/chdir to. All black/white 174# Put in the directory opentracker will chroot/chdir to. All black/white
@@ -104,3 +186,10 @@
104# redirect to another location (shell option -r). 186# redirect to another location (shell option -r).
105# 187#
106# 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/opentracker.xcodeproj/project.pbxproj b/opentracker.xcodeproj/project.pbxproj
deleted file mode 100644
index 3706a3f..0000000
--- a/opentracker.xcodeproj/project.pbxproj
+++ /dev/null
@@ -1,320 +0,0 @@
1// !$*UTF8*$!
2{
3 archiveVersion = 1;
4 classes = {
5 };
6 objectVersion = 44;
7 objects = {
8
9/* Begin PBXBuildFile section */
10 6520B7530D036AAF00A43B1F /* libowfat.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6520B7520D036AAF00A43B1F /* libowfat.a */; };
11 653A320C0CE7F475007F0D03 /* ot_accesslist.c in Sources */ = {isa = PBXBuildFile; fileRef = 653A320B0CE7F475007F0D03 /* ot_accesslist.c */; };
12 653A56B50CE28EC5000CF140 /* ot_iovec.c in Sources */ = {isa = PBXBuildFile; fileRef = 653A56B40CE28EC5000CF140 /* ot_iovec.c */; };
13 654A80890CD832FD009035DE /* opentracker.c in Sources */ = {isa = PBXBuildFile; fileRef = 654A80840CD832FC009035DE /* opentracker.c */; };
14 654A808A0CD832FD009035DE /* scan_urlencoded_query.c in Sources */ = {isa = PBXBuildFile; fileRef = 654A80850CD832FC009035DE /* scan_urlencoded_query.c */; };
15 654A808B0CD832FD009035DE /* trackerlogic.c in Sources */ = {isa = PBXBuildFile; fileRef = 654A80870CD832FC009035DE /* trackerlogic.c */; };
16 65542D8B0CE078E800469330 /* ot_vector.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542D8A0CE078E800469330 /* ot_vector.c */; };
17 65542D930CE07CED00469330 /* ot_mutex.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542D8F0CE07CED00469330 /* ot_mutex.c */; };
18 65542D940CE07CED00469330 /* ot_stats.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542D910CE07CED00469330 /* ot_stats.c */; };
19 65542E750CE08B9100469330 /* ot_clean.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542E740CE08B9100469330 /* ot_clean.c */; };
20 65542EE80CE0CA6B00469330 /* ot_udp.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542EE70CE0CA6B00469330 /* ot_udp.c */; };
21 65542F920CE17CA900469330 /* ot_fullscrape.c in Sources */ = {isa = PBXBuildFile; fileRef = 65542F910CE17CA900469330 /* ot_fullscrape.c */; };
22 65B8DF3C0D0310D20017149E /* ot_http.c in Sources */ = {isa = PBXBuildFile; fileRef = 65B8DF3B0D0310D20017149E /* ot_http.c */; };
23 65FA33990E7EF09200F7D5A5 /* ot_livesync.c in Sources */ = {isa = PBXBuildFile; fileRef = 65FA33980E7EF09200F7D5A5 /* ot_livesync.c */; };
24 8DD76FB00486AB0100D96B5E /* opentracker.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = C6A0FF2C0290799A04C91782 /* opentracker.1 */; };
25/* End PBXBuildFile section */
26
27/* Begin PBXCopyFilesBuildPhase section */
28 8DD76FAF0486AB0100D96B5E /* CopyFiles */ = {
29 isa = PBXCopyFilesBuildPhase;
30 buildActionMask = 8;
31 dstPath = /usr/share/man/man1/;
32 dstSubfolderSpec = 0;
33 files = (
34 8DD76FB00486AB0100D96B5E /* opentracker.1 in CopyFiles */,
35 );
36 runOnlyForDeploymentPostprocessing = 1;
37 };
38/* End PBXCopyFilesBuildPhase section */
39
40/* Begin PBXFileReference section */
41 6520B7520D036AAF00A43B1F /* libowfat.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libowfat.a; path = ../libowfat/libowfat.a; sourceTree = SOURCE_ROOT; };
42 653A320A0CE7F475007F0D03 /* ot_accesslist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_accesslist.h; sourceTree = "<group>"; };
43 653A320B0CE7F475007F0D03 /* ot_accesslist.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_accesslist.c; sourceTree = "<group>"; };
44 653A56AC0CE201FF000CF140 /* opentracker */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = opentracker; sourceTree = BUILT_PRODUCTS_DIR; };
45 653A56B30CE28EC5000CF140 /* ot_iovec.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_iovec.h; sourceTree = "<group>"; };
46 653A56B40CE28EC5000CF140 /* ot_iovec.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_iovec.c; sourceTree = "<group>"; };
47 654A80840CD832FC009035DE /* opentracker.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = opentracker.c; sourceTree = "<group>"; };
48 654A80850CD832FC009035DE /* scan_urlencoded_query.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = scan_urlencoded_query.c; sourceTree = "<group>"; };
49 654A80860CD832FC009035DE /* scan_urlencoded_query.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = scan_urlencoded_query.h; sourceTree = "<group>"; };
50 654A80870CD832FC009035DE /* trackerlogic.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = trackerlogic.c; sourceTree = "<group>"; };
51 654A80880CD832FC009035DE /* trackerlogic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = trackerlogic.h; sourceTree = "<group>"; };
52 65542D890CE078E800469330 /* ot_vector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_vector.h; sourceTree = "<group>"; };
53 65542D8A0CE078E800469330 /* ot_vector.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_vector.c; sourceTree = "<group>"; };
54 65542D8F0CE07CED00469330 /* ot_mutex.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_mutex.c; sourceTree = "<group>"; };
55 65542D900CE07CED00469330 /* ot_mutex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_mutex.h; sourceTree = "<group>"; };
56 65542D910CE07CED00469330 /* ot_stats.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_stats.c; sourceTree = "<group>"; };
57 65542D920CE07CED00469330 /* ot_stats.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_stats.h; sourceTree = "<group>"; };
58 65542E730CE08B9100469330 /* ot_clean.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_clean.h; sourceTree = "<group>"; };
59 65542E740CE08B9100469330 /* ot_clean.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_clean.c; sourceTree = "<group>"; };
60 65542EE60CE0CA6B00469330 /* ot_udp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_udp.h; sourceTree = "<group>"; };
61 65542EE70CE0CA6B00469330 /* ot_udp.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_udp.c; sourceTree = "<group>"; };
62 65542F900CE17CA900469330 /* ot_fullscrape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_fullscrape.h; sourceTree = "<group>"; };
63 65542F910CE17CA900469330 /* ot_fullscrape.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_fullscrape.c; sourceTree = "<group>"; };
64 65B8DF3A0D0310D20017149E /* ot_http.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_http.h; sourceTree = "<group>"; };
65 65B8DF3B0D0310D20017149E /* ot_http.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_http.c; sourceTree = "<group>"; };
66 65FA33970E7EF09200F7D5A5 /* ot_livesync.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ot_livesync.h; sourceTree = "<group>"; };
67 65FA33980E7EF09200F7D5A5 /* ot_livesync.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ot_livesync.c; sourceTree = "<group>"; };
68 C6A0FF2C0290799A04C91782 /* opentracker.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = opentracker.1; sourceTree = "<group>"; };
69/* End PBXFileReference section */
70
71/* Begin PBXFrameworksBuildPhase section */
72 8DD76FAD0486AB0100D96B5E /* Frameworks */ = {
73 isa = PBXFrameworksBuildPhase;
74 buildActionMask = 2147483647;
75 files = (
76 6520B7530D036AAF00A43B1F /* libowfat.a in Frameworks */,
77 );
78 runOnlyForDeploymentPostprocessing = 0;
79 };
80/* End PBXFrameworksBuildPhase section */
81
82/* Begin PBXGroup section */
83 08FB7794FE84155DC02AAC07 /* opentracker */ = {
84 isa = PBXGroup;
85 children = (
86 65542D810CE0786F00469330 /* Headers */,
87 08FB7795FE84155DC02AAC07 /* Source */,
88 92762AC9104EDED700FDCB60 /* Libraries */,
89 C6A0FF2B0290797F04C91782 /* Documentation */,
90 653A56AD0CE201FF000CF140 /* Products */,
91 );
92 name = opentracker;
93 sourceTree = "<group>";
94 };
95 08FB7795FE84155DC02AAC07 /* Source */ = {
96 isa = PBXGroup;
97 children = (
98 654A80840CD832FC009035DE /* opentracker.c */,
99 653A320B0CE7F475007F0D03 /* ot_accesslist.c */,
100 65542E740CE08B9100469330 /* ot_clean.c */,
101 65542F910CE17CA900469330 /* ot_fullscrape.c */,
102 65B8DF3B0D0310D20017149E /* ot_http.c */,
103 65FA33980E7EF09200F7D5A5 /* ot_livesync.c */,
104 653A56B40CE28EC5000CF140 /* ot_iovec.c */,
105 65542D8F0CE07CED00469330 /* ot_mutex.c */,
106 65542D910CE07CED00469330 /* ot_stats.c */,
107 65542EE70CE0CA6B00469330 /* ot_udp.c */,
108 65542D8A0CE078E800469330 /* ot_vector.c */,
109 654A80850CD832FC009035DE /* scan_urlencoded_query.c */,
110 654A80870CD832FC009035DE /* trackerlogic.c */,
111 );
112 name = Source;
113 sourceTree = "<group>";
114 };
115 653A56AD0CE201FF000CF140 /* Products */ = {
116 isa = PBXGroup;
117 children = (
118 653A56AC0CE201FF000CF140 /* opentracker */,
119 );
120 name = Products;
121 sourceTree = "<group>";
122 };
123 65542D810CE0786F00469330 /* Headers */ = {
124 isa = PBXGroup;
125 children = (
126 653A320A0CE7F475007F0D03 /* ot_accesslist.h */,
127 65542E730CE08B9100469330 /* ot_clean.h */,
128 65542F900CE17CA900469330 /* ot_fullscrape.h */,
129 65B8DF3A0D0310D20017149E /* ot_http.h */,
130 653A56B30CE28EC5000CF140 /* ot_iovec.h */,
131 65FA33970E7EF09200F7D5A5 /* ot_livesync.h */,
132 65542D900CE07CED00469330 /* ot_mutex.h */,
133 65542D920CE07CED00469330 /* ot_stats.h */,
134 65542EE60CE0CA6B00469330 /* ot_udp.h */,
135 65542D890CE078E800469330 /* ot_vector.h */,
136 654A80860CD832FC009035DE /* scan_urlencoded_query.h */,
137 654A80880CD832FC009035DE /* trackerlogic.h */,
138 );
139 name = Headers;
140 sourceTree = "<group>";
141 };
142 92762AC9104EDED700FDCB60 /* Libraries */ = {
143 isa = PBXGroup;
144 children = (
145 6520B7520D036AAF00A43B1F /* libowfat.a */,
146 );
147 name = Libraries;
148 sourceTree = "<group>";
149 };
150 C6A0FF2B0290797F04C91782 /* Documentation */ = {
151 isa = PBXGroup;
152 children = (
153 C6A0FF2C0290799A04C91782 /* opentracker.1 */,
154 );
155 name = Documentation;
156 sourceTree = "<group>";
157 };
158/* End PBXGroup section */
159
160/* Begin PBXNativeTarget section */
161 8DD76FA90486AB0100D96B5E /* opentracker */ = {
162 isa = PBXNativeTarget;
163 buildConfigurationList = 1DEB928508733DD80010E9CD /* Build configuration list for PBXNativeTarget "opentracker" */;
164 buildPhases = (
165 8DD76FAB0486AB0100D96B5E /* Sources */,
166 8DD76FAD0486AB0100D96B5E /* Frameworks */,
167 8DD76FAF0486AB0100D96B5E /* CopyFiles */,
168 );
169 buildRules = (
170 );
171 dependencies = (
172 );
173 name = opentracker;
174 productInstallPath = "$(HOME)/bin";
175 productName = opentracker;
176 productReference = 653A56AC0CE201FF000CF140 /* opentracker */;
177 productType = "com.apple.product-type.tool";
178 };
179/* End PBXNativeTarget section */
180
181/* Begin PBXProject section */
182 08FB7793FE84155DC02AAC07 /* Project object */ = {
183 isa = PBXProject;
184 buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "opentracker" */;
185 compatibilityVersion = "Xcode 3.0";
186 hasScannedForEncodings = 1;
187 mainGroup = 08FB7794FE84155DC02AAC07 /* opentracker */;
188 productRefGroup = 653A56AD0CE201FF000CF140 /* Products */;
189 projectDirPath = "";
190 projectRoot = "";
191 targets = (
192 8DD76FA90486AB0100D96B5E /* opentracker */,
193 );
194 };
195/* End PBXProject section */
196
197/* Begin PBXSourcesBuildPhase section */
198 8DD76FAB0486AB0100D96B5E /* Sources */ = {
199 isa = PBXSourcesBuildPhase;
200 buildActionMask = 2147483647;
201 files = (
202 654A80890CD832FD009035DE /* opentracker.c in Sources */,
203 654A808A0CD832FD009035DE /* scan_urlencoded_query.c in Sources */,
204 654A808B0CD832FD009035DE /* trackerlogic.c in Sources */,
205 65542D8B0CE078E800469330 /* ot_vector.c in Sources */,
206 65542D930CE07CED00469330 /* ot_mutex.c in Sources */,
207 65542D940CE07CED00469330 /* ot_stats.c in Sources */,
208 65542E750CE08B9100469330 /* ot_clean.c in Sources */,
209 65542EE80CE0CA6B00469330 /* ot_udp.c in Sources */,
210 65542F920CE17CA900469330 /* ot_fullscrape.c in Sources */,
211 653A56B50CE28EC5000CF140 /* ot_iovec.c in Sources */,
212 653A320C0CE7F475007F0D03 /* ot_accesslist.c in Sources */,
213 65B8DF3C0D0310D20017149E /* ot_http.c in Sources */,
214 65FA33990E7EF09200F7D5A5 /* ot_livesync.c in Sources */,
215 );
216 runOnlyForDeploymentPostprocessing = 0;
217 };
218/* End PBXSourcesBuildPhase section */
219
220/* Begin XCBuildConfiguration section */
221 1DEB928608733DD80010E9CD /* Debug */ = {
222 isa = XCBuildConfiguration;
223 buildSettings = {
224 COPY_PHASE_STRIP = NO;
225 GCC_DYNAMIC_NO_PIC = NO;
226 GCC_ENABLE_FIX_AND_CONTINUE = YES;
227 GCC_MODEL_TUNING = G5;
228 GCC_OPTIMIZATION_LEVEL = 0;
229 INSTALL_PATH = /usr/local/bin;
230 LIBRARY_SEARCH_PATHS = (
231 "$(inherited)",
232 "\"$(SRCROOT)/../libowfat\"",
233 );
234 PRODUCT_NAME = opentracker;
235 ZERO_LINK = YES;
236 };
237 name = Debug;
238 };
239 1DEB928708733DD80010E9CD /* Release */ = {
240 isa = XCBuildConfiguration;
241 buildSettings = {
242 DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
243 GCC_ENABLE_FIX_AND_CONTINUE = YES;
244 GCC_MODEL_TUNING = G5;
245 INSTALL_PATH = /usr/local/bin;
246 LIBRARY_SEARCH_PATHS = (
247 "$(inherited)",
248 "\"$(SRCROOT)/../libowfat\"",
249 );
250 PRODUCT_NAME = opentracker;
251 };
252 name = Release;
253 };
254 1DEB928A08733DD80010E9CD /* Debug */ = {
255 isa = XCBuildConfiguration;
256 buildSettings = {
257 ARCHS = "$(ONLY_ACTIVE_ARCH_PRE_XCODE_3_1)";
258 GCC_PREPROCESSOR_DEFINITIONS = (
259 WANT_ACCESSLIST_WHITE,
260 WANT_IP_FROM_QUERY_STRING,
261 WANT_FULLSCRAPE,
262 );
263 GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
264 GCC_WARN_ABOUT_RETURN_TYPE = YES;
265 GCC_WARN_UNUSED_VARIABLE = YES;
266 HEADER_SEARCH_PATHS = ../libowfat/;
267 LIBRARY_SEARCH_PATHS = ../libowfat/;
268 ONLY_ACTIVE_ARCH_PRE_XCODE_3_1 = "$(NATIVE_ARCH_ACTUAL)";
269 PREBINDING = NO;
270 SDKROOT = "$(DEVELOPER_SDK_DIR)/MacOSX10.6.sdk";
271 };
272 name = Debug;
273 };
274 1DEB928B08733DD80010E9CD /* Release */ = {
275 isa = XCBuildConfiguration;
276 buildSettings = {
277 ARCHS = "$(ONLY_ACTIVE_ARCH_PRE_XCODE_3_1)";
278 DEAD_CODE_STRIPPING = NO;
279 GCC_PREPROCESSOR_DEFINITIONS = (
280 WANT_ACCESSLIST_WHITE,
281 WANT_IP_FROM_QUERY_STRING,
282 WANT_FULLSCRAPE,
283 );
284 GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
285 GCC_WARN_ABOUT_RETURN_TYPE = YES;
286 GCC_WARN_UNUSED_VARIABLE = YES;
287 HEADER_SEARCH_PATHS = ../libowfat/;
288 LIBRARY_SEARCH_PATHS = ../libowfat/;
289 ONLY_ACTIVE_ARCH_PRE_XCODE_3_1 = "$(NATIVE_ARCH_ACTUAL)";
290 PREBINDING = NO;
291 SDKROOT = "$(DEVELOPER_SDK_DIR)/MacOSX10.6.sdk";
292 ZERO_LINK = NO;
293 };
294 name = Release;
295 };
296/* End XCBuildConfiguration section */
297
298/* Begin XCConfigurationList section */
299 1DEB928508733DD80010E9CD /* Build configuration list for PBXNativeTarget "opentracker" */ = {
300 isa = XCConfigurationList;
301 buildConfigurations = (
302 1DEB928608733DD80010E9CD /* Debug */,
303 1DEB928708733DD80010E9CD /* Release */,
304 );
305 defaultConfigurationIsVisible = 0;
306 defaultConfigurationName = Release;
307 };
308 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "opentracker" */ = {
309 isa = XCConfigurationList;
310 buildConfigurations = (
311 1DEB928A08733DD80010E9CD /* Debug */,
312 1DEB928B08733DD80010E9CD /* Release */,
313 );
314 defaultConfigurationIsVisible = 0;
315 defaultConfigurationName = Release;
316 };
317/* End XCConfigurationList section */
318 };
319 rootObject = 08FB7793FE84155DC02AAC07 /* Project object */;
320}
diff --git a/ot_accesslist.c b/ot_accesslist.c
deleted file mode 100644
index cdb964d..0000000
--- a/ot_accesslist.c
+++ /dev/null
@@ -1,313 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <pthread.h>
8#include <stdlib.h>
9#include <string.h>
10#include <stdio.h>
11#include <signal.h>
12#include <unistd.h>
13
14/* Libowfat */
15#include "byte.h"
16#include "scan.h"
17#include "ip6.h"
18#include "mmap.h"
19
20/* Opentracker */
21#include "trackerlogic.h"
22#include "ot_accesslist.h"
23#include "ot_vector.h"
24
25/* GLOBAL VARIABLES */
26#ifdef WANT_ACCESSLIST
27 char *g_accesslist_filename;
28static ot_hash *g_accesslist;
29static size_t g_accesslist_size;
30static pthread_mutex_t g_accesslist_mutex;
31
32static int vector_compare_hash(const void *hash1, const void *hash2 ) {
33 return memcmp( hash1, hash2, OT_HASH_COMPARE_SIZE );
34}
35
36/* Read initial access list */
37static void accesslist_readfile( void ) {
38 ot_hash *info_hash, *accesslist_new = NULL;
39 char *map, *map_end, *read_offs;
40 size_t maplen;
41
42 if( ( map = mmap_read( g_accesslist_filename, &maplen ) ) == NULL ) {
43 char *wd = getcwd( NULL, 0 );
44 fprintf( stderr, "Warning: Can't open accesslist file: %s (but will try to create it later, if necessary and possible).\nPWD: %s\n", g_accesslist_filename, wd );
45 free( wd );
46 return;
47 }
48
49 /* You need at least 41 bytes to pass an info_hash, make enough room
50 for the maximum amount of them */
51 info_hash = accesslist_new = malloc( ( maplen / 41 ) * 20 );
52 if( !accesslist_new ) {
53 fprintf( stderr, "Warning: Not enough memory to allocate %zd bytes for accesslist buffer. May succeed later.\n", ( maplen / 41 ) * 20 );
54 return;
55 }
56
57 /* No use to scan if there's not enough room for another full info_hash */
58 map_end = map + maplen - 40;
59 read_offs = map;
60
61 /* We do ignore anything that is not of the form "^[:xdigit:]{40}[^:xdigit:].*" */
62 while( read_offs <= map_end ) {
63 int i;
64 for( i=0; i<(int)sizeof(ot_hash); ++i ) {
65 int eger1 = scan_fromhex( read_offs[ 2*i ] );
66 int eger2 = scan_fromhex( read_offs[ 1 + 2*i ] );
67 if( eger1 < 0 || eger2 < 0 )
68 break;
69 (*info_hash)[i] = eger1 * 16 + eger2;
70 }
71
72 if( i == sizeof(ot_hash) ) {
73 read_offs += 40;
74
75 /* Append accesslist to accesslist vector */
76 if( read_offs == map_end || scan_fromhex( *read_offs ) < 0 )
77 ++info_hash;
78 }
79
80 /* Find start of next line */
81 while( read_offs <= map_end && *(read_offs++) != '\n' );
82 }
83#ifdef _DEBUG
84 fprintf( stderr, "Added %zd info_hashes to accesslist\n", (size_t)(info_hash - accesslist_new) );
85#endif
86
87 mmap_unmap( map, maplen);
88
89 qsort( accesslist_new, info_hash - accesslist_new, sizeof( *info_hash ), vector_compare_hash );
90
91 /* Now exchange the accesslist vector in the least race condition prone way */
92 pthread_mutex_lock(&g_accesslist_mutex);
93 free( g_accesslist );
94 g_accesslist = accesslist_new;
95 g_accesslist_size = info_hash - accesslist_new;
96 pthread_mutex_unlock(&g_accesslist_mutex);
97}
98
99int accesslist_hashisvalid( ot_hash hash ) {
100 void *exactmatch;
101
102 /* Lock should hardly ever be contended */
103 pthread_mutex_lock(&g_accesslist_mutex);
104 exactmatch = bsearch( hash, g_accesslist, g_accesslist_size, OT_HASH_COMPARE_SIZE, vector_compare_hash );
105 pthread_mutex_unlock(&g_accesslist_mutex);
106
107#ifdef WANT_ACCESSLIST_BLACK
108 return exactmatch == NULL;
109#else
110 return exactmatch != NULL;
111#endif
112}
113
114static void * accesslist_worker( void * args ) {
115 int sig;
116 sigset_t signal_mask;
117
118 sigemptyset(&signal_mask);
119 sigaddset(&signal_mask, SIGHUP);
120
121 (void)args;
122
123 while( 1 ) {
124
125 /* Initial attempt to read accesslist */
126 accesslist_readfile( );
127
128 /* Wait for signals */
129 while( sigwait (&signal_mask, &sig) != 0 && sig != SIGHUP );
130 }
131 return NULL;
132}
133
134static pthread_t thread_id;
135void accesslist_init( ) {
136 pthread_mutex_init(&g_accesslist_mutex, NULL);
137 pthread_create( &thread_id, NULL, accesslist_worker, NULL );
138}
139
140void accesslist_deinit( void ) {
141 pthread_cancel( thread_id );
142 pthread_mutex_destroy(&g_accesslist_mutex);
143 free( g_accesslist );
144 g_accesslist = 0;
145 g_accesslist_size = 0;
146}
147#endif
148
149int address_in_net( const ot_ip6 address, const ot_net *net ) {
150 int bits = net->bits;
151 int result = memcmp( address, &net->address, bits >> 3 );
152 if( !result && ( bits & 7 ) )
153 result = ( ( 0x7f00 >> ( bits & 7 ) ) & address[bits>>3] ) - net->address[bits>>3];
154 return result == 0;
155}
156
157void *set_value_for_net( const ot_net *net, ot_vector *vector, const void *value, const size_t member_size ) {
158 size_t i;
159 int exactmatch;
160
161 /* Caller must have a concept of ot_net in it's member */
162 if( member_size < sizeof(ot_net) )
163 return 0;
164
165 /* Check each net in vector for overlap */
166 uint8_t *member = ((uint8_t*)vector->data);
167 for( i=0; i<vector->size; ++i ) {
168 if( address_in_net( *(ot_ip6*)member, net ) ||
169 address_in_net( net->address, (ot_net*)member ) )
170 return 0;
171 member += member_size;
172 }
173
174 member = vector_find_or_insert( vector, (void*)net, member_size, sizeof(ot_net), &exactmatch );
175 if( member ) {
176 memcpy( member, net, sizeof(ot_net));
177 memcpy( member + sizeof(ot_net), value, member_size - sizeof(ot_net));
178 }
179
180 return member;
181}
182
183/* Takes a vector filled with { ot_net net, uint8_t[x] value };
184 Returns value associated with the net, or NULL if not found */
185void *get_value_for_net( const ot_ip6 address, const ot_vector *vector, const size_t member_size ) {
186 int exactmatch;
187 /* This binary search will return a pointer to the first non-containing network... */
188 ot_net *net = binary_search( address, vector->data, vector->size, member_size, sizeof(ot_ip6), &exactmatch );
189 if( !net )
190 return NULL;
191 /* ... so we'll need to move back one step unless we've exactly hit the first address in network */
192 if( !exactmatch && ( (void*)net > vector->data ) )
193 --net;
194 if( !address_in_net( address, net ) )
195 return NULL;
196 return (void*)net;
197}
198
199#ifdef WANT_FULLLOG_NETWORKS
200static ot_vector g_lognets_list;
201ot_log *g_logchain_first, *g_logchain_last;
202
203static pthread_mutex_t g_lognets_list_mutex = PTHREAD_MUTEX_INITIALIZER;
204void loglist_add_network( const ot_net *net ) {
205 pthread_mutex_lock(&g_lognets_list_mutex);
206 set_value_for_net( net, &g_lognets_list, NULL, sizeof(ot_net));
207 pthread_mutex_unlock(&g_lognets_list_mutex);
208}
209
210void loglist_reset( ) {
211 pthread_mutex_lock(&g_lognets_list_mutex);
212 free( g_lognets_list.data );
213 g_lognets_list.data = 0;
214 g_lognets_list.size = g_lognets_list.space = 0;
215 pthread_mutex_unlock(&g_lognets_list_mutex);
216}
217
218int loglist_check_address( const ot_ip6 address ) {
219 int result;
220 pthread_mutex_lock(&g_lognets_list_mutex);
221 result = ( NULL != get_value_for_net( address, &g_lognets_list, sizeof(ot_net)) );
222 pthread_mutex_unlock(&g_lognets_list_mutex);
223 return result;
224}
225#endif
226
227#ifdef WANT_IP_FROM_PROXY
228typedef struct {
229 ot_net *proxy;
230 ot_vector networks;
231} ot_proxymap;
232
233static ot_vector g_proxies_list;
234static pthread_mutex_t g_proxies_list_mutex = PTHREAD_MUTEX_INITIALIZER;
235
236int proxylist_add_network( const ot_net *proxy, const ot_net *net ) {
237 ot_proxymap *map;
238 int exactmatch, result = 1;
239 pthread_mutex_lock(&g_proxies_list_mutex);
240
241 /* If we have a direct hit, use and extend the vector there */
242 map = binary_search( proxy, g_proxies_list.data, g_proxies_list.size, sizeof(ot_proxymap), sizeof(ot_net), &exactmatch );
243
244 if( !map || !exactmatch ) {
245 /* else see, if we've got overlapping networks
246 and get a new empty vector if not */
247 ot_vector empty;
248 memset( &empty, 0, sizeof( ot_vector ) );
249 map = set_value_for_net( proxy, &g_proxies_list, &empty, sizeof(ot_proxymap));
250 }
251
252 if( map && set_value_for_net( net, &map->networks, NULL, sizeof(ot_net) ) )
253 result = 1;
254
255 pthread_mutex_unlock(&g_proxies_list_mutex);
256 return result;
257}
258
259int proxylist_check_proxy( const ot_ip6 proxy, const ot_ip6 address ) {
260 int result = 0;
261 ot_proxymap *map;
262
263 pthread_mutex_lock(&g_proxies_list_mutex);
264
265 if( ( map = get_value_for_net( proxy, &g_proxies_list, sizeof(ot_proxymap) ) ) )
266 if( !address || get_value_for_net( address, &map->networks, sizeof(ot_net) ) )
267 result = 1;
268
269 pthread_mutex_unlock(&g_proxies_list_mutex);
270 return result;
271}
272
273#endif
274
275static ot_ip6 g_adminip_addresses[OT_ADMINIP_MAX];
276static ot_permissions g_adminip_permissions[OT_ADMINIP_MAX];
277static unsigned int g_adminip_count = 0;
278
279int accesslist_blessip( ot_ip6 ip, ot_permissions permissions ) {
280 if( g_adminip_count >= OT_ADMINIP_MAX )
281 return -1;
282
283 memcpy(g_adminip_addresses + g_adminip_count,ip,sizeof(ot_ip6));
284 g_adminip_permissions[ g_adminip_count++ ] = permissions;
285
286#ifdef _DEBUG
287 {
288 char _debug[512];
289 int off = snprintf( _debug, sizeof(_debug), "Blessing ip address " );
290 off += fmt_ip6c(_debug+off, ip );
291
292 if( permissions & OT_PERMISSION_MAY_STAT ) off += snprintf( _debug+off, 512-off, " may_fetch_stats" );
293 if( permissions & OT_PERMISSION_MAY_LIVESYNC ) off += snprintf( _debug+off, 512-off, " may_sync_live" );
294 if( permissions & OT_PERMISSION_MAY_FULLSCRAPE ) off += snprintf( _debug+off, 512-off, " may_fetch_fullscrapes" );
295 if( permissions & OT_PERMISSION_MAY_PROXY ) off += snprintf( _debug+off, 512-off, " may_proxy" );
296 if( !permissions ) off += snprintf( _debug+off, sizeof(_debug)-off, " nothing\n" );
297 _debug[off++] = '.';
298 write( 2, _debug, off );
299 }
300#endif
301
302 return 0;
303}
304
305int accesslist_isblessed( ot_ip6 ip, ot_permissions permissions ) {
306 unsigned int i;
307 for( i=0; i<g_adminip_count; ++i )
308 if( !memcmp( g_adminip_addresses + i, ip, sizeof(ot_ip6)) && ( g_adminip_permissions[ i ] & permissions ) )
309 return 1;
310 return 0;
311}
312
313const char *g_version_accesslist_c = "$Source$: $Revision$\n";
diff --git a/ot_accesslist.h b/ot_accesslist.h
deleted file mode 100644
index b38b91a..0000000
--- a/ot_accesslist.h
+++ /dev/null
@@ -1,79 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_ACCESSLIST_H__
7#define OT_ACCESSLIST_H__
8
9#if defined ( WANT_ACCESSLIST_BLACK ) && defined (WANT_ACCESSLIST_WHITE )
10# error WANT_ACCESSLIST_BLACK and WANT_ACCESSLIST_WHITE are exclusive.
11#endif
12
13#if defined ( WANT_ACCESSLIST_BLACK ) || defined (WANT_ACCESSLIST_WHITE )
14#define WANT_ACCESSLIST
15void accesslist_init( );
16void accesslist_deinit( );
17int accesslist_hashisvalid( ot_hash hash );
18
19extern char *g_accesslist_filename;
20
21#else
22#define accesslist_init( accesslist_filename )
23#define accesslist_deinit( )
24#define accesslist_hashisvalid( hash ) 1
25#endif
26
27/* Test if an address is subset of an ot_net, return value is considered a bool */
28int address_in_net( const ot_ip6 address, const ot_net *net );
29
30/* Store a value into a vector of struct { ot_net net, uint8_t[x] value } member;
31 returns NULL
32 if member_size is too small, or
33 if one of the nets inside the vector are a subnet of _net_, or
34 if _net_ is a subnet of one of the nets inside the vector, or
35 if the vector could not be resized
36 returns pointer to new member in vector for success
37 member_size can be sizeof(ot_net) to reduce the lookup to a boolean mapping
38*/
39void *set_value_for_net( const ot_net *net, ot_vector *vector, const void *value, const size_t member_size );
40
41/* Takes a vector filled with struct { ot_net net, uint8_t[x] value } member;
42 Returns pointer to _member_ associated with the net, or NULL if not found
43 member_size can be sizeof(ot_net) to reduce the lookup to a boolean mapping
44*/
45void *get_value_for_net( const ot_ip6 address, const ot_vector *vector, const size_t member_size );
46
47
48#ifdef WANT_IP_FROM_PROXY
49int proxylist_add_network( const ot_net *proxy, const ot_net *net );
50int proxylist_check_network( const ot_ip6 *proxy, const ot_ip6 address /* can be NULL to only check proxy */ );
51#endif
52
53#ifdef WANT_FULLLOG_NETWORKS
54typedef struct ot_log ot_log;
55struct ot_log {
56 ot_ip6 ip;
57 uint8_t *data;
58 size_t size;
59 ot_time time;
60 ot_log *next;
61};
62extern ot_log *g_logchain_first, *g_logchain_last;
63
64void loglist_add_network( const ot_net *net );
65void loglist_reset( );
66int loglist_check_address( const ot_ip6 address );
67#endif
68
69typedef enum {
70 OT_PERMISSION_MAY_FULLSCRAPE = 0x1,
71 OT_PERMISSION_MAY_STAT = 0x2,
72 OT_PERMISSION_MAY_LIVESYNC = 0x4,
73 OT_PERMISSION_MAY_PROXY = 0x8
74} ot_permissions;
75
76int accesslist_blessip( ot_ip6 ip, ot_permissions permissions );
77int accesslist_isblessed( ot_ip6 ip, ot_permissions permissions );
78
79#endif
diff --git a/ot_clean.c b/ot_clean.c
deleted file mode 100644
index 4c03416..0000000
--- a/ot_clean.c
+++ /dev/null
@@ -1,139 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <pthread.h>
8#include <unistd.h>
9#include <string.h>
10
11/* Libowfat */
12#include "io.h"
13
14/* Opentracker */
15#include "trackerlogic.h"
16#include "ot_mutex.h"
17#include "ot_vector.h"
18#include "ot_clean.h"
19#include "ot_stats.h"
20
21/* Returns amount of removed peers */
22static ssize_t clean_single_bucket( ot_peer *peers, size_t peer_count, time_t timedout, int *removed_seeders ) {
23 ot_peer *last_peer = peers + peer_count, *insert_point;
24 time_t timediff;
25
26 /* Two scan modes: unless there is one peer removed, just increase ot_peertime */
27 while( peers < last_peer ) {
28 if( ( timediff = timedout + OT_PEERTIME( peers ) ) >= OT_PEER_TIMEOUT )
29 break;
30 OT_PEERTIME( peers++ ) = timediff;
31 }
32
33 /* If we at least remove one peer, we have to copy */
34 insert_point = peers;
35 while( peers < last_peer )
36 if( ( timediff = timedout + OT_PEERTIME( peers ) ) < OT_PEER_TIMEOUT ) {
37 OT_PEERTIME( peers ) = timediff;
38 memcpy( insert_point++, peers++, sizeof(ot_peer));
39 } else
40 if( OT_PEERFLAG( peers++ ) & PEER_FLAG_SEEDING )
41 (*removed_seeders)++;
42
43 return peers - insert_point;
44}
45
46/* Clean a single torrent
47 return 1 if torrent timed out
48*/
49int clean_single_torrent( ot_torrent *torrent ) {
50 ot_peerlist *peer_list = torrent->peer_list;
51 ot_vector *bucket_list = &peer_list->peers;
52 time_t timedout = (time_t)( g_now_minutes - peer_list->base );
53 int num_buckets = 1, removed_seeders = 0;
54
55 /* No need to clean empty torrent */
56 if( !timedout )
57 return 0;
58
59 /* Torrent has idled out */
60 if( timedout > OT_TORRENT_TIMEOUT )
61 return 1;
62
63 /* Nothing to be cleaned here? Test if torrent is worth keeping */
64 if( timedout > OT_PEER_TIMEOUT ) {
65 if( !peer_list->peer_count )
66 return peer_list->down_count ? 0 : 1;
67 timedout = OT_PEER_TIMEOUT;
68 }
69
70 if( OT_PEERLIST_HASBUCKETS( peer_list ) ) {
71 num_buckets = bucket_list->size;
72 bucket_list = (ot_vector *)bucket_list->data;
73 }
74
75 while( num_buckets-- ) {
76 size_t removed_peers = clean_single_bucket( bucket_list->data, bucket_list->size, timedout, &removed_seeders );
77 peer_list->peer_count -= removed_peers;
78 bucket_list->size -= removed_peers;
79 if( bucket_list->size < removed_peers )
80 vector_fixup_peers( bucket_list );
81 ++bucket_list;
82 }
83
84 peer_list->seed_count -= removed_seeders;
85
86 /* See, if we need to convert a torrent from simple vector to bucket list */
87 if( ( peer_list->peer_count > OT_PEER_BUCKET_MINCOUNT ) || OT_PEERLIST_HASBUCKETS(peer_list) )
88 vector_redistribute_buckets( peer_list );
89
90 if( peer_list->peer_count )
91 peer_list->base = g_now_minutes;
92 else {
93 /* When we got here, the last time that torrent
94 has been touched is OT_PEER_TIMEOUT Minutes before */
95 peer_list->base = g_now_minutes - OT_PEER_TIMEOUT;
96 }
97 return 0;
98
99}
100
101/* Clean up all peers in current bucket, remove timedout pools and
102 torrents */
103static void * clean_worker( void * args ) {
104 (void) args;
105 while( 1 ) {
106 int bucket = OT_BUCKET_COUNT;
107 while( bucket-- ) {
108 ot_vector *torrents_list = mutex_bucket_lock( bucket );
109 size_t toffs;
110 int delta_torrentcount = 0;
111
112 for( toffs=0; toffs<torrents_list->size; ++toffs ) {
113 ot_torrent *torrent = ((ot_torrent*)(torrents_list->data)) + toffs;
114 if( clean_single_torrent( torrent ) ) {
115 vector_remove_torrent( torrents_list, torrent );
116 --delta_torrentcount;
117 --toffs;
118 }
119 }
120 mutex_bucket_unlock( bucket, delta_torrentcount );
121 if( !g_opentracker_running )
122 return NULL;
123 usleep( OT_CLEAN_SLEEP );
124 }
125 stats_cleanup();
126 }
127 return NULL;
128}
129
130static pthread_t thread_id;
131void clean_init( void ) {
132 pthread_create( &thread_id, NULL, clean_worker, NULL );
133}
134
135void clean_deinit( void ) {
136 pthread_cancel( thread_id );
137}
138
139const char *g_version_clean_c = "$Source$: $Revision$\n";
diff --git a/ot_clean.h b/ot_clean.h
deleted file mode 100644
index 956770a..0000000
--- a/ot_clean.h
+++ /dev/null
@@ -1,19 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_CLEAN_H__
7#define OT_CLEAN_H__
8
9/* The amount of time a clean cycle should take */
10#define OT_CLEAN_INTERVAL_MINUTES 2
11
12/* So after each bucket wait 1 / OT_BUCKET_COUNT intervals */
13#define OT_CLEAN_SLEEP ( ( ( OT_CLEAN_INTERVAL_MINUTES ) * 60 * 1000000 ) / ( OT_BUCKET_COUNT ) )
14
15void clean_init( void );
16void clean_deinit( void );
17int clean_single_torrent( ot_torrent *torrent );
18
19#endif
diff --git a/ot_fullscrape.c b/ot_fullscrape.c
deleted file mode 100644
index faea4b9..0000000
--- a/ot_fullscrape.c
+++ /dev/null
@@ -1,249 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifdef WANT_FULLSCRAPE
7
8/* System */
9#include <sys/param.h>
10#include <stdio.h>
11#include <string.h>
12#include <pthread.h>
13#include <arpa/inet.h>
14#ifdef WANT_COMPRESSION_GZIP
15#include <zlib.h>
16#endif
17
18/* Libowfat */
19#include "byte.h"
20#include "io.h"
21#include "textcode.h"
22
23/* Opentracker */
24#include "trackerlogic.h"
25#include "ot_mutex.h"
26#include "ot_iovec.h"
27#include "ot_fullscrape.h"
28
29/* Fetch full scrape info for all torrents
30 Full scrapes usually are huge and one does not want to
31 allocate more memory. So lets get them in 512k units
32*/
33#define OT_SCRAPE_CHUNK_SIZE (512*1024)
34
35/* "d8:completei%zde10:downloadedi%zde10:incompletei%zdee" */
36#define OT_SCRAPE_MAXENTRYLEN 256
37
38#ifdef WANT_COMPRESSION_GZIP
39#define IF_COMPRESSION( TASK ) if( mode & TASK_FLAG_GZIP ) TASK
40#define WANT_COMPRESSION_GZIP_PARAM( param1, param2, param3 ) , param1, param2, param3
41#else
42#define IF_COMPRESSION( TASK )
43#define WANT_COMPRESSION_GZIP_PARAM( param1, param2, param3 )
44#endif
45
46/* Forward declaration */
47static void fullscrape_make( int *iovec_entries, struct iovec **iovector, ot_tasktype mode );
48
49/* Converter function from memory to human readable hex strings
50 XXX - Duplicated from ot_stats. Needs fix. */
51static char*to_hex(char*d,uint8_t*s){char*m="0123456789ABCDEF";char *t=d;char*e=d+40;while(d<e){*d++=m[*s>>4];*d++=m[*s++&15];}*d=0;return t;}
52
53/* This is the entry point into this worker thread
54 It grabs tasks from mutex_tasklist and delivers results back
55*/
56static void * fullscrape_worker( void * args ) {
57 int iovec_entries;
58 struct iovec *iovector;
59
60 (void) args;
61
62 while( 1 ) {
63 ot_tasktype tasktype = TASK_FULLSCRAPE;
64 ot_taskid taskid = mutex_workqueue_poptask( &tasktype );
65 fullscrape_make( &iovec_entries, &iovector, tasktype );
66 if( mutex_workqueue_pushresult( taskid, iovec_entries, iovector ) )
67 iovec_free( &iovec_entries, &iovector );
68 if( !g_opentracker_running )
69 return NULL;
70 }
71 return NULL;
72}
73
74static pthread_t thread_id;
75void fullscrape_init( ) {
76 pthread_create( &thread_id, NULL, fullscrape_worker, NULL );
77}
78
79void fullscrape_deinit( ) {
80 pthread_cancel( thread_id );
81}
82
83void fullscrape_deliver( int64 sock, ot_tasktype tasktype ) {
84 mutex_workqueue_pushtask( sock, tasktype );
85}
86
87static int fullscrape_increase( int *iovec_entries, struct iovec **iovector,
88 char **r, char **re WANT_COMPRESSION_GZIP_PARAM( z_stream *strm, ot_tasktype mode, int zaction ) ) {
89 /* Allocate a fresh output buffer at the end of our buffers list */
90 if( !( *r = iovec_fix_increase_or_free( iovec_entries, iovector, *r, OT_SCRAPE_CHUNK_SIZE ) ) ) {
91
92 /* Deallocate gzip buffers */
93 IF_COMPRESSION( deflateEnd(strm); )
94
95 /* Release lock on current bucket and return */
96 return -1;
97 }
98
99 /* Adjust new end of output buffer */
100 *re = *r + OT_SCRAPE_CHUNK_SIZE - OT_SCRAPE_MAXENTRYLEN;
101
102 /* When compressing, we have all the bytes in output buffer */
103#ifdef WANT_COMPRESSION_GZIP
104 if( mode & TASK_FLAG_GZIP ) {
105 int zres;
106 *re -= OT_SCRAPE_MAXENTRYLEN;
107 strm->next_out = (uint8_t*)*r;
108 strm->avail_out = OT_SCRAPE_CHUNK_SIZE;
109 zres = deflate( strm, zaction );
110 if( ( zres < Z_OK ) && ( zres != Z_BUF_ERROR ) )
111 fprintf( stderr, "deflate() failed while in fullscrape_increase(%d).\n", zaction );
112 *r = (char*)strm->next_out;
113 }
114#endif
115
116 return 0;
117}
118
119static void fullscrape_make( int *iovec_entries, struct iovec **iovector, ot_tasktype mode ) {
120 int bucket;
121 char *r, *re;
122#ifdef WANT_COMPRESSION_GZIP
123 char compress_buffer[OT_SCRAPE_MAXENTRYLEN];
124 z_stream strm;
125#endif
126
127 /* Setup return vector... */
128 *iovec_entries = 0;
129 *iovector = NULL;
130 if( !( r = iovec_increase( iovec_entries, iovector, OT_SCRAPE_CHUNK_SIZE ) ) )
131 return;
132
133 /* re points to low watermark */
134 re = r + OT_SCRAPE_CHUNK_SIZE - OT_SCRAPE_MAXENTRYLEN;
135
136#ifdef WANT_COMPRESSION_GZIP
137 if( mode & TASK_FLAG_GZIP ) {
138 re += OT_SCRAPE_MAXENTRYLEN;
139 byte_zero( &strm, sizeof(strm) );
140 strm.next_in = (uint8_t*)compress_buffer;
141 strm.next_out = (uint8_t*)r;
142 strm.avail_out = OT_SCRAPE_CHUNK_SIZE;
143 if( deflateInit2(&strm,7,Z_DEFLATED,31,8,Z_DEFAULT_STRATEGY) != Z_OK )
144 fprintf( stderr, "not ok.\n" );
145 r = compress_buffer;
146 }
147#endif
148
149 if( ( mode & TASK_TASK_MASK ) == TASK_FULLSCRAPE )
150 r += sprintf( r, "d5:filesd" );
151
152 /* For each bucket... */
153 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
154 /* Get exclusive access to that bucket */
155 ot_vector *torrents_list = mutex_bucket_lock( bucket );
156 size_t tor_offset;
157
158 /* For each torrent in this bucket.. */
159 for( tor_offset=0; tor_offset<torrents_list->size; ++tor_offset ) {
160 /* Address torrents members */
161 ot_peerlist *peer_list = ( ((ot_torrent*)(torrents_list->data))[tor_offset] ).peer_list;
162 ot_hash *hash =&( ((ot_torrent*)(torrents_list->data))[tor_offset] ).hash;
163
164 switch( mode & TASK_TASK_MASK ) {
165 case TASK_FULLSCRAPE:
166 default:
167 /* push hash as bencoded string */
168 *r++='2'; *r++='0'; *r++=':';
169 memcpy( r, hash, sizeof(ot_hash) ); r += sizeof(ot_hash);
170 /* push rest of the scrape string */
171 r += sprintf( r, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee", peer_list->seed_count, peer_list->down_count, peer_list->peer_count-peer_list->seed_count );
172
173 break;
174 case TASK_FULLSCRAPE_TPB_ASCII:
175 to_hex( r, *hash ); r+= 2 * sizeof(ot_hash);
176 r += sprintf( r, ":%zd:%zd\n", peer_list->seed_count, peer_list->peer_count-peer_list->seed_count );
177 break;
178 case TASK_FULLSCRAPE_TPB_ASCII_PLUS:
179 to_hex( r, *hash ); r+= 2 * sizeof(ot_hash);
180 r += sprintf( r, ":%zd:%zd:%zd\n", peer_list->seed_count, peer_list->peer_count-peer_list->seed_count, peer_list->down_count );
181 break;
182 case TASK_FULLSCRAPE_TPB_BINARY:
183 memcpy( r, *hash, sizeof(ot_hash) ); r += sizeof(ot_hash);
184 *(uint32_t*)(r+0) = htonl( (uint32_t) peer_list->seed_count );
185 *(uint32_t*)(r+4) = htonl( (uint32_t)( peer_list->peer_count-peer_list->seed_count) );
186 r+=8;
187 break;
188 case TASK_FULLSCRAPE_TPB_URLENCODED:
189 r += fmt_urlencoded( r, (char *)*hash, 20 );
190 r += sprintf( r, ":%zd:%zd\n", peer_list->seed_count, peer_list->peer_count-peer_list->seed_count );
191 break;
192 case TASK_FULLSCRAPE_TRACKERSTATE:
193 to_hex( r, *hash ); r+= 2 * sizeof(ot_hash);
194 r += sprintf( r, ":%zd:%zd\n", peer_list->base, peer_list->down_count );
195 break;
196 }
197
198#ifdef WANT_COMPRESSION_GZIP
199 if( mode & TASK_FLAG_GZIP ) {
200 int zres;
201 strm.next_in = (uint8_t*)compress_buffer;
202 strm.avail_in = r - compress_buffer;
203 zres = deflate( &strm, Z_NO_FLUSH );
204 if( ( zres < Z_OK ) && ( zres != Z_BUF_ERROR ) )
205 fprintf( stderr, "deflate() failed while in fullscrape_make().\n" );
206 r = (char*)strm.next_out;
207 }
208#endif
209
210 /* Check if there still is enough buffer left */
211 while( r >= re )
212 if( fullscrape_increase( iovec_entries, iovector, &r, &re WANT_COMPRESSION_GZIP_PARAM( &strm, mode, Z_NO_FLUSH ) ) )
213 return mutex_bucket_unlock( bucket, 0 );
214
215 IF_COMPRESSION( r = compress_buffer; )
216 }
217
218 /* All torrents done: release lock on current bucket */
219 mutex_bucket_unlock( bucket, 0 );
220
221 /* Parent thread died? */
222 if( !g_opentracker_running )
223 return;
224 }
225
226 if( ( mode & TASK_TASK_MASK ) == TASK_FULLSCRAPE )
227 r += sprintf( r, "ee" );
228
229#ifdef WANT_COMPRESSION_GZIP
230 if( mode & TASK_FLAG_GZIP ) {
231 strm.next_in = (uint8_t*)compress_buffer;
232 strm.avail_in = r - compress_buffer;
233 if( deflate( &strm, Z_FINISH ) < Z_OK )
234 fprintf( stderr, "deflate() failed while in fullscrape_make()'s endgame.\n" );
235 r = (char*)strm.next_out;
236
237 while( r >= re )
238 if( fullscrape_increase( iovec_entries, iovector, &r, &re WANT_COMPRESSION_GZIP_PARAM( &strm, mode, Z_FINISH ) ) )
239 return mutex_bucket_unlock( bucket, 0 );
240 deflateEnd(&strm);
241 }
242#endif
243
244 /* Release unused memory in current output buffer */
245 iovec_fixlast( iovec_entries, iovector, r );
246}
247#endif
248
249const char *g_version_fullscrape_c = "$Source$: $Revision$\n";
diff --git a/ot_fullscrape.h b/ot_fullscrape.h
deleted file mode 100644
index 0f920ec..0000000
--- a/ot_fullscrape.h
+++ /dev/null
@@ -1,22 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_FULLSCRAPE_H__
7#define OT_FULLSCRAPE_H__
8
9#ifdef WANT_FULLSCRAPE
10
11void fullscrape_init( );
12void fullscrape_deinit( );
13void fullscrape_deliver( int64 sock, ot_tasktype tasktype );
14
15#else
16
17#define fullscrape_init()
18#define fullscrape_deinit()
19
20#endif
21
22#endif
diff --git a/ot_http.c b/ot_http.c
deleted file mode 100644
index e05db72..0000000
--- a/ot_http.c
+++ /dev/null
@@ -1,635 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <sys/types.h>
8#include <arpa/inet.h>
9#include <stdlib.h>
10#include <stdio.h>
11#include <string.h>
12#include <unistd.h>
13#include <pthread.h>
14
15/* Libowfat */
16#include "byte.h"
17#include "array.h"
18#include "iob.h"
19#include "ip6.h"
20#include "scan.h"
21#include "case.h"
22
23/* Opentracker */
24#include "trackerlogic.h"
25#include "ot_mutex.h"
26#include "ot_http.h"
27#include "ot_iovec.h"
28#include "scan_urlencoded_query.h"
29#include "ot_fullscrape.h"
30#include "ot_stats.h"
31#include "ot_accesslist.h"
32
33#define OT_MAXMULTISCRAPE_COUNT 64
34extern char *g_redirecturl;
35
36char *g_stats_path;
37ssize_t g_stats_path_len;
38
39enum {
40 SUCCESS_HTTP_HEADER_LENGTH = 80,
41 SUCCESS_HTTP_HEADER_LENGTH_CONTENT_ENCODING = 32,
42 SUCCESS_HTTP_SIZE_OFF = 17 };
43
44static void http_senddata( const int64 sock, struct ot_workstruct *ws ) {
45 struct http_data *cookie = io_getcookie( sock );
46 ssize_t written_size;
47
48 if( !cookie ) { io_close(sock); return; }
49
50 /* whoever sends data is not interested in its input-array */
51 if( ws->keep_alive && ws->header_size != ws->request_size ) {
52 size_t rest = ws->request_size - ws->header_size;
53 if( array_start(&cookie->request) ) {
54 memmove( array_start(&cookie->request), ws->request + ws->header_size, rest );
55 array_truncate( &cookie->request, 1, rest );
56 } else
57 array_catb(&cookie->request, ws->request + ws->header_size, rest );
58 } else
59 array_reset( &cookie->request );
60
61 written_size = write( sock, ws->reply, ws->reply_size );
62 if( ( written_size < 0 ) || ( ( written_size == ws->reply_size ) && !ws->keep_alive ) ) {
63 array_reset( &cookie->request );
64 free( cookie ); io_close( sock ); return;
65 }
66
67 if( written_size < ws->reply_size ) {
68 char * outbuf;
69 tai6464 t;
70
71 if( !( outbuf = malloc( ws->reply_size - written_size ) ) ) {
72 array_reset( &cookie->request );
73 free(cookie); io_close( sock );
74 return;
75 }
76
77 memcpy( outbuf, ws->reply + written_size, ws->reply_size - written_size );
78 iob_addbuf_free( &cookie->batch, outbuf, ws->reply_size - written_size );
79
80 /* writeable short data sockets just have a tcp timeout */
81 if( !ws->keep_alive ) {
82 taia_uint( &t, 0 ); io_timeout( sock, t );
83 io_dontwantread( sock );
84 }
85 io_wantwrite( sock );
86 }
87}
88
89#define HTTPERROR_302 return http_issue_error( sock, ws, CODE_HTTPERROR_302 )
90#define HTTPERROR_400 return http_issue_error( sock, ws, CODE_HTTPERROR_400 )
91#define HTTPERROR_400_PARAM return http_issue_error( sock, ws, CODE_HTTPERROR_400_PARAM )
92#define HTTPERROR_400_COMPACT return http_issue_error( sock, ws, CODE_HTTPERROR_400_COMPACT )
93#define HTTPERROR_400_DOUBLEHASH return http_issue_error( sock, ws, CODE_HTTPERROR_400_PARAM )
94#define HTTPERROR_402_NOTMODEST return http_issue_error( sock, ws, CODE_HTTPERROR_402_NOTMODEST )
95#define HTTPERROR_403_IP return http_issue_error( sock, ws, CODE_HTTPERROR_403_IP )
96#define HTTPERROR_404 return http_issue_error( sock, ws, CODE_HTTPERROR_404 )
97#define HTTPERROR_500 return http_issue_error( sock, ws, CODE_HTTPERROR_500 )
98ssize_t http_issue_error( const int64 sock, struct ot_workstruct *ws, int code ) {
99 char *error_code[] = { "302 Found", "400 Invalid Request", "400 Invalid Request", "400 Invalid Request", "402 Payment Required",
100 "403 Not Modest", "403 Access Denied", "404 Not Found", "500 Internal Server Error" };
101 char *title = error_code[code];
102
103 ws->reply = ws->outbuf;
104 if( code == CODE_HTTPERROR_302 )
105 ws->reply_size = snprintf( ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 302 Found\r\nContent-Length: 0\r\nLocation: %s\r\n\r\n", g_redirecturl );
106 else
107 ws->reply_size = snprintf( ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 %s\r\nContent-Type: text/html\r\nContent-Length: %zd\r\n\r\n<title>%s</title>\n", title, strlen(title)+16-4,title+4);
108
109#ifdef _DEBUG_HTTPERROR
110 fprintf( stderr, "DEBUG: invalid request was: %s\n", ws->debugbuf );
111#endif
112 stats_issue_event( EVENT_FAILED, FLAG_TCP, code );
113 http_senddata( sock, ws );
114 return ws->reply_size = -2;
115}
116
117ssize_t http_sendiovecdata( const int64 sock, struct ot_workstruct *ws, int iovec_entries, struct iovec *iovector ) {
118 struct http_data *cookie = io_getcookie( sock );
119 char *header;
120 int i;
121 size_t header_size, size = iovec_length( &iovec_entries, &iovector );
122 tai6464 t;
123
124 /* No cookie? Bad socket. Leave. */
125 if( !cookie ) {
126 iovec_free( &iovec_entries, &iovector );
127 HTTPERROR_500;
128 }
129
130 /* If this socket collected request in a buffer, free it now */
131 array_reset( &cookie->request );
132
133 /* If we came here, wait for the answer is over */
134 cookie->flag &= ~STRUCT_HTTP_FLAG_WAITINGFORTASK;
135
136 /* Our answers never are 0 vectors. Return an error. */
137 if( !iovec_entries ) {
138 HTTPERROR_500;
139 }
140
141 /* Prepare space for http header */
142 header = malloc( SUCCESS_HTTP_HEADER_LENGTH + SUCCESS_HTTP_HEADER_LENGTH_CONTENT_ENCODING );
143 if( !header ) {
144 iovec_free( &iovec_entries, &iovector );
145 HTTPERROR_500;
146 }
147
148 if( cookie->flag & STRUCT_HTTP_FLAG_GZIP )
149 header_size = sprintf( header, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Encoding: gzip\r\nContent-Length: %zd\r\n\r\n", size );
150 else if( cookie->flag & STRUCT_HTTP_FLAG_BZIP2 )
151 header_size = sprintf( header, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Encoding: bzip2\r\nContent-Length: %zd\r\n\r\n", size );
152 else
153 header_size = sprintf( header, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %zd\r\n\r\n", size );
154
155 iob_reset( &cookie->batch );
156 iob_addbuf_free( &cookie->batch, header, header_size );
157
158 /* Will move to ot_iovec.c */
159 for( i=0; i<iovec_entries; ++i )
160 iob_addbuf_munmap( &cookie->batch, iovector[i].iov_base, iovector[i].iov_len );
161 free( iovector );
162
163 /* writeable sockets timeout after 10 minutes */
164 taia_now( &t ); taia_addsec( &t, &t, OT_CLIENT_TIMEOUT_SEND );
165 io_timeout( sock, t );
166 io_dontwantread( sock );
167 io_wantwrite( sock );
168 return 0;
169}
170
171static ssize_t http_handle_stats( const int64 sock, struct ot_workstruct *ws, char *read_ptr ) {
172static const ot_keywords keywords_main[] =
173 { { "mode", 1 }, {"format", 2 }, { NULL, -3 } };
174static const ot_keywords keywords_mode[] =
175 { { "peer", TASK_STATS_PEERS }, { "conn", TASK_STATS_CONNS }, { "scrp", TASK_STATS_SCRAPE }, { "udp4", TASK_STATS_UDP }, { "tcp4", TASK_STATS_TCP },
176 { "busy", TASK_STATS_BUSY_NETWORKS }, { "torr", TASK_STATS_TORRENTS }, { "fscr", TASK_STATS_FULLSCRAPE },
177 { "s24s", TASK_STATS_SLASH24S }, { "tpbs", TASK_STATS_TPB }, { "herr", TASK_STATS_HTTPERRORS }, { "completed", TASK_STATS_COMPLETED },
178 { "top100", TASK_STATS_TOP100 }, { "top10", TASK_STATS_TOP10 }, { "renew", TASK_STATS_RENEW }, { "syncs", TASK_STATS_SYNCS }, { "version", TASK_STATS_VERSION },
179 { "everything", TASK_STATS_EVERYTHING }, { "statedump", TASK_FULLSCRAPE_TRACKERSTATE }, { "fulllog", TASK_STATS_FULLLOG },
180 { "woodpeckers", TASK_STATS_WOODPECKERS},
181#ifdef WANT_LOG_NUMWANT
182 { "numwants", TASK_STATS_NUMWANTS},
183#endif
184 { NULL, -3 } };
185static const ot_keywords keywords_format[] =
186 { { "bin", TASK_FULLSCRAPE_TPB_BINARY }, { "ben", TASK_FULLSCRAPE }, { "url", TASK_FULLSCRAPE_TPB_URLENCODED },
187 { "txt", TASK_FULLSCRAPE_TPB_ASCII }, { "txtp", TASK_FULLSCRAPE_TPB_ASCII_PLUS }, { NULL, -3 } };
188
189 int mode = TASK_STATS_PEERS, scanon = 1, format = 0;
190
191#ifdef WANT_RESTRICT_STATS
192 struct http_data *cookie = io_getcookie( sock );
193
194 if( !cookie || !accesslist_isblessed( cookie->ip, OT_PERMISSION_MAY_STAT ) )
195 HTTPERROR_403_IP;
196#endif
197
198 while( scanon ) {
199 switch( scan_find_keywords( keywords_main, &read_ptr, SCAN_SEARCHPATH_PARAM ) ) {
200 case -2: scanon = 0; break; /* TERMINATOR */
201 case -1: HTTPERROR_400_PARAM; /* PARSE ERROR */
202 case -3: scan_urlencoded_skipvalue( &read_ptr ); break;
203 case 1: /* matched "mode" */
204 if( ( mode = scan_find_keywords( keywords_mode, &read_ptr, SCAN_SEARCHPATH_VALUE ) ) <= 0 ) HTTPERROR_400_PARAM;
205 break;
206 case 2: /* matched "format" */
207 if( ( format = scan_find_keywords( keywords_format, &read_ptr, SCAN_SEARCHPATH_VALUE ) ) <= 0 ) HTTPERROR_400_PARAM;
208 break;
209 }
210 }
211
212#ifdef WANT_FULLSCRAPE
213 if( mode == TASK_FULLSCRAPE_TRACKERSTATE ) {
214 format = mode; mode = TASK_STATS_TPB;
215 }
216
217 if( mode == TASK_STATS_TPB ) {
218 struct http_data* cookie = io_getcookie( sock );
219 tai6464 t;
220#ifdef WANT_COMPRESSION_GZIP
221 ws->request[ws->request_size] = 0;
222#ifdef WANT_COMPRESSION_GZIP_ALWAYS
223 if( strstr( read_ptr - 1, "gzip" ) ) {
224#endif
225 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
226 format |= TASK_FLAG_GZIP;
227#ifdef WANT_COMPRESSION_GZIP_ALWAYS
228 }
229#endif
230#endif
231 /* Pass this task to the worker thread */
232 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK;
233
234 /* Clients waiting for us should not easily timeout */
235 taia_uint( &t, 0 ); io_timeout( sock, t );
236 fullscrape_deliver( sock, format );
237 io_dontwantread( sock );
238 return ws->reply_size = -2;
239 }
240#endif
241
242 /* default format for now */
243 if( ( mode & TASK_CLASS_MASK ) == TASK_STATS ) {
244 tai6464 t;
245 /* Complex stats also include expensive memory debugging tools */
246 taia_uint( &t, 0 ); io_timeout( sock, t );
247 stats_deliver( sock, mode );
248 return ws->reply_size = -2;
249 }
250
251 /* Simple stats can be answerred immediately */
252 return ws->reply_size = return_stats_for_tracker( ws->reply, mode, 0 );
253}
254
255#ifdef WANT_MODEST_FULLSCRAPES
256static pthread_mutex_t g_modest_fullscrape_mutex = PTHREAD_MUTEX_INITIALIZER;
257static ot_vector g_modest_fullscrape_timeouts;
258typedef struct { ot_ip6 ip; ot_time last_fullscrape; } ot_scrape_log;
259#endif
260
261#ifdef WANT_FULLSCRAPE
262static ssize_t http_handle_fullscrape( const int64 sock, struct ot_workstruct *ws ) {
263 struct http_data* cookie = io_getcookie( sock );
264 int format = 0;
265 tai6464 t;
266
267#ifdef WANT_MODEST_FULLSCRAPES
268 {
269 ot_scrape_log this_peer, *new_peer;
270 int exactmatch;
271 memcpy( this_peer.ip, cookie->ip, sizeof(ot_ip6));
272 this_peer.last_fullscrape = g_now_seconds;
273 pthread_mutex_lock(&g_modest_fullscrape_mutex);
274 new_peer = vector_find_or_insert( &g_modest_fullscrape_timeouts, &this_peer, sizeof(ot_scrape_log), sizeof(ot_ip6), &exactmatch );
275 if( !new_peer ) {
276 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
277 HTTPERROR_500;
278 }
279 if( exactmatch && ( this_peer.last_fullscrape - new_peer->last_fullscrape ) < OT_MODEST_PEER_TIMEOUT ) {
280 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
281 HTTPERROR_402_NOTMODEST;
282 }
283 memcpy( new_peer, &this_peer, sizeof(ot_scrape_log));
284 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
285 }
286#endif
287
288#ifdef WANT_COMPRESSION_GZIP
289 ws->request[ws->request_size-1] = 0;
290 if( strstr( ws->request, "gzip" ) ) {
291 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
292 format = TASK_FLAG_GZIP;
293 stats_issue_event( EVENT_FULLSCRAPE_REQUEST_GZIP, 0, (uintptr_t)cookie->ip );
294 } else
295#endif
296 stats_issue_event( EVENT_FULLSCRAPE_REQUEST, 0, (uintptr_t)cookie->ip );
297
298#ifdef _DEBUG_HTTPERROR
299 fprintf( stderr, "%s", ws->debugbuf );
300#endif
301
302 /* Pass this task to the worker thread */
303 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK;
304 /* Clients waiting for us should not easily timeout */
305 taia_uint( &t, 0 ); io_timeout( sock, t );
306 fullscrape_deliver( sock, TASK_FULLSCRAPE | format );
307 io_dontwantread( sock );
308 return ws->reply_size = -2;
309}
310#endif
311
312static ssize_t http_handle_scrape( const int64 sock, struct ot_workstruct *ws, char *read_ptr ) {
313 static const ot_keywords keywords_scrape[] = { { "info_hash", 1 }, { NULL, -3 } };
314
315 ot_hash * multiscrape_buf = (ot_hash*)ws->request;
316 int scanon = 1, numwant = 0;
317
318 /* This is to hack around stupid clients that send "scrape ?info_hash" */
319 if( read_ptr[-1] != '?' ) {
320 while( ( *read_ptr != '?' ) && ( *read_ptr != '\n' ) ) ++read_ptr;
321 if( *read_ptr == '\n' ) HTTPERROR_400_PARAM;
322 ++read_ptr;
323 }
324
325 while( scanon ) {
326 switch( scan_find_keywords( keywords_scrape, &read_ptr, SCAN_SEARCHPATH_PARAM ) ) {
327 case -2: scanon = 0; break; /* TERMINATOR */
328 default: HTTPERROR_400_PARAM; /* PARSE ERROR */
329 case -3: scan_urlencoded_skipvalue( &read_ptr ); break;
330 case 1: /* matched "info_hash" */
331 /* ignore this, when we have less than 20 bytes */
332 if( scan_urlencoded_query( &read_ptr, (char*)(multiscrape_buf + numwant++), SCAN_SEARCHPATH_VALUE ) != (ssize_t)sizeof(ot_hash) )
333 HTTPERROR_400_PARAM;
334 break;
335 }
336 }
337
338 /* No info_hash found? Inform user */
339 if( !numwant ) HTTPERROR_400_PARAM;
340
341 /* Limit number of hashes to process */
342 if( numwant > OT_MAXMULTISCRAPE_COUNT )
343 numwant = OT_MAXMULTISCRAPE_COUNT;
344
345 /* Enough for http header + whole scrape string */
346 ws->reply_size = return_tcp_scrape_for_torrent( multiscrape_buf, numwant, ws->reply );
347 stats_issue_event( EVENT_SCRAPE, FLAG_TCP, ws->reply_size );
348 return ws->reply_size;
349}
350
351#ifdef WANT_LOG_NUMWANT
352 unsigned long long numwants[201];
353#endif
354
355#if defined( WANT_KEEPALIVE ) || defined( WANT_IP_FROM_PROXY )
356static char* http_header( char *data, size_t byte_count, char *header ) {
357 size_t i;
358 long sl = strlen( header );
359 for( i = 0; i + sl + 2 < byte_count; ++i ) {
360 if( data[i] != '\n' || data[ i + sl + 1] != ':' ) continue;
361 if( !case_equalb( data + i + 1, sl, header ) ) continue;
362 data += i + sl + 2;
363 while( *data == ' ' || *data == '\t' ) ++data;
364 return data;
365 }
366 return 0;
367}
368#endif
369
370static ot_keywords keywords_announce[] = { { "port", 1 }, { "left", 2 }, { "event", 3 }, { "numwant", 4 }, { "compact", 5 }, { "compact6", 5 }, { "info_hash", 6 },
371#ifdef WANT_IP_FROM_QUERY_STRING
372{ "ip", 7 },
373#endif
374#ifdef WANT_FULLLOG_NETWORKS
375{ "lognet", 8 },
376#endif
377{ "peer_id", 9 },
378{ NULL, -3 } };
379static ot_keywords keywords_announce_event[] = { { "completed", 1 }, { "stopped", 2 }, { NULL, -3 } };
380static ssize_t http_handle_announce( const int64 sock, struct ot_workstruct *ws, char *read_ptr ) {
381 int numwant, tmp, scanon;
382 unsigned short port = 0;
383 char *write_ptr;
384 ssize_t len;
385 struct http_data *cookie = io_getcookie( sock );
386
387 /* This is to hack around stupid clients that send "announce ?info_hash" */
388 if( read_ptr[-1] != '?' ) {
389 while( ( *read_ptr != '?' ) && ( *read_ptr != '\n' ) ) ++read_ptr;
390 if( *read_ptr == '\n' ) HTTPERROR_400_PARAM;
391 ++read_ptr;
392 }
393
394#ifdef WANT_IP_FROM_PROXY
395 if( accesslist_isblessed( cookie->ip, OT_PERMISSION_MAY_PROXY ) ) {
396 ot_ip6 proxied_ip;
397 char *fwd = http_header( ws->request, ws->header_size, "x-forwarded-for" );
398 if( fwd && scan_ip6( fwd, proxied_ip ) )
399 OT_SETIP( &ws->peer, proxied_ip );
400 else
401 OT_SETIP( &ws->peer, cookie->ip );
402 } else
403#endif
404 OT_SETIP( &ws->peer, cookie->ip );
405
406 ws->peer_id = NULL;
407 ws->hash = NULL;
408
409 OT_SETPORT( &ws->peer, &port );
410 OT_PEERFLAG( &ws->peer ) = 0;
411 numwant = 50;
412 scanon = 1;
413
414 while( scanon ) {
415 switch( scan_find_keywords(keywords_announce, &read_ptr, SCAN_SEARCHPATH_PARAM ) ) {
416 case -2: scanon = 0; break; /* TERMINATOR */
417 case -1: HTTPERROR_400_PARAM; /* PARSE ERROR */
418 case -3: scan_urlencoded_skipvalue( &read_ptr ); break;
419 case 1: /* matched "port" */
420 len = scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE );
421 if( ( len <= 0 ) || scan_fixed_int( write_ptr, len, &tmp ) || ( tmp > 0xffff ) ) HTTPERROR_400_PARAM;
422 port = htons( tmp ); OT_SETPORT( &ws->peer, &port );
423 break;
424 case 2: /* matched "left" */
425 if( ( len = scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE ) ) <= 0 ) HTTPERROR_400_PARAM;
426 if( scan_fixed_int( write_ptr, len, &tmp ) ) tmp = 0;
427 if( !tmp ) OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_SEEDING;
428 break;
429 case 3: /* matched "event" */
430 switch( scan_find_keywords( keywords_announce_event, &read_ptr, SCAN_SEARCHPATH_VALUE ) ) {
431 case -1: HTTPERROR_400_PARAM;
432 case 1: /* matched "completed" */
433 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_COMPLETED;
434 break;
435 case 2: /* matched "stopped" */
436 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_STOPPED;
437 break;
438 default:
439 break;
440 }
441 break;
442 case 4: /* matched "numwant" */
443 len = scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE );
444 if( ( len <= 0 ) || scan_fixed_int( write_ptr, len, &numwant ) ) HTTPERROR_400_PARAM;
445 if( numwant < 0 ) numwant = 50;
446 if( numwant > 200 ) numwant = 200;
447 break;
448 case 5: /* matched "compact" */
449 len = scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE );
450 if( ( len <= 0 ) || scan_fixed_int( write_ptr, len, &tmp ) ) HTTPERROR_400_PARAM;
451 if( !tmp ) HTTPERROR_400_COMPACT;
452 break;
453 case 6: /* matched "info_hash" */
454 if( ws->hash ) HTTPERROR_400_DOUBLEHASH;
455 /* ignore this, when we have less than 20 bytes */
456 if( scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE ) != 20 ) HTTPERROR_400_PARAM;
457 ws->hash = (ot_hash*)write_ptr;
458 break;
459#ifdef WANT_IP_FROM_QUERY_STRING
460 case 7: /* matched "ip" */
461 {
462 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply+16;
463 len = scan_urlencoded_query( &read_ptr, tmp_buf2, SCAN_SEARCHPATH_VALUE );
464 tmp_buf2[len] = 0;
465 if( ( len <= 0 ) || !scan_ip6( tmp_buf2, tmp_buf1 ) ) HTTPERROR_400_PARAM;
466 OT_SETIP( &ws->peer, tmp_buf1 );
467 }
468 break;
469#endif
470#ifdef WANT_FULLLOG_NETWORKS
471 case 8: /* matched "lognet" */
472 {
473 //if( accesslist_isblessed( cookie->ip, OT_PERMISSION_MAY_STAT ) ) {
474 char *tmp_buf = ws->reply;
475 ot_net net;
476 signed short parsed, bits;
477
478 len = scan_urlencoded_query( &read_ptr, tmp_buf, SCAN_SEARCHPATH_VALUE );
479 tmp_buf[len] = 0;
480 if( len <= 0 ) HTTPERROR_400_PARAM;
481 if( *tmp_buf == '-' ) {
482 loglist_reset( );
483 return ws->reply_size = sprintf( ws->reply, "Successfully removed.\n" );
484 }
485 parsed = scan_ip6( tmp_buf, net.address );
486 if( !parsed ) HTTPERROR_400_PARAM;
487 if( tmp_buf[parsed++] != '/' )
488 bits = 128;
489 else {
490 parsed = scan_short( tmp_buf + parsed, &bits );
491 if( !parsed ) HTTPERROR_400_PARAM;
492 if( ip6_isv4mapped( net.address ) )
493 bits += 96;
494 }
495 net.bits = bits;
496 loglist_add_network( &net );
497 return ws->reply_size = sprintf( ws->reply, "Successfully added.\n" );
498 //}
499 }
500 break;
501#endif
502 case 9: /* matched "peer_id" */
503 /* ignore this, when we have less than 20 bytes */
504 if( scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_SEARCHPATH_VALUE ) != 20 ) HTTPERROR_400_PARAM;
505 ws->peer_id = write_ptr;
506 break;
507 }
508 }
509
510#ifdef WANT_LOG_NUMWANT
511 numwants[numwant]++;
512#endif
513
514 /* XXX DEBUG
515 stats_issue_event( EVENT_ACCEPT, FLAG_TCP, (uintptr_t)ws->reply );
516 */
517
518 /* Scanned whole query string */
519 if( !ws->hash )
520 return ws->reply_size = sprintf( ws->reply, "d14:failure reason80:Your client forgot to send your torrent's info_hash. Please upgrade your client.e" );
521
522 if( OT_PEERFLAG( &ws->peer ) & PEER_FLAG_STOPPED )
523 ws->reply_size = remove_peer_from_torrent( FLAG_TCP, ws );
524 else
525 ws->reply_size = add_peer_to_torrent_and_return_peers( FLAG_TCP, ws, numwant );
526
527 stats_issue_event( EVENT_ANNOUNCE, FLAG_TCP, ws->reply_size);
528 return ws->reply_size;
529}
530
531ssize_t http_handle_request( const int64 sock, struct ot_workstruct *ws ) {
532 ssize_t reply_off, len;
533 char *read_ptr = ws->request, *write_ptr;
534
535#ifdef WANT_FULLLOG_NETWORKS
536 struct http_data *cookie = io_getcookie( sock );
537 if( loglist_check_address( cookie->ip ) ) {
538 ot_log *log = malloc( sizeof( ot_log ) );
539 if( log ) {
540 log->size = ws->request_size;
541 log->data = malloc( ws->request_size );
542 log->next = 0;
543 log->time = g_now_seconds;
544 memcpy( log->ip, cookie->ip, sizeof(ot_ip6));
545 if( log->data ) {
546 memcpy( log->data, ws->request, ws->request_size );
547 if( !g_logchain_first )
548 g_logchain_first = g_logchain_last = log;
549 else {
550 g_logchain_last->next = log;
551 g_logchain_last = log;
552 }
553 } else
554 free( log );
555 }
556 }
557#endif
558
559#ifdef _DEBUG_HTTPERROR
560 reply_off = ws->request_size;
561 if( ws->request_size >= G_DEBUGBUF_SIZE )
562 reply_off = G_DEBUGBUF_SIZE - 1;
563 memcpy( ws->debugbuf, ws->request, reply_off );
564 ws->debugbuf[ reply_off ] = 0;
565#endif
566
567 /* Tell subroutines where to put reply data */
568 ws->reply = ws->outbuf + SUCCESS_HTTP_HEADER_LENGTH;
569
570 /* This one implicitely tests strlen < 5, too -- remember, it is \n terminated */
571 if( memcmp( read_ptr, "GET /", 5) ) HTTPERROR_400;
572
573 /* Skip leading '/' */
574 for( read_ptr+=4; *read_ptr == '/'; ++read_ptr);
575
576 /* Try to parse the request.
577 In reality we abandoned requiring the url to be correct. This now
578 only decodes url encoded characters, we check for announces and
579 scrapes by looking for "a*" or "sc" */
580 len = scan_urlencoded_query( &read_ptr, write_ptr = read_ptr, SCAN_PATH );
581
582 /* If parsing returned an error, leave with not found */
583 if( g_redirecturl && ( len == -2 ) ) HTTPERROR_302;
584 if( len <= 0 ) HTTPERROR_404;
585
586 /* This is the hardcore match for announce*/
587 if( ( *write_ptr == 'a' ) || ( *write_ptr == '?' ) )
588 http_handle_announce( sock, ws, read_ptr );
589#ifdef WANT_FULLSCRAPE
590 else if( !memcmp( write_ptr, "scrape HTTP/", 12 ) )
591 http_handle_fullscrape( sock, ws );
592#endif
593 /* This is the hardcore match for scrape */
594 else if( !memcmp( write_ptr, "sc", 2 ) )
595 http_handle_scrape( sock, ws, read_ptr );
596 /* All the rest is matched the standard way */
597 else if( len == g_stats_path_len && !memcmp( write_ptr, g_stats_path, len ) )
598 http_handle_stats( sock, ws, read_ptr );
599 else
600 HTTPERROR_404;
601
602 /* Find out if the client wants to keep this connection alive */
603 ws->keep_alive = 0;
604#ifdef WANT_KEEPALIVE
605 read_ptr=http_header( ws->request, ws->header_size, "connection");
606 if( read_ptr && ( *read_ptr == 'K' || *read_ptr == 'k' ) ) ws->keep_alive = 1;
607#endif
608
609 /* If routines handled sending themselves, just return */
610 if( ws->reply_size == -2 ) return 0;
611 /* If routine failed, let http error take over */
612 if( ws->reply_size <= 0 ) HTTPERROR_500;
613
614 /* This one is rather ugly, so I take you step by step through it.
615
616 1. In order to avoid having two buffers, one for header and one for content, we allow all above functions from trackerlogic to
617 write to a fixed location, leaving SUCCESS_HTTP_HEADER_LENGTH bytes in our work buffer, which is enough for the static string
618 plus dynamic space needed to expand our Content-Length value. We reserve SUCCESS_HTTP_SIZE_OFF for its expansion and calculate
619 the space NOT needed to expand in reply_off
620 */
621 reply_off = SUCCESS_HTTP_SIZE_OFF - snprintf( ws->outbuf, 0, "%zd", ws->reply_size );
622 ws->reply = ws->outbuf + reply_off;
623
624 /* 2. Now we sprintf our header so that sprintf writes its terminating '\0' exactly one byte before content starts. Complete
625 packet size is increased by size of header plus one byte '\n', we will copy over '\0' in next step */
626 ws->reply_size += 1 + sprintf( ws->reply, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %zd\r\n\r", ws->reply_size );
627
628 /* 3. Finally we join both blocks neatly */
629 ws->outbuf[ SUCCESS_HTTP_HEADER_LENGTH - 1 ] = '\n';
630
631 http_senddata( sock, ws );
632 return ws->reply_size;
633}
634
635const char *g_version_http_c = "$Source$: $Revision$\n";
diff --git a/ot_http.h b/ot_http.h
deleted file mode 100644
index b1a60e7..0000000
--- a/ot_http.h
+++ /dev/null
@@ -1,29 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_HTTP_H__
7#define OT_HTTP_H__
8
9typedef enum {
10 STRUCT_HTTP_FLAG_WAITINGFORTASK = 1,
11 STRUCT_HTTP_FLAG_GZIP = 2,
12 STRUCT_HTTP_FLAG_BZIP2 = 4
13} STRUCT_HTTP_FLAG;
14
15struct http_data {
16 array request;
17 io_batch batch;
18 ot_ip6 ip;
19 STRUCT_HTTP_FLAG flag;
20};
21
22ssize_t http_handle_request( const int64 s, struct ot_workstruct *ws );
23ssize_t http_sendiovecdata( const int64 s, struct ot_workstruct *ws, int iovec_entries, struct iovec *iovector );
24ssize_t http_issue_error( const int64 s, struct ot_workstruct *ws, int code );
25
26extern char *g_stats_path;
27extern ssize_t g_stats_path_len;
28
29#endif
diff --git a/ot_iovec.c b/ot_iovec.c
deleted file mode 100644
index ec0bd12..0000000
--- a/ot_iovec.c
+++ /dev/null
@@ -1,76 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <sys/types.h>
8#include <sys/mman.h>
9#include <stdlib.h>
10#include <unistd.h>
11#include <sys/uio.h>
12
13/* Libowfat */
14
15/* Opentracker */
16#include "ot_iovec.h"
17
18void *iovec_increase( int *iovec_entries, struct iovec **iovector, size_t new_alloc ) {
19 void *new_ptr = realloc( *iovector, (1 + *iovec_entries ) * sizeof( struct iovec ) );
20 if( !new_ptr )
21 return NULL;
22 *iovector = new_ptr;
23 new_ptr = mmap( NULL, new_alloc, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0 );
24 if( !new_ptr )
25 return NULL;
26 ((*iovector)[*iovec_entries]).iov_base = new_ptr;
27 ((*iovector)[*iovec_entries]).iov_len = new_alloc;
28 ++*iovec_entries;
29 return new_ptr;
30}
31
32void iovec_free( int *iovec_entries, struct iovec **iovector ) {
33 int i;
34 for( i=0; i<*iovec_entries; ++i )
35 munmap( ((*iovector)[i]).iov_base, ((*iovector)[i]).iov_len );
36 *iovec_entries = 0;
37}
38
39void iovec_fixlast( int *iovec_entries, struct iovec **iovector, void *last_ptr ) {
40 int page_size = getpagesize();
41 size_t old_alloc, new_alloc, old_pages, new_pages;
42 char * base = (char*)((*iovector)[ *iovec_entries - 1 ]).iov_base;
43
44 if( !*iovec_entries ) return;
45
46 old_alloc = ((*iovector)[ *iovec_entries - 1 ]).iov_len;
47 new_alloc = ((char*)last_ptr) - base;
48 old_pages = 1 + old_alloc / page_size;
49 new_pages = 1 + new_alloc / page_size;
50
51 if( old_pages != new_pages )
52 munmap( base + new_pages * page_size, old_alloc - new_pages * page_size );
53 ((*iovector)[*iovec_entries - 1 ]).iov_len = new_alloc;
54}
55
56void *iovec_fix_increase_or_free( int *iovec_entries, struct iovec **iovector, void *last_ptr, size_t new_alloc ) {
57 void *new_ptr;
58
59 iovec_fixlast( iovec_entries, iovector, last_ptr );
60
61 if( !( new_ptr = iovec_increase( iovec_entries, iovector, new_alloc ) ) )
62 iovec_free( iovec_entries, iovector );
63
64 return new_ptr;
65}
66
67
68size_t iovec_length( int *iovec_entries, struct iovec **iovector ) {
69 size_t length = 0;
70 int i;
71 for( i=0; i<*iovec_entries; ++i )
72 length += ((*iovector)[i]).iov_len;
73 return length;
74}
75
76const char *g_version_iovec_c = "$Source$: $Revision$\n";
diff --git a/ot_iovec.h b/ot_iovec.h
deleted file mode 100644
index 5dbe706..0000000
--- a/ot_iovec.h
+++ /dev/null
@@ -1,19 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_IOVEC_H__
7#define OT_IOVEC_H__
8
9#include <sys/uio.h>
10
11void *iovec_increase( int *iovec_entries, struct iovec **iovector, size_t new_alloc );
12void iovec_fixlast( int *iovec_entries, struct iovec **iovector, void *last_ptr );
13void iovec_free( int *iovec_entries, struct iovec **iovector );
14
15size_t iovec_length( int *iovec_entries, struct iovec **iovector );
16
17void *iovec_fix_increase_or_free( int *iovec_entries, struct iovec **iovector, void *last_ptr, size_t new_alloc );
18
19#endif
diff --git a/ot_livesync.c b/ot_livesync.c
deleted file mode 100644
index cded0f7..0000000
--- a/ot_livesync.c
+++ /dev/null
@@ -1,216 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <sys/types.h>
8#include <sys/uio.h>
9#include <string.h>
10#include <pthread.h>
11#include <unistd.h>
12#include <stdlib.h>
13
14/* Libowfat */
15#include "socket.h"
16#include "ndelay.h"
17#include "byte.h"
18#include "ip6.h"
19
20/* Opentracker */
21#include "trackerlogic.h"
22#include "ot_livesync.h"
23#include "ot_accesslist.h"
24#include "ot_stats.h"
25#include "ot_mutex.h"
26
27#ifdef WANT_SYNC_LIVE
28
29char groupip_1[4] = { 224,0,23,5 };
30
31#define LIVESYNC_INCOMING_BUFFSIZE (256*256)
32
33#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480
34#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_peer)+sizeof(ot_hash))
35
36#define LIVESYNC_MAXDELAY 15 /* seconds */
37
38enum { OT_SYNC_PEER };
39
40/* Forward declaration */
41static void * livesync_worker( void * args );
42
43/* For outgoing packets */
44static int64 g_socket_in = -1;
45
46/* For incoming packets */
47static int64 g_socket_out = -1;
48
49static pthread_mutex_t g_outbuf_mutex = PTHREAD_MUTEX_INITIALIZER;
50char g_outbuf[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
51static size_t g_outbuf_data;
52static ot_time g_next_packet_time;
53
54static pthread_t thread_id;
55void livesync_init( ) {
56
57 if( g_socket_in == -1 )
58 exerr( "No socket address for live sync specified." );
59
60 /* Prepare outgoing peers buffer */
61 memcpy( g_outbuf, &g_tracker_id, sizeof( g_tracker_id ) );
62 uint32_pack_big( g_outbuf + sizeof( g_tracker_id ), OT_SYNC_PEER);
63 g_outbuf_data = sizeof( g_tracker_id ) + sizeof( uint32_t );
64
65 g_next_packet_time = g_now_seconds + LIVESYNC_MAXDELAY;
66
67 pthread_create( &thread_id, NULL, livesync_worker, NULL );
68}
69
70void livesync_deinit() {
71 if( g_socket_in != -1 )
72 close( g_socket_in );
73 if( g_socket_out != -1 )
74 close( g_socket_out );
75
76 pthread_cancel( thread_id );
77}
78
79void livesync_bind_mcast( ot_ip6 ip, uint16_t port) {
80 char tmpip[4] = {0,0,0,0};
81 char *v4ip;
82
83 if( !ip6_isv4mapped(ip))
84 exerr("v6 mcast support not yet available.");
85 v4ip = ip+12;
86
87 if( g_socket_in != -1 )
88 exerr("Error: Livesync listen ip specified twice.");
89
90 if( ( g_socket_in = socket_udp4( )) < 0)
91 exerr("Error: Cant create live sync incoming socket." );
92 ndelay_off(g_socket_in);
93
94 if( socket_bind4_reuse( g_socket_in, tmpip, port ) == -1 )
95 exerr("Error: Cant bind live sync incoming socket." );
96
97 if( socket_mcjoin4( g_socket_in, groupip_1, v4ip ) )
98 exerr("Error: Cant make live sync incoming socket join mcast group.");
99
100 if( ( g_socket_out = socket_udp4()) < 0)
101 exerr("Error: Cant create live sync outgoing socket." );
102 if( socket_bind4_reuse( g_socket_out, v4ip, port ) == -1 )
103 exerr("Error: Cant bind live sync outgoing socket." );
104
105 socket_mcttl4(g_socket_out, 1);
106 socket_mcloop4(g_socket_out, 0);
107}
108
109/* Caller MUST hold g_outbuf_mutex. Returns with g_outbuf_mutex unlocked */
110static void livesync_issue_peersync( ) {
111 char mycopy[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
112 size_t data = g_outbuf_data;
113
114 memcpy( mycopy, g_outbuf, data );
115 g_outbuf_data = sizeof( g_tracker_id ) + sizeof( uint32_t );
116 g_next_packet_time = g_now_seconds + LIVESYNC_MAXDELAY;
117
118 /* From now this thread has a local copy of the buffer and
119 has modified the protected element */
120 pthread_mutex_unlock(&g_outbuf_mutex);
121
122 socket_send4(g_socket_out, mycopy, data, groupip_1, LIVESYNC_PORT);
123}
124
125static void livesync_handle_peersync( struct ot_workstruct *ws ) {
126 int off = sizeof( g_tracker_id ) + sizeof( uint32_t );
127
128 /* Now basic sanity checks have been done on the live sync packet
129 We might add more testing and logging. */
130 while( off + (ssize_t)sizeof( ot_hash ) + (ssize_t)sizeof( ot_peer ) <= ws->request_size ) {
131 memcpy( &ws->peer, ws->request + off + sizeof(ot_hash), sizeof( ot_peer ) );
132 ws->hash = (ot_hash*)(ws->request + off);
133
134 if( !g_opentracker_running ) return;
135
136 if( OT_PEERFLAG(&ws->peer) & PEER_FLAG_STOPPED )
137 remove_peer_from_torrent( FLAG_MCA, ws );
138 else
139 add_peer_to_torrent_and_return_peers( FLAG_MCA, ws, /* amount = */ 0 );
140
141 off += sizeof( ot_hash ) + sizeof( ot_peer );
142 }
143
144 stats_issue_event(EVENT_SYNC, 0,
145 (ws->request_size - sizeof( g_tracker_id ) - sizeof( uint32_t ) ) /
146 ((ssize_t)sizeof( ot_hash ) + (ssize_t)sizeof( ot_peer )));
147}
148
149/* Tickle the live sync module from time to time, so no events get
150 stuck when there's not enough traffic to fill udp packets fast
151 enough */
152void livesync_ticker( ) {
153 /* livesync_issue_peersync sets g_next_packet_time */
154 pthread_mutex_lock(&g_outbuf_mutex);
155 if( g_now_seconds > g_next_packet_time &&
156 g_outbuf_data > sizeof( g_tracker_id ) + sizeof( uint32_t ) )
157 livesync_issue_peersync();
158 else
159 pthread_mutex_unlock(&g_outbuf_mutex);
160}
161
162/* Inform live sync about whats going on. */
163void livesync_tell( struct ot_workstruct *ws ) {
164 pthread_mutex_lock(&g_outbuf_mutex);
165
166 memcpy( g_outbuf + g_outbuf_data, ws->hash, sizeof(ot_hash) );
167 memcpy( g_outbuf + g_outbuf_data + sizeof(ot_hash), &ws->peer, sizeof(ot_peer) );
168
169 g_outbuf_data += sizeof(ot_hash) + sizeof(ot_peer);
170
171 if( g_outbuf_data >= LIVESYNC_OUTGOING_BUFFSIZE_PEERS - LIVESYNC_OUTGOING_WATERMARK_PEERS )
172 livesync_issue_peersync();
173 else
174 pthread_mutex_unlock(&g_outbuf_mutex);
175}
176
177static void * livesync_worker( void * args ) {
178 struct ot_workstruct ws;
179 ot_ip6 in_ip; uint16_t in_port;
180
181 (void)args;
182
183 /* Initialize our "thread local storage" */
184 ws.inbuf = ws.request = malloc( LIVESYNC_INCOMING_BUFFSIZE );
185 ws.outbuf = ws.reply = 0;
186
187 memcpy( in_ip, V4mappedprefix, sizeof( V4mappedprefix ) );
188
189 while( 1 ) {
190 ws.request_size = socket_recv4(g_socket_in, (char*)ws.inbuf, LIVESYNC_INCOMING_BUFFSIZE, 12+(char*)in_ip, &in_port);
191
192 /* Expect at least tracker id and packet type */
193 if( ws.request_size <= (ssize_t)(sizeof( g_tracker_id ) + sizeof( uint32_t )) )
194 continue;
195 if( !accesslist_isblessed(in_ip, OT_PERMISSION_MAY_LIVESYNC))
196 continue;
197 if( !memcmp( ws.inbuf, &g_tracker_id, sizeof( g_tracker_id ) ) ) {
198 /* TODO: log packet coming from ourselves */
199 continue;
200 }
201
202 switch( uint32_read_big( sizeof( g_tracker_id ) + (char *)ws.inbuf ) ) {
203 case OT_SYNC_PEER:
204 livesync_handle_peersync( &ws );
205 break;
206 default:
207 break;
208 }
209 }
210
211 /* Never returns. */
212 return NULL;
213}
214
215#endif
216const char *g_version_livesync_c = "$Source$: $Revision$\n";
diff --git a/ot_mutex.c b/ot_mutex.c
deleted file mode 100644
index 772d936..0000000
--- a/ot_mutex.c
+++ /dev/null
@@ -1,336 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <pthread.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <sys/mman.h>
11#include <sys/uio.h>
12
13/* Libowfat */
14#include "byte.h"
15#include "io.h"
16#include "uint32.h"
17
18/* Opentracker */
19#include "trackerlogic.h"
20#include "ot_mutex.h"
21#include "ot_stats.h"
22
23/* #define MTX_DBG( STRING ) fprintf( stderr, STRING ) */
24#define MTX_DBG( STRING )
25
26/* Our global all torrents list */
27static ot_vector all_torrents[OT_BUCKET_COUNT];
28static size_t g_torrent_count;
29
30/* Bucket Magic */
31static int bucket_locklist[ OT_MAX_THREADS ];
32static int bucket_locklist_count = 0;
33static pthread_mutex_t bucket_mutex;
34static pthread_cond_t bucket_being_unlocked;
35
36/* Self pipe from opentracker.c */
37extern int g_self_pipe[2];
38
39static int bucket_check( int bucket ) {
40 /* C should come with auto-i ;) */
41 int i;
42
43 /* No more space to acquire lock to bucket -- should not happen */
44 if( bucket_locklist_count == OT_MAX_THREADS ) {
45 fprintf( stderr, "More lock requests than mutexes. Consult source code.\n" );
46 return -1;
47 }
48
49 /* See, if bucket is already locked */
50 for( i=0; i<bucket_locklist_count; ++i )
51 if( bucket_locklist[ i ] == bucket ) {
52 stats_issue_event( EVENT_BUCKET_LOCKED, 0, 0 );
53 return -1;
54 }
55
56 return 0;
57}
58
59static void bucket_push( int bucket ) {
60 bucket_locklist[ bucket_locklist_count++ ] = bucket;
61}
62
63static void bucket_remove( int bucket ) {
64 int i = 0;
65
66 while( ( i < bucket_locklist_count ) && ( bucket_locklist[ i ] != bucket ) )
67 ++i;
68
69 if( i == bucket_locklist_count ) {
70 fprintf( stderr, "Request to unlock bucket that was never locked. Consult source code.\n" );
71 return;
72 }
73
74 for( ; i < bucket_locklist_count - 1; ++i )
75 bucket_locklist[ i ] = bucket_locklist[ i + 1 ];
76
77 --bucket_locklist_count;
78}
79
80/* Can block */
81ot_vector *mutex_bucket_lock( int bucket ) {
82 pthread_mutex_lock( &bucket_mutex );
83 while( bucket_check( bucket ) )
84 pthread_cond_wait( &bucket_being_unlocked, &bucket_mutex );
85 bucket_push( bucket );
86 pthread_mutex_unlock( &bucket_mutex );
87 return all_torrents + bucket;
88}
89
90ot_vector *mutex_bucket_lock_by_hash( ot_hash hash ) {
91 return mutex_bucket_lock( uint32_read_big( (char*)hash ) >> OT_BUCKET_COUNT_SHIFT );
92}
93
94void mutex_bucket_unlock( int bucket, int delta_torrentcount ) {
95 pthread_mutex_lock( &bucket_mutex );
96 bucket_remove( bucket );
97 g_torrent_count += delta_torrentcount;
98 pthread_cond_broadcast( &bucket_being_unlocked );
99 pthread_mutex_unlock( &bucket_mutex );
100}
101
102void mutex_bucket_unlock_by_hash( ot_hash hash, int delta_torrentcount ) {
103 mutex_bucket_unlock( uint32_read_big( (char*)hash ) >> OT_BUCKET_COUNT_SHIFT, delta_torrentcount );
104}
105
106size_t mutex_get_torrent_count( ) {
107 size_t torrent_count;
108 pthread_mutex_lock( &bucket_mutex );
109 torrent_count = g_torrent_count;
110 pthread_mutex_unlock( &bucket_mutex );
111 return torrent_count;
112}
113
114/* TaskQueue Magic */
115
116struct ot_task {
117 ot_taskid taskid;
118 ot_tasktype tasktype;
119 int64 sock;
120 int iovec_entries;
121 struct iovec *iovec;
122 struct ot_task *next;
123};
124
125static ot_taskid next_free_taskid = 1;
126static struct ot_task *tasklist;
127static pthread_mutex_t tasklist_mutex;
128static pthread_cond_t tasklist_being_filled;
129
130int mutex_workqueue_pushtask( int64 sock, ot_tasktype tasktype ) {
131 struct ot_task ** tmptask, * task;
132
133 /* Want exclusive access to tasklist */
134 MTX_DBG( "pushtask locks.\n" );
135 pthread_mutex_lock( &tasklist_mutex );
136 MTX_DBG( "pushtask locked.\n" );
137
138 task = malloc(sizeof( struct ot_task));
139 if( !task ) {
140 MTX_DBG( "pushtask fail unlocks.\n" );
141 pthread_mutex_unlock( &tasklist_mutex );
142 MTX_DBG( "pushtask fail unlocked.\n" );
143 return -1;
144 }
145
146 /* Skip to end of list */
147 tmptask = &tasklist;
148 while( *tmptask )
149 tmptask = &(*tmptask)->next;
150 *tmptask = task;
151
152 task->taskid = 0;
153 task->tasktype = tasktype;
154 task->sock = sock;
155 task->iovec_entries = 0;
156 task->iovec = NULL;
157 task->next = 0;
158
159 /* Inform waiting workers and release lock */
160 MTX_DBG( "pushtask broadcasts.\n" );
161 pthread_cond_broadcast( &tasklist_being_filled );
162 MTX_DBG( "pushtask broadcasted, mutex unlocks.\n" );
163 pthread_mutex_unlock( &tasklist_mutex );
164 MTX_DBG( "pushtask end mutex unlocked.\n" );
165 return 0;
166}
167
168void mutex_workqueue_canceltask( int64 sock ) {
169 struct ot_task ** task;
170
171 /* Want exclusive access to tasklist */
172 MTX_DBG( "canceltask locks.\n" );
173 pthread_mutex_lock( &tasklist_mutex );
174 MTX_DBG( "canceltask locked.\n" );
175
176 task = &tasklist;
177 while( *task && ( (*task)->sock != sock ) )
178 *task = (*task)->next;
179
180 if( *task && ( (*task)->sock == sock ) ) {
181 struct iovec *iovec = (*task)->iovec;
182 struct ot_task *ptask = *task;
183 int i;
184
185 /* Free task's iovec */
186 for( i=0; i<(*task)->iovec_entries; ++i )
187 munmap( iovec[i].iov_base, iovec[i].iov_len );
188
189 *task = (*task)->next;
190 free( ptask );
191 }
192
193 /* Release lock */
194 MTX_DBG( "canceltask unlocks.\n" );
195 pthread_mutex_unlock( &tasklist_mutex );
196 MTX_DBG( "canceltask unlocked.\n" );
197}
198
199ot_taskid mutex_workqueue_poptask( ot_tasktype *tasktype ) {
200 struct ot_task * task;
201 ot_taskid taskid = 0;
202
203 /* Want exclusive access to tasklist */
204 MTX_DBG( "poptask mutex locks.\n" );
205 pthread_mutex_lock( &tasklist_mutex );
206 MTX_DBG( "poptask mutex locked.\n" );
207
208 while( !taskid ) {
209 /* Skip to the first unassigned task this worker wants to do */
210 task = tasklist;
211 while( task && ( ( ( TASK_CLASS_MASK & task->tasktype ) != *tasktype ) || task->taskid ) )
212 task = task->next;
213
214 /* If we found an outstanding task, assign a taskid to it
215 and leave the loop */
216 if( task ) {
217 task->taskid = taskid = ++next_free_taskid;
218 *tasktype = task->tasktype;
219 } else {
220 /* Wait until the next task is being fed */
221 MTX_DBG( "poptask cond waits.\n" );
222 pthread_cond_wait( &tasklist_being_filled, &tasklist_mutex );
223 MTX_DBG( "poptask cond waited.\n" );
224 }
225 }
226
227 /* Release lock */
228 MTX_DBG( "poptask end mutex unlocks.\n" );
229 pthread_mutex_unlock( &tasklist_mutex );
230 MTX_DBG( "poptask end mutex unlocked.\n" );
231
232 return taskid;
233}
234
235void mutex_workqueue_pushsuccess( ot_taskid taskid ) {
236 struct ot_task ** task;
237
238 /* Want exclusive access to tasklist */
239 MTX_DBG( "pushsuccess locks.\n" );
240 pthread_mutex_lock( &tasklist_mutex );
241 MTX_DBG( "pushsuccess locked.\n" );
242
243 task = &tasklist;
244 while( *task && ( (*task)->taskid != taskid ) )
245 *task = (*task)->next;
246
247 if( *task && ( (*task)->taskid == taskid ) ) {
248 struct ot_task *ptask = *task;
249 *task = (*task)->next;
250 free( ptask );
251 }
252
253 /* Release lock */
254 MTX_DBG( "pushsuccess unlocks.\n" );
255 pthread_mutex_unlock( &tasklist_mutex );
256 MTX_DBG( "pushsuccess unlocked.\n" );
257}
258
259int mutex_workqueue_pushresult( ot_taskid taskid, int iovec_entries, struct iovec *iovec ) {
260 struct ot_task * task;
261 const char byte = 'o';
262
263 /* Want exclusive access to tasklist */
264 MTX_DBG( "pushresult locks.\n" );
265 pthread_mutex_lock( &tasklist_mutex );
266 MTX_DBG( "pushresult locked.\n" );
267
268 task = tasklist;
269 while( task && ( task->taskid != taskid ) )
270 task = task->next;
271
272 if( task ) {
273 task->iovec_entries = iovec_entries;
274 task->iovec = iovec;
275 task->tasktype = TASK_DONE;
276 }
277
278 /* Release lock */
279 MTX_DBG( "pushresult unlocks.\n" );
280 pthread_mutex_unlock( &tasklist_mutex );
281 MTX_DBG( "pushresult unlocked.\n" );
282
283 io_trywrite( g_self_pipe[1], &byte, 1 );
284
285 /* Indicate whether the worker has to throw away results */
286 return task ? 0 : -1;
287}
288
289int64 mutex_workqueue_popresult( int *iovec_entries, struct iovec ** iovec ) {
290 struct ot_task ** task;
291 int64 sock = -1;
292
293 /* Want exclusive access to tasklist */
294 MTX_DBG( "popresult locks.\n" );
295 pthread_mutex_lock( &tasklist_mutex );
296 MTX_DBG( "popresult locked.\n" );
297
298 task = &tasklist;
299 while( *task && ( (*task)->tasktype != TASK_DONE ) )
300 task = &(*task)->next;
301
302 if( *task && ( (*task)->tasktype == TASK_DONE ) ) {
303 struct ot_task *ptask = *task;
304
305 *iovec_entries = (*task)->iovec_entries;
306 *iovec = (*task)->iovec;
307 sock = (*task)->sock;
308
309 *task = (*task)->next;
310 free( ptask );
311 }
312
313 /* Release lock */
314 MTX_DBG( "popresult unlocks.\n" );
315 pthread_mutex_unlock( &tasklist_mutex );
316 MTX_DBG( "popresult unlocked.\n" );
317 return sock;
318}
319
320void mutex_init( ) {
321 pthread_mutex_init(&tasklist_mutex, NULL);
322 pthread_cond_init (&tasklist_being_filled, NULL);
323 pthread_mutex_init(&bucket_mutex, NULL);
324 pthread_cond_init (&bucket_being_unlocked, NULL);
325 byte_zero( all_torrents, sizeof( all_torrents ) );
326}
327
328void mutex_deinit( ) {
329 pthread_mutex_destroy(&bucket_mutex);
330 pthread_cond_destroy(&bucket_being_unlocked);
331 pthread_mutex_destroy(&tasklist_mutex);
332 pthread_cond_destroy(&tasklist_being_filled);
333 byte_zero( all_torrents, sizeof( all_torrents ) );
334}
335
336const char *g_version_mutex_c = "$Source$: $Revision$\n";
diff --git a/ot_mutex.h b/ot_mutex.h
deleted file mode 100644
index bd07009..0000000
--- a/ot_mutex.h
+++ /dev/null
@@ -1,75 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_MUTEX_H__
7#define OT_MUTEX_H__
8
9#include <sys/uio.h>
10
11void mutex_init( );
12void mutex_deinit( );
13
14ot_vector *mutex_bucket_lock( int bucket );
15ot_vector *mutex_bucket_lock_by_hash( ot_hash hash );
16
17void mutex_bucket_unlock( int bucket, int delta_torrentcount );
18void mutex_bucket_unlock_by_hash( ot_hash hash, int delta_torrentcount );
19
20size_t mutex_get_torrent_count();
21
22typedef enum {
23 TASK_STATS_CONNS = 0x0001,
24 TASK_STATS_TCP = 0x0002,
25 TASK_STATS_UDP = 0x0003,
26 TASK_STATS_SCRAPE = 0x0004,
27 TASK_STATS_FULLSCRAPE = 0x0005,
28 TASK_STATS_TPB = 0x0006,
29 TASK_STATS_HTTPERRORS = 0x0007,
30 TASK_STATS_VERSION = 0x0008,
31 TASK_STATS_BUSY_NETWORKS = 0x0009,
32 TASK_STATS_RENEW = 0x000a,
33 TASK_STATS_SYNCS = 0x000b,
34 TASK_STATS_COMPLETED = 0x000c,
35 TASK_STATS_NUMWANTS = 0x000d,
36
37 TASK_STATS = 0x0100, /* Mask */
38 TASK_STATS_TORRENTS = 0x0101,
39 TASK_STATS_PEERS = 0x0102,
40 TASK_STATS_SLASH24S = 0x0103,
41 TASK_STATS_TOP10 = 0x0104,
42 TASK_STATS_TOP100 = 0x0105,
43 TASK_STATS_EVERYTHING = 0x0106,
44 TASK_STATS_FULLLOG = 0x0107,
45 TASK_STATS_WOODPECKERS = 0x0108,
46
47 TASK_FULLSCRAPE = 0x0200, /* Default mode */
48 TASK_FULLSCRAPE_TPB_BINARY = 0x0201,
49 TASK_FULLSCRAPE_TPB_ASCII = 0x0202,
50 TASK_FULLSCRAPE_TPB_ASCII_PLUS = 0x0203,
51 TASK_FULLSCRAPE_TPB_URLENCODED = 0x0204,
52 TASK_FULLSCRAPE_TRACKERSTATE = 0x0205,
53
54 TASK_DMEM = 0x0300,
55
56 TASK_DONE = 0x0f00,
57
58 TASK_FLAG_GZIP = 0x1000,
59 TASK_FLAG_BZIP2 = 0x2000,
60
61 TASK_TASK_MASK = 0x0fff,
62 TASK_CLASS_MASK = 0x0f00,
63 TASK_FLAGS_MASK = 0xf000
64} ot_tasktype;
65
66typedef unsigned long ot_taskid;
67
68int mutex_workqueue_pushtask( int64 sock, ot_tasktype tasktype );
69void mutex_workqueue_canceltask( int64 sock );
70void mutex_workqueue_pushsuccess( ot_taskid taskid );
71ot_taskid mutex_workqueue_poptask( ot_tasktype *tasktype );
72int mutex_workqueue_pushresult( ot_taskid taskid, int iovec_entries, struct iovec *iovector );
73int64 mutex_workqueue_popresult( int *iovec_entries, struct iovec ** iovector );
74
75#endif
diff --git a/ot_stats.c b/ot_stats.c
deleted file mode 100644
index 83cd058..0000000
--- a/ot_stats.c
+++ /dev/null
@@ -1,773 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <stdlib.h>
8#include <arpa/inet.h>
9#include <sys/types.h>
10#include <sys/uio.h>
11#include <sys/mman.h>
12#include <stdio.h>
13#include <string.h>
14#include <pthread.h>
15#include <unistd.h>
16#include <inttypes.h>
17#ifdef WANT_SYSLOGS
18#include <syslog.h>
19#endif
20
21/* Libowfat */
22#include "byte.h"
23#include "io.h"
24#include "ip4.h"
25#include "ip6.h"
26
27/* Opentracker */
28#include "trackerlogic.h"
29#include "ot_mutex.h"
30#include "ot_iovec.h"
31#include "ot_stats.h"
32#include "ot_accesslist.h"
33
34#ifndef NO_FULLSCRAPE_LOGGING
35#define LOG_TO_STDERR( ... ) fprintf( stderr, __VA_ARGS__ )
36#else
37#define LOG_TO_STDERR( ... )
38#endif
39
40/* Forward declaration */
41static void stats_make( int *iovec_entries, struct iovec **iovector, ot_tasktype mode );
42#define OT_STATS_TMPSIZE 8192
43
44/* Clumsy counters... to be rethought */
45static unsigned long long ot_overall_tcp_connections = 0;
46static unsigned long long ot_overall_udp_connections = 0;
47static unsigned long long ot_overall_tcp_successfulannounces = 0;
48static unsigned long long ot_overall_udp_successfulannounces = 0;
49static unsigned long long ot_overall_tcp_successfulscrapes = 0;
50static unsigned long long ot_overall_udp_successfulscrapes = 0;
51static unsigned long long ot_overall_udp_connectionidmissmatches = 0;
52static unsigned long long ot_overall_tcp_connects = 0;
53static unsigned long long ot_overall_udp_connects = 0;
54static unsigned long long ot_overall_completed = 0;
55static unsigned long long ot_full_scrape_count = 0;
56static unsigned long long ot_full_scrape_request_count = 0;
57static unsigned long long ot_full_scrape_size = 0;
58static unsigned long long ot_failed_request_counts[CODE_HTTPERROR_COUNT];
59static char * ot_failed_request_names[] = { "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest", "402 Payment Required", "403 Access Denied", "404 Not found", "500 Internal Server Error" };
60static unsigned long long ot_renewed[OT_PEER_TIMEOUT];
61static unsigned long long ot_overall_sync_count;
62static unsigned long long ot_overall_stall_count;
63
64static time_t ot_start_time;
65
66#define STATS_NETWORK_NODE_BITWIDTH 4
67#define STATS_NETWORK_NODE_COUNT (1<<STATS_NETWORK_NODE_BITWIDTH)
68
69#define __BYTE(P,D) (((uint8_t*)P)[D/8])
70#define __MSK (STATS_NETWORK_NODE_COUNT-1)
71#define __SHFT(D) ((D^STATS_NETWORK_NODE_BITWIDTH)&STATS_NETWORK_NODE_BITWIDTH)
72
73#define __LDR(P,D) ((__BYTE((P),(D))>>__SHFT((D)))&__MSK)
74#define __STR(P,D,V) __BYTE((P),(D))=(__BYTE((P),(D))&~(__MSK<<__SHFT((D))))|((V)<<__SHFT((D)))
75
76#ifdef WANT_V6
77#define STATS_NETWORK_NODE_MAXDEPTH (68-STATS_NETWORK_NODE_BITWIDTH)
78#define STATS_NETWORK_NODE_LIMIT (48-STATS_NETWORK_NODE_BITWIDTH)
79#else
80#define STATS_NETWORK_NODE_MAXDEPTH (28-STATS_NETWORK_NODE_BITWIDTH)
81#define STATS_NETWORK_NODE_LIMIT (24-STATS_NETWORK_NODE_BITWIDTH)
82#endif
83
84typedef union stats_network_node stats_network_node;
85union stats_network_node {
86 size_t counters[STATS_NETWORK_NODE_COUNT];
87 stats_network_node *children[STATS_NETWORK_NODE_COUNT];
88};
89
90#ifdef WANT_LOG_NETWORKS
91static stats_network_node *stats_network_counters_root;
92#endif
93
94static int stat_increase_network_count( stats_network_node **pnode, int depth, uintptr_t ip ) {
95 int foo = __LDR(ip,depth);
96 stats_network_node *node;
97
98 if( !*pnode ) {
99 *pnode = malloc( sizeof( stats_network_node ) );
100 if( !*pnode )
101 return -1;
102 memset( *pnode, 0, sizeof( stats_network_node ) );
103 }
104 node = *pnode;
105
106 if( depth < STATS_NETWORK_NODE_MAXDEPTH )
107 return stat_increase_network_count( node->children + foo, depth+STATS_NETWORK_NODE_BITWIDTH, ip );
108
109 node->counters[ foo ]++;
110 return 0;
111}
112
113static int stats_shift_down_network_count( stats_network_node **node, int depth, int shift ) {
114 int i, rest = 0;
115
116 if( !*node )
117 return 0;
118
119 for( i=0; i<STATS_NETWORK_NODE_COUNT; ++i )
120 if( depth < STATS_NETWORK_NODE_MAXDEPTH )
121 rest += stats_shift_down_network_count( (*node)->children + i, depth+STATS_NETWORK_NODE_BITWIDTH, shift );
122 else
123 rest += (*node)->counters[i] >>= shift;
124
125 if( !rest ) {
126 free( *node );
127 *node = NULL;
128 }
129
130 return rest;
131}
132
133static size_t stats_get_highscore_networks( stats_network_node *node, int depth, ot_ip6 node_value, size_t *scores, ot_ip6 *networks, int network_count, int limit ) {
134 size_t score = 0;
135 int i;
136
137 if( !node ) return 0;
138
139 if( depth < limit ) {
140 for( i=0; i<STATS_NETWORK_NODE_COUNT; ++i )
141 if( node->children[i] ) {
142 __STR(node_value,depth,i);
143 score += stats_get_highscore_networks( node->children[i], depth+STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit );
144 }
145 return score;
146 }
147
148 if( depth > limit && depth < STATS_NETWORK_NODE_MAXDEPTH ) {
149 for( i=0; i<STATS_NETWORK_NODE_COUNT; ++i )
150 if( node->children[i] )
151 score += stats_get_highscore_networks( node->children[i], depth+STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit );
152 return score;
153 }
154
155 if( depth > limit && depth == STATS_NETWORK_NODE_MAXDEPTH ) {
156 for( i=0; i<STATS_NETWORK_NODE_COUNT; ++i )
157 score += node->counters[i];
158 return score;
159 }
160
161 /* if( depth == limit ) */
162 for( i=0; i<STATS_NETWORK_NODE_COUNT; ++i ) {
163 int j=1;
164 size_t node_score;
165
166 if( depth == STATS_NETWORK_NODE_MAXDEPTH )
167 node_score = node->counters[i];
168 else
169 node_score = stats_get_highscore_networks( node->children[i], depth+STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit );
170
171 score += node_score;
172
173 if( node_score <= scores[0] ) continue;
174
175 __STR(node_value,depth,i);
176 while( j < network_count && node_score > scores[j] ) ++j;
177 --j;
178
179 memcpy( scores, scores + 1, j * sizeof( *scores ) );
180 memcpy( networks, networks + 1, j * sizeof( *networks ) );
181 scores[ j ] = node_score;
182 memcpy( networks + j, node_value, sizeof( *networks ) );
183 }
184
185 return score;
186}
187
188static size_t stats_return_busy_networks( char * reply, stats_network_node *tree, int amount, int limit ) {
189 ot_ip6 networks[amount];
190 ot_ip6 node_value;
191 size_t scores[amount];
192 int i;
193 char * r = reply;
194
195 memset( scores, 0, sizeof( scores ) );
196 memset( networks, 0, sizeof( networks ) );
197 memset( node_value, 0, sizeof( node_value ) );
198
199 stats_get_highscore_networks( tree, 0, node_value, scores, networks, amount, limit );
200
201 r += sprintf( r, "Networks, limit /%d:\n", limit+STATS_NETWORK_NODE_BITWIDTH );
202 for( i=amount-1; i>=0; --i) {
203 if( scores[i] ) {
204 r += sprintf( r, "%08zd: ", scores[i] );
205#ifdef WANT_V6
206 r += fmt_ip6c( r, networks[i] );
207#else
208 r += fmt_ip4( r, networks[i]);
209#endif
210 *r++ = '\n';
211 }
212 }
213 *r++ = '\n';
214
215 return r - reply;
216}
217
218static size_t stats_slash24s_txt( char *reply, size_t amount ) {
219 stats_network_node *slash24s_network_counters_root = NULL;
220 char *r=reply;
221 int bucket;
222 size_t i;
223
224 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
225 ot_vector *torrents_list = mutex_bucket_lock( bucket );
226 for( i=0; i<torrents_list->size; ++i ) {
227 ot_peerlist *peer_list = ( ((ot_torrent*)(torrents_list->data))[i] ).peer_list;
228 ot_vector *bucket_list = &peer_list->peers;
229 int num_buckets = 1;
230
231 if( OT_PEERLIST_HASBUCKETS( peer_list ) ) {
232 num_buckets = bucket_list->size;
233 bucket_list = (ot_vector *)bucket_list->data;
234 }
235
236 while( num_buckets-- ) {
237 ot_peer *peers = (ot_peer*)bucket_list->data;
238 size_t numpeers = bucket_list->size;
239 while( numpeers-- )
240 if( stat_increase_network_count( &slash24s_network_counters_root, 0, (uintptr_t)(peers++) ) )
241 goto bailout_unlock;
242 ++bucket_list;
243 }
244 }
245 mutex_bucket_unlock( bucket, 0 );
246 if( !g_opentracker_running )
247 goto bailout_error;
248 }
249
250 /* The tree is built. Now analyze */
251 r += stats_return_busy_networks( r, slash24s_network_counters_root, amount, STATS_NETWORK_NODE_MAXDEPTH );
252 r += stats_return_busy_networks( r, slash24s_network_counters_root, amount, STATS_NETWORK_NODE_LIMIT );
253 goto success;
254
255bailout_unlock:
256 mutex_bucket_unlock( bucket, 0 );
257bailout_error:
258 r = reply;
259success:
260 stats_shift_down_network_count( &slash24s_network_counters_root, 0, sizeof(int)*8-1 );
261
262 return r-reply;
263}
264
265#ifdef WANT_SPOT_WOODPECKER
266static stats_network_node *stats_woodpeckers_tree;
267static pthread_mutex_t g_woodpeckers_mutex = PTHREAD_MUTEX_INITIALIZER;
268
269static size_t stats_return_woodpeckers( char * reply, int amount ) {
270 char * r = reply;
271
272 pthread_mutex_lock( &g_woodpeckers_mutex );
273 r += stats_return_busy_networks( r, stats_woodpeckers_tree, amount, STATS_NETWORK_NODE_MAXDEPTH );
274 pthread_mutex_unlock( &g_woodpeckers_mutex );
275 return r-reply;
276}
277#endif
278
279typedef struct {
280 unsigned long long torrent_count;
281 unsigned long long peer_count;
282 unsigned long long seed_count;
283} torrent_stats;
284
285static int torrent_statter( ot_torrent *torrent, uintptr_t data ) {
286 torrent_stats *stats = (torrent_stats*)data;
287 stats->torrent_count++;
288 stats->peer_count += torrent->peer_list->peer_count;
289 stats->seed_count += torrent->peer_list->seed_count;
290 return 0;
291}
292
293/* Converter function from memory to human readable hex strings */
294static char*to_hex(char*d,uint8_t*s){char*m="0123456789ABCDEF";char *t=d;char*e=d+40;while(d<e){*d++=m[*s>>4];*d++=m[*s++&15];}*d=0;return t;}
295
296typedef struct { size_t val; ot_torrent * torrent; } ot_record;
297
298/* Fetches stats from tracker */
299size_t stats_top_txt( char * reply, int amount ) {
300 size_t j;
301 ot_record top100s[100], top100c[100];
302 char *r = reply, hex_out[42];
303 int idx, bucket;
304
305 if( amount > 100 )
306 amount = 100;
307
308 byte_zero( top100s, sizeof( top100s ) );
309 byte_zero( top100c, sizeof( top100c ) );
310
311 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
312 ot_vector *torrents_list = mutex_bucket_lock( bucket );
313 for( j=0; j<torrents_list->size; ++j ) {
314 ot_peerlist *peer_list = ( ((ot_torrent*)(torrents_list->data))[j] ).peer_list;
315 int idx = amount - 1; while( (idx >= 0) && ( peer_list->peer_count > top100c[idx].val ) ) --idx;
316 if ( idx++ != amount - 1 ) {
317 memmove( top100c + idx + 1, top100c + idx, ( amount - 1 - idx ) * sizeof( ot_record ) );
318 top100c[idx].val = peer_list->peer_count;
319 top100c[idx].torrent = (ot_torrent*)(torrents_list->data) + j;
320 }
321 idx = amount - 1; while( (idx >= 0) && ( peer_list->seed_count > top100s[idx].val ) ) --idx;
322 if ( idx++ != amount - 1 ) {
323 memmove( top100s + idx + 1, top100s + idx, ( amount - 1 - idx ) * sizeof( ot_record ) );
324 top100s[idx].val = peer_list->seed_count;
325 top100s[idx].torrent = (ot_torrent*)(torrents_list->data) + j;
326 }
327 }
328 mutex_bucket_unlock( bucket, 0 );
329 if( !g_opentracker_running )
330 return 0;
331 }
332
333 r += sprintf( r, "Top %d torrents by peers:\n", amount );
334 for( idx=0; idx<amount; ++idx )
335 if( top100c[idx].torrent )
336 r += sprintf( r, "\t%zd\t%s\n", top100c[idx].val, to_hex( hex_out, top100c[idx].torrent->hash) );
337 r += sprintf( r, "Top %d torrents by seeds:\n", amount );
338 for( idx=0; idx<amount; ++idx )
339 if( top100s[idx].torrent )
340 r += sprintf( r, "\t%zd\t%s\n", top100s[idx].val, to_hex( hex_out, top100s[idx].torrent->hash) );
341
342 return r - reply;
343}
344
345static unsigned long events_per_time( unsigned long long events, time_t t ) {
346 return events / ( (unsigned int)t ? (unsigned int)t : 1 );
347}
348
349static size_t stats_connections_mrtg( char * reply ) {
350 ot_time t = time( NULL ) - ot_start_time;
351 return sprintf( reply,
352 "%llu\n%llu\n%i seconds (%i hours)\nopentracker connections, %lu conns/s :: %lu success/s.",
353 ot_overall_tcp_connections+ot_overall_udp_connections,
354 ot_overall_tcp_successfulannounces+ot_overall_udp_successfulannounces+ot_overall_udp_connects,
355 (int)t,
356 (int)(t / 3600),
357 events_per_time( ot_overall_tcp_connections+ot_overall_udp_connections, t ),
358 events_per_time( ot_overall_tcp_successfulannounces+ot_overall_udp_successfulannounces+ot_overall_udp_connects, t )
359 );
360}
361
362static size_t stats_udpconnections_mrtg( char * reply ) {
363 ot_time t = time( NULL ) - ot_start_time;
364 return sprintf( reply,
365 "%llu\n%llu\n%i seconds (%i hours)\nopentracker udp4 stats, %lu conns/s :: %lu success/s.",
366 ot_overall_udp_connections,
367 ot_overall_udp_successfulannounces+ot_overall_udp_connects,
368 (int)t,
369 (int)(t / 3600),
370 events_per_time( ot_overall_udp_connections, t ),
371 events_per_time( ot_overall_udp_successfulannounces+ot_overall_udp_connects, t )
372 );
373}
374
375static size_t stats_tcpconnections_mrtg( char * reply ) {
376 time_t t = time( NULL ) - ot_start_time;
377 return sprintf( reply,
378 "%llu\n%llu\n%i seconds (%i hours)\nopentracker tcp4 stats, %lu conns/s :: %lu success/s.",
379 ot_overall_tcp_connections,
380 ot_overall_tcp_successfulannounces,
381 (int)t,
382 (int)(t / 3600),
383 events_per_time( ot_overall_tcp_connections, t ),
384 events_per_time( ot_overall_tcp_successfulannounces, t )
385 );
386}
387
388static size_t stats_scrape_mrtg( char * reply ) {
389 time_t t = time( NULL ) - ot_start_time;
390 return sprintf( reply,
391 "%llu\n%llu\n%i seconds (%i hours)\nopentracker scrape stats, %lu scrape/s (tcp and udp)",
392 ot_overall_tcp_successfulscrapes,
393 ot_overall_udp_successfulscrapes,
394 (int)t,
395 (int)(t / 3600),
396 events_per_time( (ot_overall_tcp_successfulscrapes+ot_overall_udp_successfulscrapes), t )
397 );
398}
399
400static size_t stats_fullscrapes_mrtg( char * reply ) {
401 ot_time t = time( NULL ) - ot_start_time;
402 return sprintf( reply,
403 "%llu\n%llu\n%i seconds (%i hours)\nopentracker full scrape stats, %lu conns/s :: %lu bytes/s.",
404 ot_full_scrape_count * 1000,
405 ot_full_scrape_size,
406 (int)t,
407 (int)(t / 3600),
408 events_per_time( ot_full_scrape_count, t ),
409 events_per_time( ot_full_scrape_size, t )
410 );
411}
412
413static size_t stats_peers_mrtg( char * reply ) {
414 torrent_stats stats = {0,0,0};
415
416 iterate_all_torrents( torrent_statter, (uintptr_t)&stats );
417
418 return sprintf( reply, "%llu\n%llu\nopentracker serving %llu torrents\nopentracker",
419 stats.peer_count,
420 stats.seed_count,
421 stats.torrent_count
422 );
423}
424
425static size_t stats_torrents_mrtg( char * reply )
426{
427 size_t torrent_count = mutex_get_torrent_count();
428
429 return sprintf( reply, "%zd\n%zd\nopentracker serving %zd torrents\nopentracker",
430 torrent_count,
431 (size_t)0,
432 torrent_count
433 );
434}
435
436static size_t stats_httperrors_txt ( char * reply ) {
437 return sprintf( reply, "302 RED %llu\n400 ... %llu\n400 PAR %llu\n400 COM %llu\n403 IP %llu\n404 INV %llu\n500 SRV %llu\n",
438 ot_failed_request_counts[0], ot_failed_request_counts[1], ot_failed_request_counts[2],
439 ot_failed_request_counts[3], ot_failed_request_counts[4], ot_failed_request_counts[5],
440 ot_failed_request_counts[6] );
441}
442
443static size_t stats_return_renew_bucket( char * reply ) {
444 char *r = reply;
445 int i;
446
447 for( i=0; i<OT_PEER_TIMEOUT; ++i )
448 r+=sprintf(r,"%02i %llu\n", i, ot_renewed[i] );
449 return r - reply;
450}
451
452static size_t stats_return_sync_mrtg( char * reply ) {
453 ot_time t = time( NULL ) - ot_start_time;
454 return sprintf( reply,
455 "%llu\n%llu\n%i seconds (%i hours)\nopentracker connections, %lu conns/s :: %lu success/s.",
456 ot_overall_sync_count,
457 0LL,
458 (int)t,
459 (int)(t / 3600),
460 events_per_time( ot_overall_tcp_connections+ot_overall_udp_connections, t ),
461 events_per_time( ot_overall_tcp_successfulannounces+ot_overall_udp_successfulannounces+ot_overall_udp_connects, t )
462 );
463}
464
465static size_t stats_return_completed_mrtg( char * reply ) {
466 ot_time t = time( NULL ) - ot_start_time;
467
468 return sprintf( reply,
469 "%llu\n%llu\n%i seconds (%i hours)\nopentracker, %lu completed/h.",
470 ot_overall_completed,
471 0LL,
472 (int)t,
473 (int)(t / 3600),
474 events_per_time( ot_overall_completed, t / 3600 )
475 );
476}
477
478#ifdef WANT_LOG_NUMWANT
479extern unsigned long long numwants[201];
480static size_t stats_return_numwants( char * reply ) {
481 char * r = reply;
482 int i;
483 for( i=0; i<=200; ++i )
484 r += sprintf( r, "%03d => %lld\n", i, numwants[i] );
485 return r-reply;
486}
487#endif
488
489#ifdef WANT_FULLLOG_NETWORKS
490static void stats_return_fulllog( int *iovec_entries, struct iovec **iovector, char *r ) {
491 ot_log *loglist = g_logchain_first, *llnext;
492 char * re = r + OT_STATS_TMPSIZE;
493
494 g_logchain_first = g_logchain_last = 0;
495
496 while( loglist ) {
497 if( r + ( loglist->size + 64 ) >= re ) {
498 r = iovec_fix_increase_or_free( iovec_entries, iovector, r, 32 * OT_STATS_TMPSIZE );
499 if( !r ) return;
500 re = r + 32 * OT_STATS_TMPSIZE;
501 }
502 r += sprintf( r, "%08ld: ", loglist->time );
503 r += fmt_ip6c( r, loglist->ip );
504 *r++ = '\n';
505 memcpy( r, loglist->data, loglist->size );
506 r += loglist->size;
507 *r++ = '\n';
508 *r++ = '*';
509 *r++ = '\n';
510 *r++ = '\n';
511
512 llnext = loglist->next;
513 free( loglist->data );
514 free( loglist );
515 loglist = llnext;
516 }
517 iovec_fixlast( iovec_entries, iovector, r );
518}
519#endif
520
521static size_t stats_return_everything( char * reply ) {
522 torrent_stats stats = {0,0,0};
523 int i;
524 char * r = reply;
525
526 iterate_all_torrents( torrent_statter, (uintptr_t)&stats );
527
528 r += sprintf( r, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
529 r += sprintf( r, "<stats>\n" );
530 r += sprintf( r, " <tracker_id>%" PRIu32 "</tracker_id>\n", g_tracker_id );
531 r += sprintf( r, " <version>\n" ); r += stats_return_tracker_version( r ); r += sprintf( r, " </version>\n" );
532 r += sprintf( r, " <uptime>%llu</uptime>\n", (unsigned long long)(time( NULL ) - ot_start_time) );
533 r += sprintf( r, " <torrents>\n" );
534 r += sprintf( r, " <count_mutex>%zd</count_mutex>\n", mutex_get_torrent_count() );
535 r += sprintf( r, " <count_iterator>%llu</count_iterator>\n", stats.torrent_count );
536 r += sprintf( r, " </torrents>\n" );
537 r += sprintf( r, " <peers>\n <count>%llu</count>\n </peers>\n", stats.peer_count );
538 r += sprintf( r, " <seeds>\n <count>%llu</count>\n </seeds>\n", stats.seed_count );
539 r += sprintf( r, " <completed>\n <count>%llu</count>\n </completed>\n", ot_overall_completed );
540 r += sprintf( r, " <connections>\n" );
541 r += sprintf( r, " <tcp>\n <accept>%llu</accept>\n <announce>%llu</announce>\n <scrape>%llu</scrape>\n </tcp>\n", ot_overall_tcp_connections, ot_overall_tcp_successfulannounces, ot_overall_tcp_successfulscrapes );
542 r += sprintf( r, " <udp>\n <overall>%llu</overall>\n <connect>%llu</connect>\n <announce>%llu</announce>\n <scrape>%llu</scrape>\n <missmatch>%llu</missmatch>\n </udp>\n", ot_overall_udp_connections, ot_overall_udp_connects, ot_overall_udp_successfulannounces, ot_overall_udp_successfulscrapes, ot_overall_udp_connectionidmissmatches );
543 r += sprintf( r, " <livesync>\n <count>%llu</count>\n </livesync>\n", ot_overall_sync_count );
544 r += sprintf( r, " </connections>\n" );
545 r += sprintf( r, " <debug>\n" );
546 r += sprintf( r, " <renew>\n" );
547 for( i=0; i<OT_PEER_TIMEOUT; ++i )
548 r += sprintf( r, " <count interval=\"%02i\">%llu</count>\n", i, ot_renewed[i] );
549 r += sprintf( r, " </renew>\n" );
550 r += sprintf( r, " <http_error>\n" );
551 for( i=0; i<CODE_HTTPERROR_COUNT; ++i )
552 r += sprintf( r, " <count code=\"%s\">%llu</count>\n", ot_failed_request_names[i], ot_failed_request_counts[i] );
553 r += sprintf( r, " </http_error>\n" );
554 r += sprintf( r, " <mutex_stall>\n <count>%llu</count>\n </mutex_stall>\n", ot_overall_stall_count );
555 r += sprintf( r, " </debug>\n" );
556 r += sprintf( r, "</stats>" );
557 return r - reply;
558}
559
560extern const char
561*g_version_opentracker_c, *g_version_accesslist_c, *g_version_clean_c, *g_version_fullscrape_c, *g_version_http_c,
562*g_version_iovec_c, *g_version_mutex_c, *g_version_stats_c, *g_version_udp_c, *g_version_vector_c,
563*g_version_scan_urlencoded_query_c, *g_version_trackerlogic_c, *g_version_livesync_c, *g_version_rijndael_c;
564
565size_t stats_return_tracker_version( char *reply ) {
566 return sprintf( reply, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
567 g_version_opentracker_c, g_version_accesslist_c, g_version_clean_c, g_version_fullscrape_c, g_version_http_c,
568 g_version_iovec_c, g_version_mutex_c, g_version_stats_c, g_version_udp_c, g_version_vector_c,
569 g_version_scan_urlencoded_query_c, g_version_trackerlogic_c, g_version_livesync_c, g_version_rijndael_c );
570}
571
572size_t return_stats_for_tracker( char *reply, int mode, int format ) {
573 (void) format;
574 switch( mode & TASK_TASK_MASK ) {
575 case TASK_STATS_CONNS:
576 return stats_connections_mrtg( reply );
577 case TASK_STATS_SCRAPE:
578 return stats_scrape_mrtg( reply );
579 case TASK_STATS_UDP:
580 return stats_udpconnections_mrtg( reply );
581 case TASK_STATS_TCP:
582 return stats_tcpconnections_mrtg( reply );
583 case TASK_STATS_FULLSCRAPE:
584 return stats_fullscrapes_mrtg( reply );
585 case TASK_STATS_COMPLETED:
586 return stats_return_completed_mrtg( reply );
587 case TASK_STATS_HTTPERRORS:
588 return stats_httperrors_txt( reply );
589 case TASK_STATS_VERSION:
590 return stats_return_tracker_version( reply );
591 case TASK_STATS_RENEW:
592 return stats_return_renew_bucket( reply );
593 case TASK_STATS_SYNCS:
594 return stats_return_sync_mrtg( reply );
595#ifdef WANT_LOG_NUMWANT
596 case TASK_STATS_NUMWANTS:
597 return stats_return_numwants( reply );
598#endif
599 default:
600 return 0;
601 }
602}
603
604static void stats_make( int *iovec_entries, struct iovec **iovector, ot_tasktype mode ) {
605 char *r;
606
607 *iovec_entries = 0;
608 *iovector = NULL;
609 if( !( r = iovec_increase( iovec_entries, iovector, OT_STATS_TMPSIZE ) ) )
610 return;
611
612 switch( mode & TASK_TASK_MASK ) {
613 case TASK_STATS_TORRENTS: r += stats_torrents_mrtg( r ); break;
614 case TASK_STATS_PEERS: r += stats_peers_mrtg( r ); break;
615 case TASK_STATS_SLASH24S: r += stats_slash24s_txt( r, 128 ); break;
616 case TASK_STATS_TOP10: r += stats_top_txt( r, 10 ); break;
617 case TASK_STATS_TOP100:
618 r = iovec_fix_increase_or_free( iovec_entries, iovector, r, 4 * OT_STATS_TMPSIZE );
619 if( !r ) return;
620 r += stats_top_txt( r, 100 ); break;
621 case TASK_STATS_EVERYTHING: r += stats_return_everything( r ); break;
622#ifdef WANT_SPOT_WOODPECKER
623 case TASK_STATS_WOODPECKERS: r += stats_return_woodpeckers( r, 128 ); break;
624#endif
625#ifdef WANT_FULLLOG_NETWORKS
626 case TASK_STATS_FULLLOG: stats_return_fulllog( iovec_entries, iovector, r );
627 return;
628#endif
629 default:
630 iovec_free(iovec_entries, iovector);
631 return;
632 }
633 iovec_fixlast( iovec_entries, iovector, r );
634}
635
636void stats_issue_event( ot_status_event event, PROTO_FLAG proto, uintptr_t event_data ) {
637 switch( event ) {
638 case EVENT_ACCEPT:
639 if( proto == FLAG_TCP ) ot_overall_tcp_connections++; else ot_overall_udp_connections++;
640#ifdef WANT_LOG_NETWORKS
641 stat_increase_network_count( &stats_network_counters_root, 0, event_data );
642#endif
643 break;
644 case EVENT_ANNOUNCE:
645 if( proto == FLAG_TCP ) ot_overall_tcp_successfulannounces++; else ot_overall_udp_successfulannounces++;
646 break;
647 case EVENT_CONNECT:
648 if( proto == FLAG_TCP ) ot_overall_tcp_connects++; else ot_overall_udp_connects++;
649 break;
650 case EVENT_COMPLETED:
651#ifdef WANT_SYSLOGS
652 if( event_data) {
653 struct ot_workstruct *ws = (struct ot_workstruct *)event_data;
654 char timestring[64];
655 char hash_hex[42], peerid_hex[42], ip_readable[64];
656 struct tm time_now;
657 time_t ttt;
658
659 time( &ttt );
660 localtime_r( &ttt, &time_now );
661 strftime( timestring, sizeof( timestring ), "%FT%T%z", &time_now );
662
663 to_hex( hash_hex, *ws->hash );
664 if( ws->peer_id )
665 to_hex( peerid_hex, (uint8_t*)ws->peer_id );
666 else {
667 *peerid_hex=0;
668 }
669
670#ifdef WANT_V6
671 ip_readable[ fmt_ip6c( ip_readable, (char*)&ws->peer ) ] = 0;
672#else
673 ip_readable[ fmt_ip4( ip_readable, (char*)&ws->peer ) ] = 0;
674#endif
675 syslog( LOG_INFO, "time=%s event=completed info_hash=%s peer_id=%s ip=%s", timestring, hash_hex, peerid_hex, ip_readable );
676 }
677#endif
678 ot_overall_completed++;
679 break;
680 case EVENT_SCRAPE:
681 if( proto == FLAG_TCP ) ot_overall_tcp_successfulscrapes++; else ot_overall_udp_successfulscrapes++;
682 break;
683 case EVENT_FULLSCRAPE:
684 ot_full_scrape_count++;
685 ot_full_scrape_size += event_data;
686 break;
687 case EVENT_FULLSCRAPE_REQUEST:
688 {
689 ot_ip6 *ip = (ot_ip6*)event_data; /* ugly hack to transfer ip to stats */
690 char _debug[512];
691 int off = snprintf( _debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)(g_now_seconds - ot_start_time)/60 );
692 off += fmt_ip6c( _debug+off, *ip );
693 off += snprintf( _debug+off, sizeof(_debug)-off, " - FULL SCRAPE\n" );
694 write( 2, _debug, off );
695 ot_full_scrape_request_count++;
696 }
697 break;
698 case EVENT_FULLSCRAPE_REQUEST_GZIP:
699 {
700 ot_ip6 *ip = (ot_ip6*)event_data; /* ugly hack to transfer ip to stats */
701 char _debug[512];
702 int off = snprintf( _debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)(g_now_seconds - ot_start_time)/60 );
703 off += fmt_ip6c(_debug+off, *ip );
704 off += snprintf( _debug+off, sizeof(_debug)-off, " - FULL SCRAPE\n" );
705 write( 2, _debug, off );
706 ot_full_scrape_request_count++;
707 }
708 break;
709 case EVENT_FAILED:
710 ot_failed_request_counts[event_data]++;
711 break;
712 case EVENT_RENEW:
713 ot_renewed[event_data]++;
714 break;
715 case EVENT_SYNC:
716 ot_overall_sync_count+=event_data;
717 break;
718 case EVENT_BUCKET_LOCKED:
719 ot_overall_stall_count++;
720 break;
721#ifdef WANT_SPOT_WOODPECKER
722 case EVENT_WOODPECKER:
723 pthread_mutex_lock( &g_woodpeckers_mutex );
724 stat_increase_network_count( &stats_woodpeckers_tree, 0, event_data );
725 pthread_mutex_unlock( &g_woodpeckers_mutex );
726 break;
727#endif
728 case EVENT_CONNID_MISSMATCH:
729 ++ot_overall_udp_connectionidmissmatches;
730 default:
731 break;
732 }
733}
734
735void stats_cleanup() {
736#ifdef WANT_SPOT_WOODPECKER
737 pthread_mutex_lock( &g_woodpeckers_mutex );
738 stats_shift_down_network_count( &stats_woodpeckers_tree, 0, 1 );
739 pthread_mutex_unlock( &g_woodpeckers_mutex );
740#endif
741}
742
743static void * stats_worker( void * args ) {
744 int iovec_entries;
745 struct iovec *iovector;
746
747 (void) args;
748
749 while( 1 ) {
750 ot_tasktype tasktype = TASK_STATS;
751 ot_taskid taskid = mutex_workqueue_poptask( &tasktype );
752 stats_make( &iovec_entries, &iovector, tasktype );
753 if( mutex_workqueue_pushresult( taskid, iovec_entries, iovector ) )
754 iovec_free( &iovec_entries, &iovector );
755 }
756 return NULL;
757}
758
759void stats_deliver( int64 sock, int tasktype ) {
760 mutex_workqueue_pushtask( sock, tasktype );
761}
762
763static pthread_t thread_id;
764void stats_init( ) {
765 ot_start_time = g_now_seconds;
766 pthread_create( &thread_id, NULL, stats_worker, NULL );
767}
768
769void stats_deinit( ) {
770 pthread_cancel( thread_id );
771}
772
773const char *g_version_stats_c = "$Source$: $Revision$\n";
diff --git a/ot_stats.h b/ot_stats.h
deleted file mode 100644
index 6a2515b..0000000
--- a/ot_stats.h
+++ /dev/null
@@ -1,52 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_STATS_H__
7#define OT_STATS_H__
8
9typedef enum {
10 EVENT_ACCEPT,
11 EVENT_READ,
12 EVENT_CONNECT, /* UDP only */
13 EVENT_ANNOUNCE,
14 EVENT_COMPLETED,
15 EVENT_RENEW,
16 EVENT_SYNC,
17 EVENT_SCRAPE,
18 EVENT_FULLSCRAPE_REQUEST,
19 EVENT_FULLSCRAPE_REQUEST_GZIP,
20 EVENT_FULLSCRAPE, /* TCP only */
21 EVENT_FAILED,
22 EVENT_BUCKET_LOCKED,
23 EVENT_WOODPECKER,
24 EVENT_CONNID_MISSMATCH
25} ot_status_event;
26
27enum {
28 CODE_HTTPERROR_302,
29 CODE_HTTPERROR_400,
30 CODE_HTTPERROR_400_PARAM,
31 CODE_HTTPERROR_400_COMPACT,
32 CODE_HTTPERROR_402_NOTMODEST,
33 CODE_HTTPERROR_402_PAYMENT_REQUIRED,
34 CODE_HTTPERROR_403_IP,
35 CODE_HTTPERROR_404,
36 CODE_HTTPERROR_500,
37
38 CODE_HTTPERROR_COUNT
39};
40
41void stats_issue_event( ot_status_event event, PROTO_FLAG proto, uintptr_t event_data );
42void stats_deliver( int64 sock, int tasktype );
43void stats_cleanup();
44size_t return_stats_for_tracker( char *reply, int mode, int format );
45size_t stats_return_tracker_version( char *reply );
46void stats_init( );
47void stats_deinit( );
48
49extern const char *g_version_rijndael_c;
50extern const char *g_version_livesync_c;
51
52#endif
diff --git a/ot_sync.c b/ot_sync.c
deleted file mode 100644
index cd66a46..0000000
--- a/ot_sync.c
+++ /dev/null
@@ -1,166 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <sys/types.h>
8#include <sys/mman.h>
9#include <sys/uio.h>
10#include <stdio.h>
11#include <string.h>
12#include <pthread.h>
13
14/* Libowfat */
15#include "scan.h"
16#include "byte.h"
17#include "io.h"
18
19/* Opentracker */
20#include "trackerlogic.h"
21#include "ot_mutex.h"
22#include "ot_sync.h"
23#include "ot_stats.h"
24#include "ot_iovec.h"
25
26#ifdef WANT_SYNC_BATCH
27
28#define OT_SYNC_CHUNK_SIZE (512*1024)
29
30/* Import Changeset from an external authority
31 format: d4:syncd[..]ee
32 [..]: ( 20:01234567890abcdefghij16:XXXXYYYY )+
33*/
34int add_changeset_to_tracker( uint8_t *data, size_t len ) {
35 ot_hash *hash;
36 uint8_t *end = data + len;
37 unsigned long peer_count;
38
39 /* We do know, that the string is \n terminated, so it cant
40 overflow */
41 if( byte_diff( data, 8, "d4:syncd" ) ) return -1;
42 data += 8;
43
44 while( 1 ) {
45 if( byte_diff( data, 3, "20:" ) ) {
46 if( byte_diff( data, 2, "ee" ) )
47 return -1;
48 return 0;
49 }
50 data += 3;
51 hash = (ot_hash*)data;
52 data += sizeof( ot_hash );
53
54 /* Scan string length indicator */
55 data += ( len = scan_ulong( (char*)data, &peer_count ) );
56
57 /* If no long was scanned, it is not divisible by 8, it is not
58 followed by a colon or claims to need to much memory, we fail */
59 if( !len || !peer_count || ( peer_count & 7 ) || ( *data++ != ':' ) || ( data + peer_count > end ) )
60 return -1;
61
62 while( peer_count > 0 ) {
63 add_peer_to_torrent( hash, (ot_peer*)data, 1 );
64 data += 8; peer_count -= 8;
65 }
66 }
67 return 0;
68}
69
70/* Proposed output format
71 d4:syncd20:<info_hash>8*N:(xxxxyyyy)*Nee
72*/
73static void sync_make( int *iovec_entries, struct iovec **iovector ) {
74 int bucket;
75 char *r, *re;
76
77 /* Setup return vector... */
78 *iovec_entries = 0;
79 *iovector = NULL;
80 if( !( r = iovec_increase( iovec_entries, iovector, OT_SYNC_CHUNK_SIZE ) ) )
81 return;
82
83 /* ... and pointer to end of current output buffer.
84 This works as a low watermark */
85 re = r + OT_SYNC_CHUNK_SIZE;
86
87 memmove( r, "d4:syncd", 8 ); r += 8;
88
89 /* For each bucket... */
90 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
91 /* Get exclusive access to that bucket */
92 ot_vector *torrents_list = mutex_bucket_lock( bucket );
93 size_t tor_offset;
94
95 /* For each torrent in this bucket.. */
96 for( tor_offset=0; tor_offset<torrents_list->size; ++tor_offset ) {
97 /* Address torrents members */
98 ot_peerlist *peer_list = ( ((ot_torrent*)(torrents_list->data))[tor_offset] ).peer_list;
99 ot_hash *hash =&( ((ot_torrent*)(torrents_list->data))[tor_offset] ).hash;
100 const size_t byte_count = sizeof(ot_peer) * peer_list->changeset.size;
101
102 /* If we reached our low watermark in buffer... */
103 if( re - r <= (ssize_t)(/* strlen( "20:" ) == */ 3 + sizeof( ot_hash ) + /* strlen_max( "%zd" ) == */ 12 + byte_count ) ) {
104
105 /* Allocate a fresh output buffer at the end of our buffers list
106 release bucket and return, if that fails */
107 if( !( r = iovec_fix_increase_or_free( iovec_entries, iovector, r, OT_SYNC_CHUNK_SIZE ) ) )
108 return mutex_bucket_unlock( bucket );
109
110 /* Adjust new end of output buffer */
111 re = r + OT_SYNC_CHUNK_SIZE;
112 }
113
114 *r++ = '2'; *r++ = '0'; *r++ = ':';
115 memmove( r, hash, sizeof( ot_hash ) ); r += sizeof( ot_hash );
116 r += sprintf( r, "%zd:", byte_count );
117 memmove( r, peer_list->changeset.data, byte_count ); r += byte_count;
118 }
119
120 /* All torrents done: release lock on currenct bucket */
121 mutex_bucket_unlock( bucket );
122 }
123
124 /* Close bencoded sync dictionary */
125 *r++='e'; *r++='e';
126
127 /* Release unused memory in current output buffer */
128 iovec_fixlast( iovec_entries, iovector, r );
129}
130
131/* This is the entry point into this worker thread
132 It grabs tasks from mutex_tasklist and delivers results back
133*/
134static void * sync_worker( void * args) {
135 int iovec_entries;
136 struct iovec *iovector;
137
138 args = args;
139
140 while( 1 ) {
141 ot_tasktype tasktype = TASK_SYNC_OUT;
142 ot_taskid taskid = mutex_workqueue_poptask( &tasktype );
143 sync_make( &iovec_entries, &iovector );
144 stats_issue_event( EVENT_SYNC_OUT, FLAG_TCP, iovec_length( &iovec_entries, &iovector) );
145 if( mutex_workqueue_pushresult( taskid, iovec_entries, iovector ) )
146 iovec_free( &iovec_entries, &iovector );
147 }
148 return NULL;
149}
150
151static pthread_t thread_id;
152void sync_init( ) {
153 pthread_create( &thread_id, NULL, sync_worker, NULL );
154}
155
156void sync_deinit( ) {
157 pthread_cancel( thread_id );
158}
159
160void sync_deliver( int64 socket ) {
161 mutex_workqueue_pushtask( socket, TASK_SYNC_OUT );
162}
163
164#endif
165
166const char *g_version_sync_c = "$Source$: $Revision$\n";
diff --git a/ot_sync.h b/ot_sync.h
deleted file mode 100644
index 441010d..0000000
--- a/ot_sync.h
+++ /dev/null
@@ -1,24 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_SYNC_H__
7#define OT_SYNC_H__
8
9#ifdef WANT_SYNC_BATCH
10enum { SYNC_IN, SYNC_OUT };
11
12void sync_init( );
13void sync_deinit( );
14void sync_deliver( int64 socket );
15
16int add_changeset_to_tracker( uint8_t *data, size_t len );
17#else
18
19#define sync_init()
20#define sync_deinit()
21
22#endif
23
24#endif
diff --git a/ot_udp.c b/ot_udp.c
deleted file mode 100644
index 3bf311c..0000000
--- a/ot_udp.c
+++ /dev/null
@@ -1,215 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <stdlib.h>
8#include <pthread.h>
9#include <string.h>
10#include <arpa/inet.h>
11#include <stdio.h>
12
13/* Libowfat */
14#include "socket.h"
15#include "io.h"
16
17/* Opentracker */
18#include "trackerlogic.h"
19#include "ot_udp.h"
20#include "ot_stats.h"
21#include "ot_rijndael.h"
22
23#if 0
24static const uint8_t g_static_connid[8] = { 0x23, 0x42, 0x05, 0x17, 0xde, 0x41, 0x50, 0xff };
25#endif
26static uint32_t g_rijndael_round_key[44] = {0};
27static uint32_t g_key_of_the_hour[2] = {0};
28static ot_time g_hour_of_the_key;
29
30static void udp_generate_rijndael_round_key() {
31 uint32_t key[16];
32 key[0] = random();
33 key[1] = random();
34 key[2] = random();
35 key[3] = random();
36 rijndaelKeySetupEnc128( g_rijndael_round_key, (uint8_t*)key );
37
38 g_key_of_the_hour[0] = random();
39 g_hour_of_the_key = g_now_minutes;
40}
41
42/* Generate current and previous connection id for ip */
43static void udp_make_connectionid( uint32_t connid[2], const ot_ip6 remoteip, int age ) {
44 uint32_t plain[4], crypt[4];
45 int i;
46 if( g_now_minutes + 60 > g_hour_of_the_key ) {
47 g_hour_of_the_key = g_now_minutes;
48 g_key_of_the_hour[1] = g_key_of_the_hour[0];
49 g_key_of_the_hour[0] = random();
50 }
51
52 memcpy( plain, remoteip, sizeof( plain ) );
53 for( i=0; i<4; ++i ) plain[i] ^= g_key_of_the_hour[age];
54 rijndaelEncrypt128( g_rijndael_round_key, (uint8_t*)remoteip, (uint8_t*)crypt );
55 connid[0] = crypt[0] ^ crypt[1];
56 connid[1] = crypt[2] ^ crypt[3];
57}
58
59/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */
60int handle_udp6( int64 serversocket, struct ot_workstruct *ws ) {
61 ot_ip6 remoteip;
62 uint32_t *inpacket = (uint32_t*)ws->inbuf;
63 uint32_t *outpacket = (uint32_t*)ws->outbuf;
64 uint32_t numwant, left, event, scopeid;
65 uint32_t connid[2];
66 uint32_t action;
67 uint16_t port, remoteport;
68 size_t byte_count, scrape_count;
69
70 byte_count = socket_recv6( serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport, &scopeid );
71 if( !byte_count ) return 0;
72
73 stats_issue_event( EVENT_ACCEPT, FLAG_UDP, (uintptr_t)remoteip );
74 stats_issue_event( EVENT_READ, FLAG_UDP, byte_count );
75
76 /* Minimum udp tracker packet size, also catches error */
77 if( byte_count < 16 )
78 return 1;
79
80 /* Get action to take. Ignore error messages and broken packets */
81 action = ntohl( inpacket[2] );
82 if( action > 2 )
83 return 1;
84
85 /* Generate the connection id we give out and expect to and from
86 the requesting ip address, this prevents udp spoofing */
87 udp_make_connectionid( connid, remoteip, 0 );
88
89 /* Initialise hash pointer */
90 ws->hash = NULL;
91 ws->peer_id = NULL;
92
93 /* If action is not 0 (connect), then we expect the derived
94 connection id in first 64 bit */
95 if( ( action > 0 ) && ( inpacket[0] != connid[0] || inpacket[1] != connid[1] ) ) {
96 /* If connection id does not match, try the one that was
97 valid in the previous hour. Only if this also does not
98 match, return an error packet */
99 udp_make_connectionid( connid, remoteip, 1 );
100 if( inpacket[0] != connid[0] || inpacket[1] != connid[1] ) {
101 const size_t s = sizeof( "Connection ID missmatch." );
102 outpacket[0] = htonl( 3 ); outpacket[1] = inpacket[3];
103 memcpy( &outpacket[2], "Connection ID missmatch.", s );
104 socket_send6( serversocket, ws->outbuf, 8 + s, remoteip, remoteport, 0 );
105 stats_issue_event( EVENT_CONNID_MISSMATCH, FLAG_UDP, 8 + s );
106 return 1;
107 }
108 }
109
110 switch( action ) {
111 case 0: /* This is a connect action */
112 /* look for udp bittorrent magic id */
113 if( (ntohl(inpacket[0]) != 0x00000417) || (ntohl(inpacket[1]) != 0x27101980) )
114 return 1;
115
116 outpacket[0] = 0;
117 outpacket[1] = inpacket[3];
118 outpacket[2] = connid[0];
119 outpacket[3] = connid[1];
120
121 socket_send6( serversocket, ws->outbuf, 16, remoteip, remoteport, 0 );
122 stats_issue_event( EVENT_CONNECT, FLAG_UDP, 16 );
123 break;
124 case 1: /* This is an announce action */
125 /* Minimum udp announce packet size */
126 if( byte_count < 98 )
127 return 1;
128
129 /* We do only want to know, if it is zero */
130 left = inpacket[64/4] | inpacket[68/4];
131
132 /* Limit amount of peers to 200 */
133 numwant = ntohl( inpacket[92/4] );
134 if (numwant > 200) numwant = 200;
135
136 event = ntohl( inpacket[80/4] );
137 port = *(uint16_t*)( ((char*)inpacket) + 96 );
138 ws->hash = (ot_hash*)( ((char*)inpacket) + 16 );
139
140 OT_SETIP( &ws->peer, remoteip );
141 OT_SETPORT( &ws->peer, &port );
142 OT_PEERFLAG( &ws->peer ) = 0;
143
144 switch( event ) {
145 case 1: OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_COMPLETED; break;
146 case 3: OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_STOPPED; break;
147 default: break;
148 }
149
150 if( !left )
151 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_SEEDING;
152
153 outpacket[0] = htonl( 1 ); /* announce action */
154 outpacket[1] = inpacket[12/4];
155
156 if( OT_PEERFLAG( &ws->peer ) & PEER_FLAG_STOPPED ) { /* Peer is gone. */
157 ws->reply = ws->outbuf;
158 ws->reply_size = remove_peer_from_torrent( FLAG_UDP, ws );
159 } else {
160 ws->reply = ws->outbuf + 8;
161 ws->reply_size = 8 + add_peer_to_torrent_and_return_peers( FLAG_UDP, ws, numwant );
162 }
163
164 socket_send6( serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport, 0 );
165 stats_issue_event( EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size );
166 break;
167
168 case 2: /* This is a scrape action */
169 outpacket[0] = htonl( 2 ); /* scrape action */
170 outpacket[1] = inpacket[12/4];
171
172 for( scrape_count = 0; ( scrape_count * 20 < byte_count - 16) && ( scrape_count <= 74 ); scrape_count++ )
173 return_udp_scrape_for_torrent( *(ot_hash*)( ((char*)inpacket) + 16 + 20 * scrape_count ), ((char*)outpacket) + 8 + 12 * scrape_count );
174
175 socket_send6( serversocket, ws->outbuf, 8 + 12 * scrape_count, remoteip, remoteport, 0 );
176 stats_issue_event( EVENT_SCRAPE, FLAG_UDP, scrape_count );
177 break;
178 }
179 return 1;
180}
181
182static void* udp_worker( void * args ) {
183 int64 sock = (int64)args;
184 struct ot_workstruct ws;
185 memset( &ws, 0, sizeof(ws) );
186
187 ws.inbuf=malloc(G_INBUF_SIZE);
188 ws.outbuf=malloc(G_OUTBUF_SIZE);
189#ifdef _DEBUG_HTTPERROR
190 ws.debugbuf=malloc(G_DEBUGBUF_SIZE);
191#endif
192
193 while( g_opentracker_running )
194 handle_udp6( sock, &ws );
195
196 free( ws.inbuf );
197 free( ws.outbuf );
198#ifdef _DEBUG_HTTPERROR
199 free( ws.debugbuf );
200#endif
201 return NULL;
202}
203
204void udp_init( int64 sock, unsigned int worker_count ) {
205 pthread_t thread_id;
206 if( !g_rijndael_round_key[0] )
207 udp_generate_rijndael_round_key();
208#ifdef _DEBUG
209 fprintf( stderr, " installing %d workers on udp socket %ld", worker_count, (unsigned long)sock );
210#endif
211 while( worker_count-- )
212 pthread_create( &thread_id, NULL, udp_worker, (void *)sock );
213}
214
215const char *g_version_udp_c = "$Source$: $Revision$\n";
diff --git a/ot_udp.h b/ot_udp.h
deleted file mode 100644
index 974c727..0000000
--- a/ot_udp.h
+++ /dev/null
@@ -1,12 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_UDP_H__
7#define OT_UDP_H__
8
9void udp_init( int64 sock, unsigned int worker_count );
10int handle_udp6( int64 serversocket, struct ot_workstruct *ws );
11
12#endif
diff --git a/ot_vector.c b/ot_vector.c
deleted file mode 100644
index 2a632b2..0000000
--- a/ot_vector.c
+++ /dev/null
@@ -1,266 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <stdlib.h>
8#include <string.h>
9#include <strings.h>
10#include <stdint.h>
11
12/* Opentracker */
13#include "trackerlogic.h"
14#include "ot_vector.h"
15
16/* Libowfat */
17#include "uint32.h"
18#include "uint16.h"
19
20static int vector_compare_peer(const void *peer1, const void *peer2 ) {
21 return memcmp( peer1, peer2, OT_PEER_COMPARE_SIZE );
22}
23
24/* This function gives us a binary search that returns a pointer, even if
25 no exact match is found. In that case it sets exactmatch 0 and gives
26 calling functions the chance to insert data
27*/
28void *binary_search( const void * const key, const void * base, const size_t member_count, const size_t member_size,
29 size_t compare_size, int *exactmatch ) {
30 size_t interval = member_count;
31
32 while( interval ) {
33 uint8_t *lookat = ((uint8_t*)base) + member_size * ( interval / 2 );
34 int cmp = memcmp( lookat, key, compare_size );
35 if(cmp == 0 ) {
36 base = lookat;
37 break;
38 }
39 if(cmp < 0) {
40 base = lookat + member_size;
41 interval--;
42 }
43 interval /= 2;
44 }
45
46 *exactmatch = interval;
47 return (void*)base;
48}
49
50static uint8_t vector_hash_peer( ot_peer *peer, int bucket_count ) {
51 unsigned int hash = 5381, i = OT_PEER_COMPARE_SIZE;
52 uint8_t *p = (uint8_t*)peer;
53 while( i-- ) hash += (hash<<5) + *(p++);
54 return hash % bucket_count;
55}
56
57/* This is the generic insert operation for our vector type.
58 It tries to locate the object at "key" with size "member_size" by comparing its first "compare_size" bytes with
59 those of objects in vector. Our special "binary_search" function does that and either returns the match or a
60 pointer to where the object is to be inserted. vector_find_or_insert makes space for the object and copies it,
61 if it wasn't found in vector. Caller needs to check the passed "exactmatch" variable to see, whether an insert
62 took place. If resizing the vector failed, NULL is returned, else the pointer to the object in vector.
63*/
64void *vector_find_or_insert( ot_vector *vector, void *key, size_t member_size, size_t compare_size, int *exactmatch ) {
65 uint8_t *match = binary_search( key, vector->data, vector->size, member_size, compare_size, exactmatch );
66
67 if( *exactmatch ) return match;
68
69 if( vector->size + 1 > vector->space ) {
70 size_t new_space = vector->space ? OT_VECTOR_GROW_RATIO * vector->space : OT_VECTOR_MIN_MEMBERS;
71 uint8_t *new_data = realloc( vector->data, new_space * member_size );
72 if( !new_data ) return NULL;
73 /* Adjust pointer if it moved by realloc */
74 match = new_data + (match - (uint8_t*)vector->data);
75
76 vector->data = new_data;
77 vector->space = new_space;
78 }
79 memmove( match + member_size, match, ((uint8_t*)vector->data) + member_size * vector->size - match );
80
81 vector->size++;
82 return match;
83}
84
85ot_peer *vector_find_or_insert_peer( ot_vector *vector, ot_peer *peer, int *exactmatch ) {
86 ot_peer *match;
87
88 /* If space is zero but size is set, we're dealing with a list of vector->size buckets */
89 if( vector->space < vector->size )
90 vector = ((ot_vector*)vector->data) + vector_hash_peer(peer, vector->size );
91 match = (ot_peer*)binary_search( peer, vector->data, vector->size, sizeof(ot_peer), OT_PEER_COMPARE_SIZE, exactmatch );
92
93 if( *exactmatch ) return match;
94
95 if( vector->size + 1 > vector->space ) {
96 size_t new_space = vector->space ? OT_VECTOR_GROW_RATIO * vector->space : OT_VECTOR_MIN_MEMBERS;
97 ot_peer *new_data = realloc( vector->data, new_space * sizeof(ot_peer) );
98 if( !new_data ) return NULL;
99 /* Adjust pointer if it moved by realloc */
100 match = new_data + (match - (ot_peer*)vector->data);
101
102 vector->data = new_data;
103 vector->space = new_space;
104 }
105 memmove( match + 1, match, sizeof(ot_peer) * ( ((ot_peer*)vector->data) + vector->size - match ) );
106
107 vector->size++;
108 return match;
109}
110
111/* This is the non-generic delete from vector-operation specialized for peers in pools.
112 It returns 0 if no peer was found (and thus not removed)
113 1 if a non-seeding peer was removed
114 2 if a seeding peer was removed
115*/
116int vector_remove_peer( ot_vector *vector, ot_peer *peer ) {
117 int exactmatch;
118 ot_peer *match, *end;
119
120 if( !vector->size ) return 0;
121
122 /* If space is zero but size is set, we're dealing with a list of vector->size buckets */
123 if( vector->space < vector->size )
124 vector = ((ot_vector*)vector->data) + vector_hash_peer(peer, vector->size );
125
126 end = ((ot_peer*)vector->data) + vector->size;
127 match = (ot_peer*)binary_search( peer, vector->data, vector->size, sizeof(ot_peer), OT_PEER_COMPARE_SIZE, &exactmatch );
128 if( !exactmatch ) return 0;
129
130 exactmatch = ( OT_PEERFLAG( match ) & PEER_FLAG_SEEDING ) ? 2 : 1;
131 memmove( match, match + 1, sizeof(ot_peer) * ( end - match - 1 ) );
132
133 vector->size--;
134 vector_fixup_peers( vector );
135 return exactmatch;
136}
137
138void vector_remove_torrent( ot_vector *vector, ot_torrent *match ) {
139 ot_torrent *end = ((ot_torrent*)vector->data) + vector->size;
140
141 if( !vector->size ) return;
142
143 /* If this is being called after a unsuccessful malloc() for peer_list
144 in add_peer_to_torrent, match->peer_list actually might be NULL */
145 if( match->peer_list) free_peerlist( match->peer_list );
146
147 memmove( match, match + 1, sizeof(ot_torrent) * ( end - match - 1 ) );
148 if( ( --vector->size * OT_VECTOR_SHRINK_THRESH < vector->space ) && ( vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS ) ) {
149 vector->space /= OT_VECTOR_SHRINK_RATIO;
150 vector->data = realloc( vector->data, vector->space * sizeof( ot_torrent ) );
151 }
152}
153
154void vector_clean_list( ot_vector * vector, int num_buckets ) {
155 while( num_buckets-- )
156 free( vector[num_buckets].data );
157 free( vector );
158 return;
159}
160
161void vector_redistribute_buckets( ot_peerlist * peer_list ) {
162 int tmp, bucket, bucket_size_new, num_buckets_new, num_buckets_old = 1;
163 ot_vector * bucket_list_new, * bucket_list_old = &peer_list->peers;
164
165 if( OT_PEERLIST_HASBUCKETS( peer_list ) ) {
166 num_buckets_old = peer_list->peers.size;
167 bucket_list_old = peer_list->peers.data;
168 }
169
170 if( peer_list->peer_count < 255 )
171 num_buckets_new = 1;
172 else if( peer_list->peer_count > 8192 )
173 num_buckets_new = 64;
174 else if( peer_list->peer_count >= 512 && peer_list->peer_count < 4096 )
175 num_buckets_new = 16;
176 else if( peer_list->peer_count < 512 && num_buckets_old <= 16 )
177 num_buckets_new = num_buckets_old;
178 else if( peer_list->peer_count < 512 )
179 num_buckets_new = 1;
180 else if( peer_list->peer_count < 8192 && num_buckets_old > 1 )
181 num_buckets_new = num_buckets_old;
182 else
183 num_buckets_new = 16;
184
185 if( num_buckets_new == num_buckets_old )
186 return;
187
188 /* Assume near perfect distribution */
189 bucket_list_new = malloc( num_buckets_new * sizeof( ot_vector ) );
190 if( !bucket_list_new) return;
191 bzero( bucket_list_new, num_buckets_new * sizeof( ot_vector ) );
192
193 tmp = peer_list->peer_count / num_buckets_new;
194 bucket_size_new = OT_VECTOR_MIN_MEMBERS;
195 while( bucket_size_new < tmp)
196 bucket_size_new *= OT_VECTOR_GROW_RATIO;
197
198 /* preallocate vectors to hold all peers */
199 for( bucket=0; bucket<num_buckets_new; ++bucket ) {
200 bucket_list_new[bucket].space = bucket_size_new;
201 bucket_list_new[bucket].data = malloc( bucket_size_new * sizeof(ot_peer) );
202 if( !bucket_list_new[bucket].data )
203 return vector_clean_list( bucket_list_new, num_buckets_new );
204 }
205
206 /* Now sort them into the correct bucket */
207 for( bucket=0; bucket<num_buckets_old; ++bucket ) {
208 ot_peer * peers_old = bucket_list_old[bucket].data, * peers_new;
209 int peer_count_old = bucket_list_old[bucket].size;
210 while( peer_count_old-- ) {
211 ot_vector * bucket_dest = bucket_list_new;
212 if( num_buckets_new > 1 )
213 bucket_dest += vector_hash_peer(peers_old, num_buckets_new);
214 if( bucket_dest->size + 1 > bucket_dest->space ) {
215 void * tmp = realloc( bucket_dest->data, sizeof(ot_peer) * OT_VECTOR_GROW_RATIO * bucket_dest->space );
216 if( !tmp ) return vector_clean_list( bucket_list_new, num_buckets_new );
217 bucket_dest->data = tmp;
218 bucket_dest->space *= OT_VECTOR_GROW_RATIO;
219 }
220 peers_new = (ot_peer*)bucket_dest->data;
221 memcpy(peers_new + bucket_dest->size++, peers_old++, sizeof(ot_peer));
222 }
223 }
224
225 /* Now sort each bucket to later allow bsearch */
226 for( bucket=0; bucket<num_buckets_new; ++bucket )
227 qsort( bucket_list_new[bucket].data, bucket_list_new[bucket].size, sizeof( ot_peer ), vector_compare_peer );
228
229 /* Everything worked fine. Now link new bucket_list to peer_list */
230 if( OT_PEERLIST_HASBUCKETS( peer_list) )
231 vector_clean_list( (ot_vector*)peer_list->peers.data, peer_list->peers.size );
232 else
233 free( peer_list->peers.data );
234
235 if( num_buckets_new > 1 ) {
236 peer_list->peers.data = bucket_list_new;
237 peer_list->peers.size = num_buckets_new;
238 peer_list->peers.space = 0; /* Magic marker for "is list of buckets" */
239 } else {
240 peer_list->peers.data = bucket_list_new->data;
241 peer_list->peers.size = bucket_list_new->size;
242 peer_list->peers.space = bucket_list_new->space;
243 free( bucket_list_new );
244 }
245}
246
247void vector_fixup_peers( ot_vector * vector ) {
248 int need_fix = 0;
249
250 if( !vector->size ) {
251 free( vector->data );
252 vector->data = NULL;
253 vector->space = 0;
254 return;
255 }
256
257 while( ( vector->size * OT_VECTOR_SHRINK_THRESH < vector->space ) &&
258 ( vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS ) ) {
259 vector->space /= OT_VECTOR_SHRINK_RATIO;
260 need_fix++;
261 }
262 if( need_fix )
263 vector->data = realloc( vector->data, vector->space * sizeof( ot_peer ) );
264}
265
266const char *g_version_vector_c = "$Source$: $Revision$\n";
diff --git a/ot_vector.h b/ot_vector.h
deleted file mode 100644
index f7f87aa..0000000
--- a/ot_vector.h
+++ /dev/null
@@ -1,34 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_VECTOR_H__
7#define OT_VECTOR_H__
8
9/* These defines control vectors behaviour */
10#define OT_VECTOR_MIN_MEMBERS 2
11#define OT_VECTOR_GROW_RATIO 2
12#define OT_VECTOR_SHRINK_THRESH 4
13#define OT_VECTOR_SHRINK_RATIO 2
14
15#define OT_PEER_BUCKET_MINCOUNT 512
16#define OT_PEER_BUCKET_MAXCOUNT 256
17
18typedef struct {
19 void *data;
20 size_t size;
21 size_t space;
22} ot_vector;
23
24void *binary_search( const void * const key, const void * base, const size_t member_count, const size_t member_size,
25 size_t compare_size, int *exactmatch );
26void *vector_find_or_insert( ot_vector *vector, void *key, size_t member_size, size_t compare_size, int *exactmatch );
27ot_peer *vector_find_or_insert_peer( ot_vector *vector, ot_peer *peer, int *exactmatch );
28
29int vector_remove_peer( ot_vector *vector, ot_peer *peer );
30void vector_remove_torrent( ot_vector *vector, ot_torrent *match );
31void vector_redistribute_buckets( ot_peerlist * peer_list );
32void vector_fixup_peers( ot_vector * vector );
33
34#endif
diff --git a/proxy.c b/proxy.c
deleted file mode 100644
index 1f09777..0000000
--- a/proxy.c
+++ /dev/null
@@ -1,844 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $Id$ */
5
6/* System */
7#include <stdint.h>
8#include <stdlib.h>
9#include <string.h>
10#include <arpa/inet.h>
11#include <sys/socket.h>
12#include <unistd.h>
13#include <errno.h>
14#include <signal.h>
15#include <stdio.h>
16#include <pwd.h>
17#include <ctype.h>
18#include <pthread.h>
19
20/* Libowfat */
21#include "socket.h"
22#include "io.h"
23#include "iob.h"
24#include "byte.h"
25#include "scan.h"
26#include "ip6.h"
27#include "ndelay.h"
28
29/* Opentracker */
30#include "trackerlogic.h"
31#include "ot_vector.h"
32#include "ot_mutex.h"
33#include "ot_stats.h"
34
35#ifndef WANT_SYNC_LIVE
36#define WANT_SYNC_LIVE
37#endif
38#include "ot_livesync.h"
39
40ot_ip6 g_serverip;
41uint16_t g_serverport = 9009;
42uint32_t g_tracker_id;
43char groupip_1[4] = { 224,0,23,5 };
44int g_self_pipe[2];
45
46/* If you have more than 10 peers, don't use this proxy
47 Use 20 slots for 10 peers to have room for 10 incoming connection slots
48 */
49#define MAX_PEERS 20
50
51#define LIVESYNC_INCOMING_BUFFSIZE (256*256)
52#define STREAMSYNC_OUTGOING_BUFFSIZE (256*256)
53
54#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480
55#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_peer)+sizeof(ot_hash))
56#define LIVESYNC_MAXDELAY 15 /* seconds */
57
58/* The amount of time a complete sync cycle should take */
59#define OT_SYNC_INTERVAL_MINUTES 2
60
61/* So after each bucket wait 1 / OT_BUCKET_COUNT intervals */
62#define OT_SYNC_SLEEP ( ( ( OT_SYNC_INTERVAL_MINUTES ) * 60 * 1000000 ) / ( OT_BUCKET_COUNT ) )
63
64enum { OT_SYNC_PEER };
65enum { FLAG_SERVERSOCKET = 1 };
66
67/* For incoming packets */
68static int64 g_socket_in = -1;
69static uint8_t g_inbuffer[LIVESYNC_INCOMING_BUFFSIZE];
70
71/* For outgoing packets */
72static int64 g_socket_out = -1;
73static uint8_t g_peerbuffer_start[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
74static uint8_t *g_peerbuffer_pos;
75static uint8_t *g_peerbuffer_highwater = g_peerbuffer_start + LIVESYNC_OUTGOING_BUFFSIZE_PEERS - LIVESYNC_OUTGOING_WATERMARK_PEERS;
76static ot_time g_next_packet_time;
77
78static void * livesync_worker( void * args );
79static void * streamsync_worker( void * args );
80static void livesync_proxytell( uint8_t prefix, uint8_t *info_hash, uint8_t *peer );
81
82void exerr( char * message ) {
83 fprintf( stderr, "%s\n", message );
84 exit( 111 );
85}
86
87void stats_issue_event( ot_status_event event, PROTO_FLAG proto, uintptr_t event_data ) {
88 (void) event;
89 (void) proto;
90 (void) event_data;
91}
92
93void livesync_bind_mcast( ot_ip6 ip, uint16_t port) {
94 char tmpip[4] = {0,0,0,0};
95 char *v4ip;
96
97 if( !ip6_isv4mapped(ip))
98 exerr("v6 mcast support not yet available.");
99 v4ip = ip+12;
100
101 if( g_socket_in != -1 )
102 exerr("Error: Livesync listen ip specified twice.");
103
104 if( ( g_socket_in = socket_udp4( )) < 0)
105 exerr("Error: Cant create live sync incoming socket." );
106 ndelay_off(g_socket_in);
107
108 if( socket_bind4_reuse( g_socket_in, tmpip, port ) == -1 )
109 exerr("Error: Cant bind live sync incoming socket." );
110
111 if( socket_mcjoin4( g_socket_in, groupip_1, v4ip ) )
112 exerr("Error: Cant make live sync incoming socket join mcast group.");
113
114 if( ( g_socket_out = socket_udp4()) < 0)
115 exerr("Error: Cant create live sync outgoing socket." );
116 if( socket_bind4_reuse( g_socket_out, v4ip, port ) == -1 )
117 exerr("Error: Cant bind live sync outgoing socket." );
118
119 socket_mcttl4(g_socket_out, 1);
120 socket_mcloop4(g_socket_out, 1);
121}
122
123size_t add_peer_to_torrent_proxy( ot_hash hash, ot_peer *peer ) {
124 int exactmatch;
125 ot_torrent *torrent;
126 ot_peer *peer_dest;
127 ot_vector *torrents_list = mutex_bucket_lock_by_hash( hash );
128
129 torrent = vector_find_or_insert( torrents_list, (void*)hash, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
130 if( !torrent )
131 return -1;
132
133 if( !exactmatch ) {
134 /* Create a new torrent entry, then */
135 memcpy( torrent->hash, hash, sizeof(ot_hash) );
136
137 if( !( torrent->peer_list = malloc( sizeof (ot_peerlist) ) ) ) {
138 vector_remove_torrent( torrents_list, torrent );
139 mutex_bucket_unlock_by_hash( hash, 0 );
140 return -1;
141 }
142
143 byte_zero( torrent->peer_list, sizeof( ot_peerlist ) );
144 }
145
146 /* Check for peer in torrent */
147 peer_dest = vector_find_or_insert_peer( &(torrent->peer_list->peers), peer, &exactmatch );
148 if( !peer_dest ) {
149 mutex_bucket_unlock_by_hash( hash, 0 );
150 return -1;
151 }
152 /* Tell peer that it's fresh */
153 OT_PEERTIME( peer ) = 0;
154
155 /* If we hadn't had a match create peer there */
156 if( !exactmatch ) {
157 torrent->peer_list->peer_count++;
158 if( OT_PEERFLAG(peer) & PEER_FLAG_SEEDING )
159 torrent->peer_list->seed_count++;
160 }
161 memcpy( peer_dest, peer, sizeof(ot_peer) );
162 mutex_bucket_unlock_by_hash( hash, 0 );
163 return 0;
164}
165
166size_t remove_peer_from_torrent_proxy( ot_hash hash, ot_peer *peer ) {
167 int exactmatch;
168 ot_vector *torrents_list = mutex_bucket_lock_by_hash( hash );
169 ot_torrent *torrent = binary_search( hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
170
171 if( exactmatch ) {
172 ot_peerlist *peer_list = torrent->peer_list;
173 switch( vector_remove_peer( &peer_list->peers, peer ) ) {
174 case 2: peer_list->seed_count--; /* Fall throughs intended */
175 case 1: peer_list->peer_count--; /* Fall throughs intended */
176 default: break;
177 }
178 }
179
180 mutex_bucket_unlock_by_hash( hash, 0 );
181 return 0;
182}
183
184void free_peerlist( ot_peerlist *peer_list ) {
185 if( peer_list->peers.data ) {
186 if( OT_PEERLIST_HASBUCKETS( peer_list ) ) {
187 ot_vector *bucket_list = (ot_vector*)(peer_list->peers.data);
188
189 while( peer_list->peers.size-- )
190 free( bucket_list++->data );
191 }
192 free( peer_list->peers.data );
193 }
194 free( peer_list );
195}
196
197static void livesync_handle_peersync( ssize_t datalen ) {
198 int off = sizeof( g_tracker_id ) + sizeof( uint32_t );
199
200 fprintf( stderr, "." );
201
202 while( off + (ssize_t)sizeof( ot_hash ) + (ssize_t)sizeof( ot_peer ) <= datalen ) {
203 ot_peer *peer = (ot_peer*)(g_inbuffer + off + sizeof(ot_hash));
204 ot_hash *hash = (ot_hash*)(g_inbuffer + off);
205
206 if( OT_PEERFLAG(peer) & PEER_FLAG_STOPPED )
207 remove_peer_from_torrent_proxy( *hash, peer );
208 else
209 add_peer_to_torrent_proxy( *hash, peer );
210
211 off += sizeof( ot_hash ) + sizeof( ot_peer );
212 }
213}
214
215int usage( char *self ) {
216 fprintf( stderr, "Usage: %s -L <livesync_iface_ip> -l <listenip>:<listenport> -c <connectip>:<connectport>\n", self );
217 return 0;
218}
219
220enum {
221 FLAG_OUTGOING = 0x80,
222
223 FLAG_DISCONNECTED = 0x00,
224 FLAG_CONNECTING = 0x01,
225 FLAG_WAITTRACKERID = 0x02,
226 FLAG_CONNECTED = 0x03,
227
228 FLAG_MASK = 0x07
229};
230
231#define PROXYPEER_NEEDSCONNECT(flag) ((flag)==FLAG_OUTGOING)
232#define PROXYPEER_ISCONNECTED(flag) (((flag)&FLAG_MASK)==FLAG_CONNECTED)
233#define PROXYPEER_SETDISCONNECTED(flag) (flag)=(((flag)&FLAG_OUTGOING)|FLAG_DISCONNECTED)
234#define PROXYPEER_SETCONNECTING(flag) (flag)=(((flag)&FLAG_OUTGOING)|FLAG_CONNECTING)
235#define PROXYPEER_SETWAITTRACKERID(flag) (flag)=(((flag)&FLAG_OUTGOING)|FLAG_WAITTRACKERID)
236#define PROXYPEER_SETCONNECTED(flag) (flag)=(((flag)&FLAG_OUTGOING)|FLAG_CONNECTED)
237
238typedef struct {
239 int state; /* Whether we want to connect, how far our handshake is, etc. */
240 ot_ip6 ip; /* The peer to connect to */
241 uint16_t port; /* The peers port */
242 uint8_t indata[8192*16]; /* Any data not processed yet */
243 size_t indata_length; /* Length of unprocessed data */
244 uint32_t tracker_id; /* How the other end greeted */
245 int64 fd; /* A file handle, if connected, <= 0 is disconnected (0 initially, -1 else) */
246 io_batch outdata; /* The iobatch containing our sync data */
247
248 size_t packet_tcount; /* Number of unprocessed torrents in packet we currently receive */
249 uint8_t packet_tprefix; /* Prefix byte for all torrents in current packet */
250 uint8_t packet_type; /* Type of current packet */
251 uint32_t packet_tid; /* Tracker id for current packet */
252
253} proxy_peer;
254static void process_indata( proxy_peer * peer );
255
256void reset_info_block( proxy_peer * peer ) {
257 peer->indata_length = 0;
258 peer->tracker_id = 0;
259 peer->fd = -1;
260 peer->packet_tcount = 0;
261 iob_reset( &peer->outdata );
262 PROXYPEER_SETDISCONNECTED( peer->state );
263}
264
265/* Number of connections to peers
266 * If a peer's IP is set, we try to reconnect, when the connection drops
267 * If we already have a connected tracker_id in our records for an _incoming_ connection, drop it
268 * Multiple connections to/from the same ip are okay, if tracker_id doesn't match
269 * Reconnect attempts occur only twice a minute
270*/
271static int g_connection_count;
272static ot_time g_connection_reconn;
273static proxy_peer g_connections[MAX_PEERS];
274
275static void handle_reconnects( void ) {
276 int i;
277 for( i=0; i<g_connection_count; ++i )
278 if( PROXYPEER_NEEDSCONNECT( g_connections[i].state ) ) {
279 int64 newfd = socket_tcp6( );
280 fprintf( stderr, "(Re)connecting to peer..." );
281 if( newfd < 0 ) continue; /* No socket for you */
282 io_fd(newfd);
283 if( socket_bind6_reuse(newfd,g_serverip,g_serverport,0) ) {
284 io_close( newfd );
285 continue;
286 }
287 if( socket_connect6(newfd,g_connections[i].ip,g_connections[i].port,0) == -1 &&
288 errno != EINPROGRESS && errno != EWOULDBLOCK ) {
289 close(newfd);
290 continue;
291 }
292 io_wantwrite(newfd); /* So we will be informed when it is connected */
293 io_setcookie(newfd,g_connections+i);
294
295 /* Prepare connection info block */
296 reset_info_block( g_connections+i );
297 g_connections[i].fd = newfd;
298 PROXYPEER_SETCONNECTING( g_connections[i].state );
299 }
300 g_connection_reconn = time(NULL) + 30;
301}
302
303/* Handle incoming connection requests, check against whitelist */
304static void handle_accept( int64 serversocket ) {
305 int64 newfd;
306 ot_ip6 ip;
307 uint16 port;
308
309 while( ( newfd = socket_accept6( serversocket, ip, &port, NULL ) ) != -1 ) {
310
311 /* XXX some access control */
312
313 /* Put fd into a non-blocking mode */
314 io_nonblock( newfd );
315
316 if( !io_fd( newfd ) )
317 io_close( newfd );
318 else {
319 /* Find a new home for our incoming connection */
320 int i;
321 for( i=0; i<MAX_PEERS; ++i )
322 if( g_connections[i].state == FLAG_DISCONNECTED )
323 break;
324 if( i == MAX_PEERS ) {
325 fprintf( stderr, "No room for incoming connection." );
326 close( newfd );
327 continue;
328 }
329
330 /* Prepare connection info block */
331 reset_info_block( g_connections+i );
332 PROXYPEER_SETCONNECTING( g_connections[i].state );
333 g_connections[i].port = port;
334 g_connections[i].fd = newfd;
335
336 io_setcookie( newfd, g_connections + i );
337
338 /* We expect the connecting side to begin with its tracker_id */
339 io_wantread( newfd );
340 }
341 }
342
343 return;
344}
345
346/* New sync data on the stream */
347static void handle_read( int64 peersocket ) {
348 int i;
349 int64 datalen;
350 uint32_t tracker_id;
351 proxy_peer *peer = io_getcookie( peersocket );
352
353 if( !peer ) {
354 /* Can't happen ;) */
355 io_close( peersocket );
356 return;
357 }
358 switch( peer->state & FLAG_MASK ) {
359 case FLAG_DISCONNECTED:
360 io_close( peersocket );
361 break; /* Shouldnt happen */
362 case FLAG_CONNECTING:
363 case FLAG_WAITTRACKERID:
364 /* We want at least the first four bytes to come at once, to avoid keeping extra states (for now)
365 This also catches 0 bytes reads == EOF and negative values, denoting connection errors */
366 if( io_tryread( peersocket, (void*)&tracker_id, sizeof( tracker_id ) ) != sizeof( tracker_id ) )
367 goto close_socket;
368
369 /* See, if we already have a connection to that peer */
370 for( i=0; i<MAX_PEERS; ++i )
371 if( ( g_connections[i].state & FLAG_MASK ) == FLAG_CONNECTED &&
372 g_connections[i].tracker_id == tracker_id ) {
373 fprintf( stderr, "Peer already connected. Closing connection.\n" );
374 goto close_socket;
375 }
376
377 /* Also no need for soliloquy */
378 if( tracker_id == g_tracker_id )
379 goto close_socket;
380
381 /* The new connection is good, send our tracker_id on incoming connections */
382 if( peer->state == FLAG_CONNECTING )
383 if( io_trywrite( peersocket, (void*)&g_tracker_id, sizeof( g_tracker_id ) ) != sizeof( g_tracker_id ) )
384 goto close_socket;
385
386 peer->tracker_id = tracker_id;
387 PROXYPEER_SETCONNECTED( peer->state );
388
389 if( peer->state & FLAG_OUTGOING )
390 fprintf( stderr, "succeeded.\n" );
391 else
392 fprintf( stderr, "Incoming connection successful.\n" );
393
394 break;
395close_socket:
396 fprintf( stderr, "Handshake incomplete, closing socket\n" );
397 io_close( peersocket );
398 reset_info_block( peer );
399 break;
400 case FLAG_CONNECTED:
401 /* Here we acutally expect data from peer
402 indata_length should be less than 20+256*7 bytes, for incomplete torrent entries */
403 datalen = io_tryread( peersocket, (void*)(peer->indata + peer->indata_length), sizeof( peer->indata ) - peer->indata_length );
404 if( !datalen || datalen < -1 ) {
405 fprintf( stderr, "Connection closed by remote peer.\n" );
406 io_close( peersocket );
407 reset_info_block( peer );
408 } else if( datalen > 0 ) {
409 peer->indata_length += datalen;
410 process_indata( peer );
411 }
412 break;
413 }
414}
415
416/* Can write new sync data to the stream */
417static void handle_write( int64 peersocket ) {
418 proxy_peer *peer = io_getcookie( peersocket );
419
420 if( !peer ) {
421 /* Can't happen ;) */
422 io_close( peersocket );
423 return;
424 }
425
426 switch( peer->state & FLAG_MASK ) {
427 case FLAG_DISCONNECTED:
428 default: /* Should not happen */
429 io_close( peersocket );
430 break;
431 case FLAG_CONNECTING:
432 /* Ensure that the connection is established and handle connection error */
433 if( peer->state & FLAG_OUTGOING && !socket_connected( peersocket ) ) {
434 fprintf( stderr, "failed\n" );
435 reset_info_block( peer );
436 io_close( peersocket );
437 break;
438 }
439
440 if( io_trywrite( peersocket, (void*)&g_tracker_id, sizeof( g_tracker_id ) ) == sizeof( g_tracker_id ) ) {
441 PROXYPEER_SETWAITTRACKERID( peer->state );
442 io_dontwantwrite( peersocket );
443 io_wantread( peersocket );
444 } else {
445 fprintf( stderr, "Handshake incomplete, closing socket\n" );
446 io_close( peersocket );
447 reset_info_block( peer );
448 }
449 break;
450 case FLAG_CONNECTED:
451 switch( iob_send( peersocket, &peer->outdata ) ) {
452 case 0: /* all data sent */
453 io_dontwantwrite( peersocket );
454 break;
455 case -3: /* an error occured */
456 io_close( peersocket );
457 reset_info_block( peer );
458 break;
459 default: /* Normal operation or eagain */
460 break;
461 }
462 break;
463 }
464
465 return;
466}
467
468static void server_mainloop() {
469 int64 sock;
470
471 /* inlined livesync_init() */
472 memset( g_peerbuffer_start, 0, sizeof( g_peerbuffer_start ) );
473 g_peerbuffer_pos = g_peerbuffer_start;
474 memcpy( g_peerbuffer_pos, &g_tracker_id, sizeof( g_tracker_id ) );
475 uint32_pack_big( (char*)g_peerbuffer_pos + sizeof( g_tracker_id ), OT_SYNC_PEER);
476 g_peerbuffer_pos += sizeof( g_tracker_id ) + sizeof( uint32_t);
477 g_next_packet_time = time(NULL) + LIVESYNC_MAXDELAY;
478
479 while(1) {
480 /* See, if we need to connect to anyone */
481 if( time(NULL) > g_connection_reconn )
482 handle_reconnects( );
483
484 /* Wait for io events until next approx reconn check time */
485 io_waituntil2( 30*1000 );
486
487 /* Loop over readable sockets */
488 while( ( sock = io_canread( ) ) != -1 ) {
489 const void *cookie = io_getcookie( sock );
490 if( (uintptr_t)cookie == FLAG_SERVERSOCKET )
491 handle_accept( sock );
492 else
493 handle_read( sock );
494 }
495
496 /* Loop over writable sockets */
497 while( ( sock = io_canwrite( ) ) != -1 )
498 handle_write( sock );
499
500 livesync_ticker( );
501 }
502}
503
504static void panic( const char *routine ) {
505 fprintf( stderr, "%s: %s\n", routine, strerror(errno) );
506 exit( 111 );
507}
508
509static int64_t ot_try_bind( ot_ip6 ip, uint16_t port ) {
510 int64 sock = socket_tcp6( );
511
512 if( socket_bind6_reuse( sock, ip, port, 0 ) == -1 )
513 panic( "socket_bind6_reuse" );
514
515 if( socket_listen( sock, SOMAXCONN) == -1 )
516 panic( "socket_listen" );
517
518 if( !io_fd( sock ) )
519 panic( "io_fd" );
520
521 io_setcookie( sock, (void*)FLAG_SERVERSOCKET );
522 io_wantread( sock );
523 return sock;
524}
525
526
527static int scan_ip6_port( const char *src, ot_ip6 ip, uint16 *port ) {
528 const char *s = src;
529 int off, bracket = 0;
530 while( isspace(*s) ) ++s;
531 if( *s == '[' ) ++s, ++bracket; /* for v6 style notation */
532 if( !(off = scan_ip6( s, ip ) ) )
533 return 0;
534 s += off;
535 if( *s == 0 || isspace(*s)) return s-src;
536 if( *s == ']' && bracket ) ++s;
537 if( !ip6_isv4mapped(ip)){
538 if( ( bracket && *(s) != ':' ) || ( *(s) != '.' ) ) return 0;
539 s++;
540 } else {
541 if( *(s++) != ':' ) return 0;
542 }
543 if( !(off = scan_ushort (s, port ) ) )
544 return 0;
545 return off+s-src;
546}
547
548int main( int argc, char **argv ) {
549 static pthread_t sync_in_thread_id;
550 static pthread_t sync_out_thread_id;
551 ot_ip6 serverip;
552 uint16_t tmpport;
553 int scanon = 1, lbound = 0, sbound = 0;
554
555 srandom( time(NULL) );
556 g_tracker_id = random();
557 noipv6=1;
558
559 while( scanon ) {
560 switch( getopt( argc, argv, ":l:c:L:h" ) ) {
561 case -1: scanon = 0; break;
562 case 'l':
563 tmpport = 0;
564 if( !scan_ip6_port( optarg, serverip, &tmpport ) || !tmpport ) { usage( argv[0] ); exit( 1 ); }
565 ot_try_bind( serverip, tmpport );
566 ++sbound;
567 break;
568 case 'c':
569 if( g_connection_count > MAX_PEERS / 2 ) exerr( "Connection limit exceeded.\n" );
570 tmpport = 0;
571 if( !scan_ip6_port( optarg,
572 g_connections[g_connection_count].ip,
573 &g_connections[g_connection_count].port ) ||
574 !g_connections[g_connection_count].port ) { usage( argv[0] ); exit( 1 ); }
575 g_connections[g_connection_count++].state = FLAG_OUTGOING;
576 break;
577 case 'L':
578 tmpport = 9696;
579 if( !scan_ip6_port( optarg, serverip, &tmpport ) || !tmpport ) { usage( argv[0] ); exit( 1 ); }
580 livesync_bind_mcast( serverip, tmpport); ++lbound; break;
581 default:
582 case '?': usage( argv[0] ); exit( 1 );
583 }
584 }
585
586 if( !lbound ) exerr( "No livesync port bound." );
587 if( !g_connection_count && !sbound ) exerr( "No streamsync port bound." );
588 pthread_create( &sync_in_thread_id, NULL, livesync_worker, NULL );
589 pthread_create( &sync_out_thread_id, NULL, streamsync_worker, NULL );
590
591 server_mainloop();
592 return 0;
593}
594
595static void * streamsync_worker( void * args ) {
596 (void)args;
597 while( 1 ) {
598 int bucket;
599 /* For each bucket... */
600 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
601 /* Get exclusive access to that bucket */
602 ot_vector *torrents_list = mutex_bucket_lock( bucket );
603 size_t tor_offset, count_def = 0, count_one = 0, count_two = 0, count_peers = 0;
604 size_t mem, mem_a = 0, mem_b = 0;
605 uint8_t *ptr = 0, *ptr_a, *ptr_b, *ptr_c;
606
607 if( !torrents_list->size ) goto unlock_continue;
608
609 /* For each torrent in this bucket.. */
610 for( tor_offset=0; tor_offset<torrents_list->size; ++tor_offset ) {
611 /* Address torrents members */
612 ot_peerlist *peer_list = ( ((ot_torrent*)(torrents_list->data))[tor_offset] ).peer_list;
613 switch( peer_list->peer_count ) {
614 case 2: count_two++; break;
615 case 1: count_one++; break;
616 case 0: break;
617 default: count_def++;
618 count_peers += peer_list->peer_count;
619 }
620 }
621
622 /* Maximal memory requirement: max 3 blocks, max torrents * 20 + max peers * 7 */
623 mem = 3 * ( 1 + 1 + 2 ) + ( count_one + count_two ) * ( 19 + 1 ) + count_def * ( 19 + 8 ) +
624 ( count_one + 2 * count_two + count_peers ) * 7;
625
626 fprintf( stderr, "Mem: %zd\n", mem );
627
628 ptr = ptr_a = ptr_b = ptr_c = malloc( mem );
629 if( !ptr ) goto unlock_continue;
630
631 if( count_one > 4 || !count_def ) {
632 mem_a = 1 + 1 + 2 + count_one * ( 19 + 7 );
633 ptr_b += mem_a; ptr_c += mem_a;
634 ptr_a[0] = 1; /* Offset 0: packet type 1 */
635 ptr_a[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
636 ptr_a[2] = count_one >> 8;
637 ptr_a[3] = count_one & 255;
638 ptr_a += 4;
639 } else
640 count_def += count_one;
641
642 if( count_two > 4 || !count_def ) {
643 mem_b = 1 + 1 + 2 + count_two * ( 19 + 14 );
644 ptr_c += mem_b;
645 ptr_b[0] = 2; /* Offset 0: packet type 2 */
646 ptr_b[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
647 ptr_b[2] = count_two >> 8;
648 ptr_b[3] = count_two & 255;
649 ptr_b += 4;
650 } else
651 count_def += count_two;
652
653 if( count_def ) {
654 ptr_c[0] = 0; /* Offset 0: packet type 0 */
655 ptr_c[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
656 ptr_c[2] = count_def >> 8;
657 ptr_c[3] = count_def & 255;
658 ptr_c += 4;
659 }
660
661 /* For each torrent in this bucket.. */
662 for( tor_offset=0; tor_offset<torrents_list->size; ++tor_offset ) {
663 /* Address torrents members */
664 ot_torrent *torrent = ((ot_torrent*)(torrents_list->data)) + tor_offset;
665 ot_peerlist *peer_list = torrent->peer_list;
666 ot_peer *peers = (ot_peer*)(peer_list->peers.data);
667 uint8_t **dst;
668
669 /* Determine destination slot */
670 count_peers = peer_list->peer_count;
671 switch( count_peers ) {
672 case 0: continue;
673 case 1: dst = mem_a ? &ptr_a : &ptr_c; break;
674 case 2: dst = mem_b ? &ptr_b : &ptr_c; break;
675 default: dst = &ptr_c; break;
676 }
677
678 /* Copy tail of info_hash, advance pointer */
679 memcpy( *dst, ((uint8_t*)torrent->hash) + 1, sizeof( ot_hash ) - 1);
680 *dst += sizeof( ot_hash ) - 1;
681
682 /* Encode peer count */
683 if( dst == &ptr_c )
684 while( count_peers ) {
685 if( count_peers <= 0x7f )
686 *(*dst)++ = count_peers;
687 else
688 *(*dst)++ = 0x80 | ( count_peers & 0x7f );
689 count_peers >>= 7;
690 }
691
692 /* Copy peers */
693 count_peers = peer_list->peer_count;
694 while( count_peers-- ) {
695 memcpy( *dst, peers++, OT_IP_SIZE + 3 );
696 *dst += OT_IP_SIZE + 3;
697 }
698 free_peerlist(peer_list);
699 }
700
701 free( torrents_list->data );
702 memset( torrents_list, 0, sizeof(*torrents_list ) );
703unlock_continue:
704 mutex_bucket_unlock( bucket, 0 );
705
706 if( ptr ) {
707 int i;
708
709 if( ptr_b > ptr_c ) ptr_c = ptr_b;
710 if( ptr_a > ptr_c ) ptr_c = ptr_a;
711 mem = ptr_c - ptr;
712
713 for( i=0; i < MAX_PEERS; ++i ) {
714 if( PROXYPEER_ISCONNECTED(g_connections[i].state) ) {
715 void *tmp = malloc( mem );
716 if( tmp ) {
717 memcpy( tmp, ptr, mem );
718 iob_addbuf_free( &g_connections[i].outdata, tmp, mem );
719 io_wantwrite( g_connections[i].fd );
720 }
721 }
722 }
723
724 free( ptr );
725 }
726 usleep( OT_SYNC_SLEEP );
727 }
728 }
729 return 0;
730}
731
732static void livesync_issue_peersync( ) {
733 socket_send4(g_socket_out, (char*)g_peerbuffer_start, g_peerbuffer_pos - g_peerbuffer_start,
734 groupip_1, LIVESYNC_PORT);
735 g_peerbuffer_pos = g_peerbuffer_start + sizeof( g_tracker_id ) + sizeof( uint32_t );
736 g_next_packet_time = time(NULL) + LIVESYNC_MAXDELAY;
737}
738
739void livesync_ticker( ) {
740 /* livesync_issue_peersync sets g_next_packet_time */
741 if( time(NULL) > g_next_packet_time &&
742 g_peerbuffer_pos > g_peerbuffer_start + sizeof( g_tracker_id ) )
743 livesync_issue_peersync();
744}
745
746static void livesync_proxytell( uint8_t prefix, uint8_t *info_hash, uint8_t *peer ) {
747// unsigned int i;
748
749 *g_peerbuffer_pos = prefix;
750 memcpy( g_peerbuffer_pos + 1, info_hash, sizeof(ot_hash) - 1 );
751 memcpy( g_peerbuffer_pos + sizeof(ot_hash), peer, sizeof(ot_peer) - 1 );
752
753#if 0
754 /* Dump info_hash */
755 for( i=0; i<sizeof(ot_hash); ++i )
756 printf( "%02X", g_peerbuffer_pos[i] );
757 putchar( ':' );
758#endif
759 g_peerbuffer_pos += sizeof(ot_hash);
760#if 0
761 printf( "%hhu.%hhu.%hhu.%hhu:%hu (%02X %02X)\n", g_peerbuffer_pos[0], g_peerbuffer_pos[1], g_peerbuffer_pos[2], g_peerbuffer_pos[3],
762 g_peerbuffer_pos[4] | ( g_peerbuffer_pos[5] << 8 ), g_peerbuffer_pos[6], g_peerbuffer_pos[7] );
763#endif
764 g_peerbuffer_pos += sizeof(ot_peer);
765
766 if( g_peerbuffer_pos >= g_peerbuffer_highwater )
767 livesync_issue_peersync();
768}
769
770static void process_indata( proxy_peer * peer ) {
771 size_t consumed, peers;
772 uint8_t *data = peer->indata, *hash;
773 uint8_t *dataend = data + peer->indata_length;
774
775 while( 1 ) {
776 /* If we're not inside of a packet, make a new one */
777 if( !peer->packet_tcount ) {
778 /* Ensure the header is complete or postpone processing */
779 if( data + 4 > dataend ) break;
780 peer->packet_type = data[0];
781 peer->packet_tprefix = data[1];
782 peer->packet_tcount = data[2] * 256 + data[3];
783 data += 4;
784printf( "type: %hhu, prefix: %02X, torrentcount: %zd\n", peer->packet_type, peer->packet_tprefix, peer->packet_tcount );
785 }
786
787 /* Ensure size for a minimal torrent block */
788 if( data + sizeof(ot_hash) + OT_IP_SIZE + 3 > dataend ) break;
789
790 /* Advance pointer to peer count or peers */
791 hash = data;
792 data += sizeof(ot_hash) - 1;
793
794 /* Type 0 has peer count encoded before each peers */
795 peers = peer->packet_type;
796 if( !peers ) {
797 int shift = 0;
798 do peers |= ( 0x7f & *data ) << ( 7 * shift );
799 while ( *(data++) & 0x80 && shift++ < 6 );
800 }
801#if 0
802printf( "peers: %zd\n", peers );
803#endif
804 /* Ensure enough data being read to hold all peers */
805 if( data + (OT_IP_SIZE + 3) * peers > dataend ) {
806 data = hash;
807 break;
808 }
809 while( peers-- ) {
810 livesync_proxytell( peer->packet_tprefix, hash, data );
811 data += OT_IP_SIZE + 3;
812 }
813 --peer->packet_tcount;
814 }
815
816 consumed = data - peer->indata;
817 memmove( peer->indata, data, peer->indata_length - consumed );
818 peer->indata_length -= consumed;
819}
820
821static void * livesync_worker( void * args ) {
822 (void)args;
823 while( 1 ) {
824 ot_ip6 in_ip; uint16_t in_port;
825 size_t datalen = socket_recv4(g_socket_in, (char*)g_inbuffer, LIVESYNC_INCOMING_BUFFSIZE, 12+(char*)in_ip, &in_port);
826
827 /* Expect at least tracker id and packet type */
828 if( datalen <= (ssize_t)(sizeof( g_tracker_id ) + sizeof( uint32_t )) )
829 continue;
830 if( !memcmp( g_inbuffer, &g_tracker_id, sizeof( g_tracker_id ) ) ) {
831 /* drop packet coming from ourselves */
832 continue;
833 }
834 switch( uint32_read_big( sizeof( g_tracker_id ) + (char*)g_inbuffer ) ) {
835 case OT_SYNC_PEER:
836 livesync_handle_peersync( datalen );
837 break;
838 default:
839 // fprintf( stderr, "Received an unknown live sync packet type %u.\n", uint32_read_big( sizeof( g_tracker_id ) + (char*)g_inbuffer ) );
840 break;
841 }
842 }
843 return 0;
844}
diff --git a/scan_urlencoded_query.c b/scan_urlencoded_query.c
deleted file mode 100644
index a4f89c2..0000000
--- a/scan_urlencoded_query.c
+++ /dev/null
@@ -1,143 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* Opentracker */
7#include "scan_urlencoded_query.h"
8
9/* Libwofat */
10#include "scan.h"
11
12/* System */
13#include <string.h>
14
15/* Idea is to do a in place replacement or guarantee at least
16 strlen( string ) bytes in deststring
17 watch http://www.ietf.org/rfc/rfc2396.txt
18 unreserved = alphanum | mark
19 mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
20 we add '%' to the matrix to not stop at encoded chars.
21 After losing too many requests to being too strict, add the following characters to reserved matrix
22 relax = "+" | "," | "/" | ";" | "<" | ">" | ":"
23*/
24
25/* This matrix holds for each ascii character the information,
26 whether it is a non-terminating character for on of the three
27 scan states we are in, that is 'path', 'param' and 'value' from
28 /path?param=value&param=value, it is encoded in bit 0, 1 and 2
29 respectively
30
31 The top bit of lower nibble indicates, whether this character is
32 a hard terminator, ie. \0, \n or \s, where the whole scanning
33 process should terminate
34 */
35static const unsigned char is_unreserved[256] = {
36 8,0,0,0,0,0,0,0,0,0,8,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
37 8,7,8,8,8,7,0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,4,7,6,
38 4,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,7,
39 8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,7,0,
40 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
41 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
42 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
43 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
44};
45
46/* Do a fast nibble to hex representation conversion */
47static unsigned char fromhex(unsigned char x) {
48 x-='0'; if( x<=9) return x;
49 x&=~0x20; x-='A'-'0';
50 if( x<6 ) return x+10;
51 return 0xff;
52}
53
54/* Skip the value of a param=value pair */
55void scan_urlencoded_skipvalue( char **string ) {
56 const unsigned char* s=*(const unsigned char**) string;
57 unsigned char f;
58
59 /* Since we are asked to skip the 'value', we assume to stop at
60 terminators for a 'value' string position */
61 while( ( f = is_unreserved[ *s++ ] ) & SCAN_SEARCHPATH_VALUE );
62
63 /* If we stopped at a hard terminator like \0 or \n, make the
64 next scan_urlencoded_query encounter it again */
65 if( f & SCAN_SEARCHPATH_TERMINATOR ) --s;
66
67 *string = (char*)s;
68}
69
70int scan_find_keywords( const ot_keywords * keywords, char **string, SCAN_SEARCHPATH_FLAG flags) {
71 char *deststring = *string;
72 ssize_t match_length = scan_urlencoded_query(string, deststring, flags );
73
74 if( match_length < 0 ) return match_length;
75 if( match_length == 0 ) return -3;
76
77 while( keywords->key ) {
78 if( !strncmp( keywords->key, deststring, match_length ) && !keywords->key[match_length] )
79 return keywords->value;
80 keywords++;
81 }
82
83 return -3;
84}
85
86ssize_t scan_urlencoded_query(char **string, char *deststring, SCAN_SEARCHPATH_FLAG flags) {
87 const unsigned char* s=*(const unsigned char**) string;
88 unsigned char *d = (unsigned char*)deststring;
89 unsigned char b, c;
90
91 /* This is the main decoding loop.
92 'flag' determines, which characters are non-terminating in current context
93 (ie. stop at '=' and '&' if scanning for a 'param'; stop at '?' if scanning for the path )
94 */
95 while( is_unreserved[ c = *s++ ] & flags ) {
96
97 /* When encountering an url escaped character, try to decode */
98 if( c=='%') {
99 if( ( b = fromhex(*s++) ) == 0xff ) return -1;
100 if( ( c = fromhex(*s++) ) == 0xff ) return -1;
101 c|=(b<<4);
102 }
103
104 /* Write (possibly decoded) character to output */
105 *d++ = c;
106 }
107
108 switch( c ) {
109 case 0: case '\r': case '\n': case ' ':
110 /* If we started scanning on a hard terminator, indicate we've finished */
111 if( d == (unsigned char*)deststring ) return -2;
112
113 /* Else make the next call to scan_urlencoded_param encounter it again */
114 --s;
115 break;
116 case '?':
117 if( flags != SCAN_PATH ) return -1;
118 break;
119 case '=':
120 if( flags != SCAN_SEARCHPATH_PARAM ) return -1;
121 break;
122 case '&':
123 if( flags == SCAN_PATH ) return -1;
124 if( flags == SCAN_SEARCHPATH_PARAM ) --s;
125 break;
126 default:
127 return -1;
128 }
129
130 *string = (char *)s;
131 return d - (unsigned char*)deststring;
132}
133
134ssize_t scan_fixed_int( char *data, size_t len, int *tmp ) {
135 int minus = 0;
136 *tmp = 0;
137 if( *data == '-' ) --len, ++data, ++minus;
138 while( (len > 0) && (*data >= '0') && (*data <= '9') ) { --len; *tmp = 10**tmp + *data++-'0'; }
139 if( minus ) *tmp = -*tmp;
140 return len;
141}
142
143const char *g_version_scan_urlencoded_query_c = "$Source$: $Revision$\n";
diff --git a/src/opentracker.c b/src/opentracker.c
new file mode 100644
index 0000000..81b4df6
--- /dev/null
+++ b/src/opentracker.c
@@ -0,0 +1,473 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3 Some of the stuff below is stolen from Fefes example libowfat httpd. */
4
5/* System */
6#include <ctype.h>
7#include <errno.h>
8#include <limits.h>
9#include <pthread.h>
10#include <grp.h>
11#include <pwd.h>
12#include <signal.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <sys/socket.h>
18#include <unistd.h>
19#ifdef WANT_SYSLOGS
20#include <syslog.h>
21#endif
22
23/* Opentracker */
24#include "ot_accesslist.h"
25#include "ot_config.h"
26#include "ot_hex.h"
27#include "ot_http.h"
28#include "ot_iovec.h"
29#include "ot_ip.h"
30#include "ot_livesync.h"
31#include "ot_mutex.h"
32#include "ot_workqueue.h"
33#include "ot_random.h"
34#include "ot_scan.h"
35#include "ot_event.h"
36#include "ot_fdstate.h"
37#include "ot_socket.h"
38#include "ot_stats.h"
39#include "ot_tcp.h"
40#include "ot_udp.h"
41#include "ot_worker.h"
42#include "trackerlogic.h"
43
44/* Globals */
45uint32_t g_tracker_id;
46_Atomic int g_opentracker_running = 1;
47int g_self_pipe[2];
48
49static void panic(const char *routine) __attribute__((noreturn));
50static void panic(const char *routine) {
51 fprintf(stderr, "%s: %s\n", routine, strerror(errno));
52 exit(111);
53}
54
55/* Say we are stopping, wake the loop, and let main do the work on its own
56 stack. Everything other than SIGINT falls through and does nothing, which
57 is what OT_SIGNAL_WAKE wants: returning from the read is all it is for. */
58static void signal_handler(int s) {
59 if (s == SIGINT) {
60 const char byte = 0;
61 int saved = errno;
62
63 /* Any new interrupt signal quits the application */
64 signal(SIGINT, SIG_DFL);
65
66 /* Tell all other threads to not acquire any new lock on a bucket
67 but cancel their operations and return */
68 g_opentracker_running = 0;
69
70 (void)!write(g_self_pipe[1], &byte, 1);
71 errno = saved;
72 }
73}
74
75static void defaul_signal_handlers(void) {
76 sigset_t signal_mask;
77 sigemptyset(&signal_mask);
78 sigaddset(&signal_mask, SIGPIPE);
79 sigaddset(&signal_mask, SIGHUP);
80 sigaddset(&signal_mask, SIGINT);
81 sigaddset(&signal_mask, SIGALRM);
82 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
83}
84
85static void install_signal_handlers(void) {
86 struct sigaction sa;
87 sigset_t signal_mask;
88 sigemptyset(&signal_mask);
89
90 sa.sa_handler = signal_handler;
91 sigemptyset(&sa.sa_mask);
92 sa.sa_flags = 0;
93 if ((sigaction(SIGINT, &sa, NULL) == -1) || (sigaction(SIGALRM, &sa, NULL) == -1) ||
94 (sigaction(OT_SIGNAL_WAKE, &sa, NULL) == -1))
95 panic("install_signal_handlers");
96
97 sigaddset(&signal_mask, SIGINT);
98 pthread_sigmask(SIG_UNBLOCK, &signal_mask, NULL);
99}
100
101
102/* How many ready descriptors one wait hands back at a time */
103#define OT_EVENT_BATCH 512
104
105static void *server_mainloop(void *args) {
106 struct ot_workstruct ws;
107 time_t next_timeout_check = time_future_seconds(OT_CLIENT_TIMEOUT_CHECKINTERVAL);
108 struct iovec *iovector;
109 size_t iovec_entries;
110 int is_partial;
111 uint32_t generation;
112
113 (void)args;
114
115 if (workstruct_init(&ws, G_INBUF_SIZE) == -1)
116 panic("Initializing worker failed");
117
118 while (g_opentracker_running) {
119 ot_event ready[OT_EVENT_BATCH];
120 int64_t sock;
121 int count, i;
122
123 count = event_wait(ready, OT_EVENT_BATCH, OT_CLIENT_TIMEOUT_CHECKINTERVAL * 1000);
124
125 for (i = 0; i < count; ++i) {
126 const void *cookie;
127
128 sock = ready[i].fd;
129 /* A descriptor closed earlier in this same batch may already have been
130 handed out again by accept, so an event is only ours if the
131 generation it was registered under is still the one in place */
132 if (fdstate_generation((int)sock) != ready[i].generation)
133 continue;
134 cookie = fdstate_cookie((int)sock);
135
136 if ((intptr_t)cookie == FLAG_TCP)
137 tcp_accept(sock, &ws);
138 else if ((intptr_t)cookie == FLAG_UDP)
139 handle_udp6(sock, &ws);
140 else if ((intptr_t)cookie == FLAG_SELFPIPE)
141 while (read((int)sock, ws.inbuf, G_INBUF_SIZE) > 0)
142 ;
143 else if (fdstate_claim((int)sock, ready[i].generation)) {
144 if (ready[i].what & EVENT_IN)
145 tcp_read(sock, &ws);
146 /* The read may have closed it, so look again before writing */
147 if ((ready[i].what & EVENT_OUT) && fdstate_generation((int)sock) == ready[i].generation)
148 tcp_write(sock);
149 if (fdstate_generation((int)sock) == ready[i].generation)
150 fdstate_release((int)sock);
151 }
152 }
153
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 }
159 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial);
160 }
161
162 if (time_is_past(next_timeout_check)) {
163 int cursor = 0;
164
165 while ((sock = fdstate_next_expired(time_now_seconds(), &cursor)) != -1)
166 http_close(sock);
167 next_timeout_check = time_future_seconds(OT_CLIENT_TIMEOUT_CHECKINTERVAL);
168 }
169
170 livesync_ticker();
171 }
172
173 /* This work struct is about to go out of scope, so hand its tally over
174 before anything can read it there */
175 workstruct_deinit(&ws);
176 return 0;
177}
178
179
180/* A group of sockets sharing one address only spreads datagrams if every
181 member asked for it before binding, the first one included, so whether
182 this entry will have workers has to be known here. */
183static socket_sharing listen_sharing_for(const ot_listen *entry) {
184 if (entry->proto != FLAG_MCA && entry->workers > 1 && socket_can_balance())
185 return SOCKET_BALANCED;
186 return entry->shared ? SOCKET_SHARED : SOCKET_EXCLUSIVE;
187}
188
189static void listen_bind_one(ot_listen *entry) {
190 socket_sharing sharing = listen_sharing_for(entry);
191
192#ifdef _DEBUG
193 {
194 const char *protos[] = {"TCP", "UDP", "UDP mcast"};
195 char _debug[512];
196 int off = snprintf(_debug, sizeof(_debug), "Binding socket type %s to address [", protos[entry->proto]);
197 off += ip_format(_debug + off, entry->ip);
198 snprintf(_debug + off, sizeof(_debug) - off, "]:%d...", entry->port);
199 fputs(_debug, stderr);
200 }
201#endif
202
203#ifdef WANT_SYNC_LIVE
204 if (entry->proto == FLAG_MCA) {
205 livesync_bind_mcast(entry->ip, entry->port);
206#ifdef _DEBUG
207 fputs(" success.\n", stderr);
208#endif
209 return;
210 }
211#endif
212
213 if (entry->proto == FLAG_TCP) {
214 if ((entry->sock = socket_tcp_listen(entry->ip, entry->port, sharing)) == -1)
215 panic("socket_tcp_listen");
216 socket_defer_accept((int)entry->sock);
217 } else {
218 if ((entry->sock = socket_udp_bind(entry->ip, entry->port, sharing)) == -1)
219 panic("socket_udp_bind");
220 }
221
222 if (event_add((int)entry->sock, EVENT_IN, fdstate_open(entry->sock, (void *)entry->proto, 0)) == -1)
223 panic("event_add");
224
225#ifdef _DEBUG
226 fputs(" success.\n", stderr);
227#endif
228}
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
240/* Bound in the order the entries were given.
241 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */
242static void listen_bind_all(void) {
243 size_t count, i;
244 ot_listen *entries = config_listen_entries(&count);
245
246 for (i = 0; i < count; ++i)
247 listen_warn_if_taken(entries + i);
248
249 for (i = 0; i < count; ++i)
250 listen_bind_one(entries + i);
251}
252
253/* The socket the event loop was using is passed to the first worker.
254 If start up tests show that the kernel can spread connections over
255 a group bound to one address, every worker binds one of its own.
256 If not, all workers call accept on the first. */
257static void listen_start_tcp_workers(void) {
258 size_t count, i;
259 ot_listen *entries = config_listen_entries(&count);
260
261 for (i = 0; i < count; ++i) {
262 ot_listen *entry = entries + i;
263 int balance = listen_sharing_for(entry) == SOCKET_BALANCED;
264 int worker;
265
266 if (entry->proto != FLAG_TCP || entry->workers <= 0)
267 continue;
268
269 event_del((int)entry->sock);
270 tcp_worker_install(entry->sock);
271
272 for (worker = 1; worker < entry->workers; ++worker) {
273 int64_t sock = entry->sock;
274
275 if (balance) {
276 sock = socket_tcp_listen(entry->ip, entry->port, SOCKET_BALANCED);
277 if (sock == -1) {
278 fprintf(stderr, "Warning: could not bind another socket for tcp worker %d: %s. Sharing the first instead.\n", worker,
279 strerror(errno));
280 sock = entry->sock;
281 }
282 }
283 tcp_worker_install(sock);
284 }
285 }
286}
287
288static void listen_start_udp_workers(void) {
289 size_t count, i;
290 ot_listen *entries = config_listen_entries(&count);
291
292 udp_init();
293
294 for (i = 0; i < count; ++i) {
295 ot_listen *entry = entries + i;
296 int balance = listen_sharing_for(entry) == SOCKET_BALANCED;
297 int worker;
298
299 if (entry->proto != FLAG_UDP || entry->workers <= 0)
300 continue;
301
302 event_del((int)entry->sock);
303 udp_worker_install(entry->sock);
304
305 for (worker = 1; worker < entry->workers; ++worker) {
306 int64_t sock = entry->sock;
307
308 if (balance) {
309 sock = socket_udp_bind(entry->ip, entry->port, SOCKET_BALANCED);
310 if (sock == -1) {
311 fprintf(stderr, "Warning: could not bind another socket for udp worker %d: %s. Sharing the first instead.\n", worker, strerror(errno));
312 sock = entry->sock;
313 }
314 }
315 udp_worker_install(sock);
316 }
317 }
318}
319
320void load_state(const char *const state_filename) {
321 FILE *state_filehandle;
322 char inbuf[512];
323 ot_hash infohash;
324 uint64_t touched, downcount;
325 int consumed;
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
331 state_filehandle = fopen(state_filename, "r");
332
333 if (state_filehandle == NULL) {
334 fprintf(stderr, "Warning: Can't open config file: %s.", state_filename);
335 return;
336 }
337
338 /* We do ignore anything that is not of the form "^[:xdigit:]:\d+:\d+" */
339 while (fgets(inbuf, sizeof(inbuf), state_filehandle)) {
340 size_t i;
341
342 if (!hex_to_hash(infohash, inbuf))
343 continue;
344 i = 2 * sizeof(ot_hash);
345
346 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &touched, now)))
347 continue;
348 i += consumed;
349 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &downcount, SIZE_MAX)))
350 continue;
351 add_torrent_from_saved_state(infohash, (ot_time)(now - touched), (size_t)downcount);
352 }
353
354 fclose(state_filehandle);
355}
356
357int drop_privileges(const char *const serveruser, const char *const serverdir) {
358 struct passwd *pws = NULL;
359
360#ifdef _DEBUG
361 if (!geteuid())
362 fprintf(stderr, "Dropping to user %s.\n", serveruser);
363 if (serverdir)
364 fprintf(stderr, "ch%s'ing to directory %s.\n", geteuid() ? "dir" : "root", serverdir);
365#endif
366
367 /* Grab pws entry before chrooting */
368 pws = getpwnam(serveruser);
369 endpwent();
370
371 if (geteuid() == 0) {
372 /* Running as root: chroot and drop privileges */
373 if (serverdir && chroot(serverdir)) {
374 fprintf(stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno));
375 return -1;
376 }
377
378 if (chdir("/"))
379 panic("chdir() failed after chrooting: ");
380
381 /* If we can't find server user, revert to nobody's default uid */
382 if (!pws) {
383 fprintf(stderr, "Warning: Could not get password entry for %s. Reverting to uid -2.\n", serveruser);
384 if (setgroups(0, NULL) || setegid((gid_t)-2) || setgid((gid_t)-2) || setuid((uid_t)-2) || seteuid((uid_t)-2))
385 panic("Could not set uid to value -2");
386 } else {
387 if (setgroups(0, NULL) || setegid(pws->pw_gid) || setgid(pws->pw_gid) || setuid(pws->pw_uid) || seteuid(pws->pw_uid))
388 panic("Could not set uid to specified value");
389 }
390
391 if (geteuid() == 0 || getegid() == 0)
392 panic("Still running with root privileges?!");
393 } else {
394 /* Normal user, just chdir() */
395 if (serverdir && chdir(serverdir)) {
396 fprintf(stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno));
397 return -1;
398 }
399 }
400
401 return 0;
402}
403
404/* Maintain our copy of the clock. time() on BSDs is very expensive. */
405int main(int argc, char **argv) {
406
407 random_init();
408 if (fdstate_init() == -1)
409 panic("fdstate_init");
410 if (event_init() == -1)
411 panic("event_init");
412 config_parse(argc, argv);
413
414 listen_bind_all();
415
416 defaul_signal_handlers();
417
418#ifdef WANT_SYSLOGS
419 openlog("opentracker", 0, LOG_USER);
420 setlogmask(LOG_UPTO(LOG_INFO));
421#endif
422
423 if (drop_privileges(g_serveruser ? g_serveruser : "nobody", g_serverdir) == -1)
424 panic("drop_privileges failed, exiting. Last error");
425
426
427 /* Create our self pipe which allows us to interrupt mainloops
428 wait in case some data is available to send out */
429 if (pipe(g_self_pipe) == -1)
430 panic("selfpipe failed: ");
431 /* Both ends have to be non blocking: the loop drains the read end until it
432 is empty, and a worker nudging a full pipe has already made its point */
433 socket_set_blocking(g_self_pipe[0], 0);
434 socket_set_blocking(g_self_pipe[1], 0);
435 if (event_add(g_self_pipe[0], EVENT_IN, fdstate_open(g_self_pipe[0], (void *)FLAG_SELFPIPE, 0)) == -1)
436 panic("selfpipe event_add");
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
442 /* Init all sub systems. This call may fail with an exit() */
443 trackerlogic_init();
444
445#ifdef _DEBUG_RANDOMTORRENTS
446 fprintf(stderr, "DEBUG: Generating %d random peers on random torrents. This may take a while. (Setting RANDOMTORRENTS in trackerlogic.h)\n", RANDOMTORRENTS);
447 trackerlogic_add_random_torrents(RANDOMTORRENTS);
448 fprintf(stderr, "... done.\n");
449#endif
450
451 if (g_statefile)
452 load_state(g_statefile);
453
454 /* Nothing that adds a peer runs before the state file has been read */
455 livesync_init();
456 listen_start_tcp_workers();
457 listen_start_udp_workers();
458
459 server_mainloop(0);
460 worker_stop_all();
461 livesync_deinit();
462
463 /* No thread is serving any more, so the teardown can run where a debugger
464 and the sanitizers can follow it */
465 trackerlogic_deinit();
466#ifdef WANT_SYSLOGS
467 closelog();
468#endif
469
470 event_deinit();
471 fdstate_deinit();
472 return 0;
473}
diff --git a/src/ot_accesslist.c b/src/ot_accesslist.c
new file mode 100644
index 0000000..5d4f059
--- /dev/null
+++ b/src/ot_accesslist.c
@@ -0,0 +1,607 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <signal.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <unistd.h>
11#if defined(WANT_ACCESSLIST_BLACK) || defined(WANT_ACCESSLIST_WHITE)
12#include <fcntl.h>
13#include <stdint.h>
14#include <sys/mman.h>
15#include <sys/stat.h>
16#include <sys/types.h>
17#endif
18#ifdef WANT_DYNAMIC_ACCESSLIST
19#include <errno.h>
20#endif
21
22/* Opentracker */
23#include "ot_accesslist.h"
24#include "ot_hex.h"
25#include "ot_ip.h"
26#include "ot_vector.h"
27#include "trackerlogic.h"
28
29/* GLOBAL VARIABLES */
30#ifdef WANT_ACCESSLIST
31const char *g_accesslist_filename = NULL;
32#ifdef WANT_DYNAMIC_ACCESSLIST
33const char *g_accesslist_pipe_add = NULL;
34const char *g_accesslist_pipe_delete = NULL;
35#endif
36static pthread_mutex_t g_accesslist_mutex = PTHREAD_MUTEX_INITIALIZER;
37
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,
40 basically creating a central performance choke point.
41
42 The idea is that updating the list heads happens under the g_accesslist_mutex guard and is
43 done atomically, while consumers might potentially still hold pointers deeper inside the list.
44
45 Consumers (for now only via accesslist_hashisvalid) will always fetch the list head pointer
46 that is guaranteed to live for at least five minutes. This should be many orders of magnitudes
47 more than how long it will be needed by the bsearch done on the list. */
48struct ot_accesslist;
49typedef struct ot_accesslist ot_accesslist;
50struct ot_accesslist {
51 ot_hash *list;
52 size_t size;
53 ot_time base;
54 ot_accesslist *next;
55};
56static ot_accesslist *_Atomic g_accesslist = NULL;
57#ifdef WANT_DYNAMIC_ACCESSLIST
58static ot_accesslist *_Atomic g_accesslist_add = NULL;
59static ot_accesslist *_Atomic g_accesslist_delete = NULL;
60#endif
61
62/* Helpers to work on access lists */
63static int vector_compare_hash(const void *hash1, const void *hash2) { return memcmp(hash1, hash2, OT_HASH_COMPARE_SIZE); }
64
65static ot_accesslist *accesslist_free(ot_accesslist *accesslist) {
66 while (accesslist) {
67 ot_accesslist *this_accesslist = accesslist;
68 accesslist = this_accesslist->next;
69 free(this_accesslist->list);
70 free(this_accesslist);
71 }
72 return NULL;
73}
74
75static ot_accesslist *accesslist_make(ot_accesslist *next, size_t size) {
76 ot_accesslist *accesslist_new = malloc(sizeof(ot_accesslist));
77 if (accesslist_new) {
78 accesslist_new->list = size ? malloc(sizeof(ot_hash) * size) : NULL;
79 accesslist_new->size = size;
80 accesslist_new->base = 0;
81 accesslist_new->next = next;
82 if (size && !accesslist_new->list) {
83 free(accesslist_new);
84 accesslist_new = NULL;
85 }
86 }
87 return accesslist_new;
88}
89
90/* This must be called with g_accesslist_mutex held.
91 This will never delete head, because that might still be in use. */
92static void accesslist_clean(ot_accesslist *accesslist) {
93 while (accesslist && accesslist->next) {
94 if (time_since_minutes(accesslist->next->base) > 5)
95 accesslist->next = accesslist_free(accesslist->next);
96 accesslist = accesslist->next;
97 }
98}
99
100/* A hash needs forty bytes, and all but a final one are followed by at least
101 one separator, so n hashes need at least 41n - 1 bytes. (len + 1) / 41 is
102 therefore an exact upper bound on what a buffer of len bytes can hold. */
103size_t accesslist_parse_hashes(ot_hash *dest, size_t capacity, const char *buf, size_t len) {
104 const char *end = buf + len;
105 const char *offs = buf;
106 size_t count = 0;
107
108 while (count < capacity && end - offs >= 40) {
109 if (hex_to_hash(dest[count], offs)) {
110 offs += 40;
111
112 if (offs == end || !hex_isdigit((unsigned char)*offs))
113 ++count;
114 }
115
116 /* Find start of next line */
117 while (offs < end && *(offs++) != '\n') {}
118 }
119
120 return count;
121}
122
123/* Map a file read only. Returns 0 and sets map and maplen on success, -1 if
124 the file cannot be opened or mapped. */
125static int accesslist_map(const char *filename, const char **map, size_t *maplen) {
126 struct stat st;
127 void *mapped;
128 int fd = open(filename, O_RDONLY);
129
130 if (fd < 0)
131 return -1;
132
133 if (fstat(fd, &st) < 0 || st.st_size < 0 || (uintmax_t)st.st_size > (uintmax_t)SIZE_MAX) {
134 close(fd);
135 return -1;
136 }
137
138 if (st.st_size == 0) {
139 close(fd);
140 *map = NULL;
141 *maplen = 0;
142 return 0;
143 }
144
145 mapped = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_SHARED, fd, 0);
146 close(fd);
147
148 if (mapped == MAP_FAILED)
149 return -1;
150
151 *map = mapped;
152 *maplen = (size_t)st.st_size;
153 return 0;
154}
155
156static void accesslist_readfile(void) {
157 ot_accesslist *accesslist_new;
158 const char *map;
159 size_t maplen, capacity, found;
160
161 if (!g_accesslist_filename)
162 return;
163
164 if (accesslist_map(g_accesslist_filename, &map, &maplen) < 0) {
165 char *wd = getcwd(NULL, 0);
166 fprintf(stderr, "Warning: Can't open accesslist file: %s (but will try to create it later, if necessary and possible).\nPWD: %s\n", g_accesslist_filename, wd);
167 free(wd);
168 return;
169 }
170
171 /* Make room for the most info_hashes this file could possibly hold */
172 capacity = (maplen + 1) / 41;
173 accesslist_new = accesslist_make(g_accesslist, capacity);
174 if (!accesslist_new) {
175 fprintf(stderr, "Warning: Not enough memory to allocate %zd bytes for accesslist buffer. May succeed later.\n", capacity * sizeof(ot_hash));
176 if (map)
177 munmap((void *)map, maplen);
178 return;
179 }
180
181 found = maplen ? accesslist_parse_hashes(accesslist_new->list, capacity, map, maplen) : 0;
182#ifdef _DEBUG
183 fprintf(stderr, "Added %zd info_hashes to accesslist\n", found);
184#endif
185
186 if (map)
187 munmap((void *)map, maplen);
188
189 if (found)
190 qsort(accesslist_new->list, found, sizeof(ot_hash), vector_compare_hash);
191 accesslist_new->size = found;
192
193 /* Now exchange the accesslist vector in the least race condition prone way */
194 pthread_mutex_lock(&g_accesslist_mutex);
195
196 /* Mark old accesslist as "needs to live another five minutes" */
197 if (g_accesslist)
198 g_accesslist->base = time_now_minutes();
199 accesslist_new->next = g_accesslist;
200 g_accesslist = accesslist_new; /* Only now set a new list */
201
202#ifdef WANT_DYNAMIC_ACCESSLIST
203 /* If we have dynamic accesslists, reloading a new one will always void the add/delete lists.
204 Insert empty ones at the list head */
205 if (g_accesslist_add && (accesslist_new = accesslist_make(g_accesslist_add, 0)) != NULL) {
206 g_accesslist_add->base = time_now_minutes();
207 g_accesslist_add = accesslist_new;
208 }
209 if (g_accesslist_delete && (accesslist_new = accesslist_make(g_accesslist_delete, 0)) != NULL) {
210 g_accesslist_delete->base = time_now_minutes();
211 g_accesslist_delete = accesslist_new;
212 }
213#endif
214
215 accesslist_clean(g_accesslist);
216
217 pthread_mutex_unlock(&g_accesslist_mutex);
218}
219
220int accesslist_hashisvalid(const ot_hash hash) {
221 /* Get working copy of current access list */
222 ot_accesslist *accesslist = g_accesslist;
223#ifdef WANT_DYNAMIC_ACCESSLIST
224 ot_accesslist *accesslist_add, *accesslist_delete;
225#endif
226 void *exactmatch = NULL;
227
228 if (accesslist && accesslist->size)
229 exactmatch = bsearch(hash, accesslist->list, accesslist->size, OT_HASH_COMPARE_SIZE, vector_compare_hash);
230
231#ifdef WANT_DYNAMIC_ACCESSLIST
232 /* If we had no match on the main list, scan the list of dynamically added hashes */
233 accesslist_add = g_accesslist_add;
234 if ((exactmatch == NULL) && accesslist_add && accesslist_add->size)
235 exactmatch = bsearch(hash, accesslist_add->list, accesslist_add->size, OT_HASH_COMPARE_SIZE, vector_compare_hash);
236
237 /* If we found a matching hash on the main list, scan the list of dynamically deleted hashes */
238 accesslist_delete = g_accesslist_delete;
239 if ((exactmatch != NULL) && accesslist_delete && accesslist_delete->size && bsearch(hash, accesslist_delete->list, accesslist_delete->size, OT_HASH_COMPARE_SIZE, vector_compare_hash))
240 exactmatch = NULL;
241#endif
242
243#ifdef WANT_ACCESSLIST_BLACK
244 return exactmatch == NULL;
245#else
246 return exactmatch != NULL;
247#endif
248}
249
250static void *accesslist_worker(void *args) {
251 int sig;
252 sigset_t signal_mask;
253
254 sigemptyset(&signal_mask);
255 sigaddset(&signal_mask, SIGHUP);
256
257 (void)args;
258
259 while (1) {
260 /* Wait for signals */
261 while (sigwait(&signal_mask, &sig) != 0)
262 ;
263
264 if (!g_opentracker_running)
265 return NULL;
266
267 accesslist_readfile();
268 }
269 return NULL;
270}
271
272#ifdef WANT_DYNAMIC_ACCESSLIST
273static pthread_t thread_adder_id, thread_deleter_id;
274static _Atomic int adder_left, deleter_left;
275static void *accesslist_adddel_worker(const char *fifoname, ot_accesslist *_Atomic *adding_to, ot_accesslist *_Atomic *removing_from) {
276 struct stat st;
277
278 if (!stat(fifoname, &st)) {
279 if (!S_ISFIFO(st.st_mode)) {
280 fprintf(stderr, "Error when starting dynamic accesslists: Found Non-FIFO file at %s.\nPlease remove it and restart opentracker.\n", fifoname);
281 return NULL;
282 }
283 } else {
284 if (mkfifo(fifoname, 0600) && errno != EEXIST) {
285 fprintf(stderr, "Error when starting dynamic accesslists: Couldn't create FIFO at %s, error: %s\n", fifoname, strerror(errno));
286 return NULL;
287 }
288 }
289
290 while (g_opentracker_running) {
291 FILE *fifo = fopen(fifoname, "r");
292 char *line = NULL;
293 size_t linecap = 0;
294 ssize_t linelen;
295
296 if (!fifo) {
297 /* Woken on purpose: the loop condition above decides what happens next */
298 if (errno == EINTR)
299 continue;
300 fprintf(stderr, "Error when reading dynamic accesslists: Couldn't open FIFO at %s, error: %s\n", fifoname, strerror(errno));
301 return NULL;
302 }
303
304 while ((linelen = getline(&line, &linecap, fifo)) > 0) {
305 ot_hash info_hash;
306
307 printf("Got line %*s", (int)linelen, line);
308 /* We do ignore anything that is not of the form "^[:xdigit:]{40}[^:xdigit:].*"
309 If there's not enough characters for an info_hash in the line, skip it. */
310 if (linelen < 41)
311 continue;
312
313 if (!hex_to_hash(info_hash, line))
314 continue;
315
316 /* From now on we modify g_accesslist_add and g_accesslist_delete, so prevent the
317 other worker threads from doing the same */
318 pthread_mutex_lock(&g_accesslist_mutex);
319
320 /* If the info hash is in the removing_from list, create a new head without that entry */
321 if (*removing_from && (*removing_from)->list) {
322 ot_hash *exactmatch = bsearch(info_hash, (*removing_from)->list, (*removing_from)->size, OT_HASH_COMPARE_SIZE, vector_compare_hash);
323 if (exactmatch) {
324 ptrdiff_t off = exactmatch - (*removing_from)->list;
325 ot_accesslist *accesslist_new = accesslist_make(*removing_from, (*removing_from)->size - 1);
326 if (accesslist_new) {
327 size_t after = (*removing_from)->size - off - 1;
328
329 /* Removing the only entry leaves a list with no room at all, and
330 memcpy may not be handed that even for nothing */
331 if (off)
332 memcpy(accesslist_new->list, (*removing_from)->list, sizeof(ot_hash) * off);
333 if (after)
334 memcpy(accesslist_new->list + off, (*removing_from)->list + off + 1, sizeof(ot_hash) * after);
335 (*removing_from)->base = time_now_minutes();
336 *removing_from = accesslist_new;
337 }
338 }
339 }
340
341 /* Simple case: there's no adding_to list yet, create one with one member */
342 if (!*adding_to) {
343 ot_accesslist *accesslist_new = accesslist_make(NULL, 1);
344 if (accesslist_new) {
345 memcpy(accesslist_new->list, info_hash, sizeof(ot_hash));
346 *adding_to = accesslist_new;
347 }
348 } else {
349 int exactmatch = 0;
350 ot_hash *insert_point = vector_binary_search(info_hash, (*adding_to)->list, (*adding_to)->size, sizeof(ot_hash), OT_HASH_COMPARE_SIZE, &exactmatch);
351
352 /* Only if the info hash is not in the adding_to list, create a new head with that entry */
353 if (!exactmatch) {
354 ot_accesslist *accesslist_new = accesslist_make(*adding_to, (*adding_to)->size + 1);
355 if (accesslist_new) {
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);
363 memcpy(accesslist_new->list + off, info_hash, sizeof(info_hash));
364 if (after)
365 memcpy(accesslist_new->list + off + 1, (*adding_to)->list + off, sizeof(ot_hash) * after);
366 (*adding_to)->base = time_now_minutes();
367 *adding_to = accesslist_new;
368 }
369 }
370 }
371
372 pthread_mutex_unlock(&g_accesslist_mutex);
373 }
374
375 free(line);
376 fclose(fifo);
377 }
378 return NULL;
379}
380
381static void *accesslist_adder_worker(void *args) {
382 (void)args;
383 accesslist_adddel_worker(g_accesslist_pipe_add, &g_accesslist_add, &g_accesslist_delete);
384 atomic_store(&adder_left, 1);
385 return NULL;
386}
387static void *accesslist_deleter_worker(void *args) {
388 (void)args;
389 accesslist_adddel_worker(g_accesslist_pipe_delete, &g_accesslist_delete, &g_accesslist_add);
390 atomic_store(&deleter_left, 1);
391 return NULL;
392}
393
394/* These sit in a blocking open or read on a FIFO, so they are woken the way
395 the other workers are, and the signal is repeated because it only
396 interrupts a call already under way. The pipe name is what says whether
397 the thread was ever started. */
398static void accesslist_stop_fifo_worker(pthread_t thread, _Atomic int *left, const char *pipe_name) {
399 if (!pipe_name)
400 return;
401
402 while (!atomic_load(left)) {
403 pthread_kill(thread, OT_SIGNAL_WAKE);
404 usleep(1000);
405 }
406 pthread_join(thread, NULL);
407}
408#endif
409
410static pthread_t thread_id;
411void accesslist_init(void) {
412 /* Everything that consults the list starts after this returns */
413 accesslist_readfile();
414
415 if (pthread_create(&thread_id, NULL, accesslist_worker, NULL))
416 exerr("Cannot create accesslist worker thread.");
417#ifdef WANT_DYNAMIC_ACCESSLIST
418 if (g_accesslist_pipe_add && pthread_create(&thread_adder_id, NULL, accesslist_adder_worker, NULL))
419 exerr("Cannot create accesslist adder thread.");
420 if (g_accesslist_pipe_delete && pthread_create(&thread_deleter_id, NULL, accesslist_deleter_worker, NULL))
421 exerr("Cannot create accesslist deleter thread.");
422#endif
423}
424
425void accesslist_deinit(void) {
426 /* Wake the worker and wait for it to notice that the tracker is stopping. */
427 pthread_kill(thread_id, SIGHUP);
428 pthread_join(thread_id, NULL);
429
430#ifdef WANT_DYNAMIC_ACCESSLIST
431 /* Before the lists they are reading are freed below */
432 accesslist_stop_fifo_worker(thread_adder_id, &adder_left, g_accesslist_pipe_add);
433 accesslist_stop_fifo_worker(thread_deleter_id, &deleter_left, g_accesslist_pipe_delete);
434#endif
435
436 pthread_mutex_lock(&g_accesslist_mutex);
437
438 g_accesslist = accesslist_free(g_accesslist);
439
440#ifdef WANT_DYNAMIC_ACCESSLIST
441 g_accesslist_add = accesslist_free(g_accesslist_add);
442 g_accesslist_delete = accesslist_free(g_accesslist_delete);
443#endif
444
445 pthread_mutex_unlock(&g_accesslist_mutex);
446}
447
448void accesslist_cleanup(void) {
449 pthread_mutex_lock(&g_accesslist_mutex);
450
451 accesslist_clean(g_accesslist);
452#if WANT_DYNAMIC_ACCESSLIST
453 accesslist_clean(g_accesslist_add);
454 accesslist_clean(g_accesslist_delete);
455#endif
456
457 pthread_mutex_unlock(&g_accesslist_mutex);
458}
459#endif
460
461int accesslist_address_in_net(const ot_ip6 address, const ot_net *net) {
462 int bits = net->bits, checkbits = (0x7f00 >> (bits & 7));
463 int result = memcmp(address, &net->address, bits >> 3);
464 if (!result && (bits & 7))
465 result = (checkbits & address[bits >> 3]) - (checkbits & net->address[bits >> 3]);
466 return result == 0;
467}
468
469void *accesslist_set_value_for_net(const ot_net *net, ot_vector *vector, const void *value, const size_t member_size) {
470 size_t i;
471 int exactmatch;
472
473 /* Caller must have a concept of ot_net in it's member */
474 if (member_size < sizeof(ot_net))
475 return 0;
476
477 /* Check each net in vector for overlap */
478 uint8_t *member = ((uint8_t *)vector->data);
479 for (i = 0; i < vector->size; ++i) {
480 if (accesslist_address_in_net(*(ot_ip6 *)member, net) || accesslist_address_in_net(net->address, (ot_net *)member))
481 return 0;
482 member += member_size;
483 }
484
485 member = vector_find_or_insert(vector, (void *)net, member_size, sizeof(ot_net), &exactmatch);
486 if (member) {
487 memcpy(member, net, sizeof(ot_net));
488 memcpy(member + sizeof(ot_net), value, member_size - sizeof(ot_net));
489 }
490
491 return member;
492}
493
494/* Takes a vector filled with { ot_net net, uint8_t[x] value };
495 Returns value associated with the net, or NULL if not found */
496void *accesslist_get_value_for_net(const ot_ip6 address, const ot_vector *vector, const size_t member_size) {
497 int exactmatch;
498 /* This binary search will return a pointer to the first non-containing network... */
499 ot_net *net = vector_binary_search(address, vector->data, vector->size, member_size, sizeof(ot_ip6), &exactmatch);
500 if (!net)
501 return NULL;
502 /* ... so we'll need to move back one step unless we've exactly hit the first address in network */
503 if (!exactmatch && ((void *)net > vector->data))
504 --net;
505 if (!accesslist_address_in_net(address, net))
506 return NULL;
507 return (void *)net;
508}
509
510#ifdef WANT_IP_FROM_PROXY
511typedef struct {
512 ot_net *proxy;
513 ot_vector networks;
514} ot_proxymap;
515
516static ot_vector g_proxies_list;
517static pthread_mutex_t g_proxies_list_mutex = PTHREAD_MUTEX_INITIALIZER;
518
519int proxylist_add_network(const ot_net *proxy, const ot_net *net) {
520 ot_proxymap *map;
521 int exactmatch, result = 1;
522 pthread_mutex_lock(&g_proxies_list_mutex);
523
524 /* If we have a direct hit, use and extend the vector there */
525 map = vector_binary_search(proxy, g_proxies_list.data, g_proxies_list.size, sizeof(ot_proxymap), sizeof(ot_net), &exactmatch);
526
527 if (!map || !exactmatch) {
528 /* else see, if we've got overlapping networks
529 and get a new empty vector if not */
530 ot_vector empty;
531 memset(&empty, 0, sizeof(ot_vector));
532 map = accesslist_set_value_for_net(proxy, &g_proxies_list, &empty, sizeof(ot_proxymap));
533 }
534
535 if (map && accesslist_set_value_for_net(net, &map->networks, NULL, sizeof(ot_net)))
536 result = 1;
537
538 pthread_mutex_unlock(&g_proxies_list_mutex);
539 return result;
540}
541
542int proxylist_check_proxy(const ot_ip6 proxy, const ot_ip6 address) {
543 int result = 0;
544 ot_proxymap *map;
545
546 pthread_mutex_lock(&g_proxies_list_mutex);
547
548 if ((map = accesslist_get_value_for_net(proxy, &g_proxies_list, sizeof(ot_proxymap))))
549 if (!address || accesslist_get_value_for_net(address, &map->networks, sizeof(ot_net)))
550 result = 1;
551
552 pthread_mutex_unlock(&g_proxies_list_mutex);
553 return result;
554}
555
556#endif
557
558static ot_net g_admin_nets[OT_ADMINIP_MAX];
559static ot_permissions g_admin_nets_permissions[OT_ADMINIP_MAX];
560static size_t g_admin_nets_count = 0;
561
562int accesslist_bless_net(ot_net *net, ot_permissions permissions) {
563 if (g_admin_nets_count >= OT_ADMINIP_MAX)
564 return -1;
565
566 memcpy(g_admin_nets + g_admin_nets_count, net, sizeof(ot_net));
567 g_admin_nets_permissions[g_admin_nets_count++] = permissions;
568
569#ifdef _DEBUG
570 {
571 char _debug[512];
572 int off = snprintf(_debug, sizeof(_debug), "Blessing ip net ");
573 off += ip_format(_debug + off, net->address);
574 if (net->bits < 128) {
575 _debug[off++] = '/';
576 if (ip_is_v4mapped(net->address))
577 off += snprintf(_debug + off, sizeof(_debug) - off, "%d", net->bits - 96);
578 else
579 off += snprintf(_debug + off, sizeof(_debug) - off, "%d", net->bits);
580 }
581
582 if (permissions & OT_PERMISSION_MAY_STAT)
583 off += snprintf(_debug + off, 512 - off, " may_fetch_stats");
584 if (permissions & OT_PERMISSION_MAY_LIVESYNC)
585 off += snprintf(_debug + off, 512 - off, " may_sync_live");
586 if (permissions & OT_PERMISSION_MAY_FULLSCRAPE)
587 off += snprintf(_debug + off, 512 - off, " may_fetch_fullscrapes");
588 if (permissions & OT_PERMISSION_MAY_PROXY)
589 off += snprintf(_debug + off, 512 - off, " may_proxy");
590 if (!permissions)
591 off += snprintf(_debug + off, sizeof(_debug) - off, " nothing");
592 _debug[off++] = '.';
593 _debug[off++] = '\n';
594 (void)write(2, _debug, off);
595 }
596#endif
597
598 return 0;
599}
600
601int accesslist_is_blessed(ot_ip6 ip, ot_permissions permissions) {
602 size_t i;
603 for (i = 0; i < g_admin_nets_count; ++i)
604 if (accesslist_address_in_net(ip, g_admin_nets + i) && (g_admin_nets_permissions[i] & permissions))
605 return 1;
606 return 0;
607}
diff --git a/src/ot_accesslist.h b/src/ot_accesslist.h
new file mode 100644
index 0000000..c0f3fc2
--- /dev/null
+++ b/src/ot_accesslist.h
@@ -0,0 +1,78 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_ACCESSLIST_H__
5#define OT_ACCESSLIST_H__
6
7#include "trackerlogic.h"
8
9#if defined(WANT_ACCESSLIST_BLACK) && defined(WANT_ACCESSLIST_WHITE)
10#error WANT_ACCESSLIST_BLACK and WANT_ACCESSLIST_WHITE are exclusive.
11#endif
12
13#if defined(WANT_ACCESSLIST_BLACK) || defined(WANT_ACCESSLIST_WHITE)
14#define WANT_ACCESSLIST
15/* Reads the list, then starts a thread that rereads it when sent SIGHUP and
16 is stopped by being sent one, so the caller blocks SIGHUP process wide
17 beforehand */
18void accesslist_init(void);
19void accesslist_deinit(void);
20int accesslist_hashisvalid(const ot_hash hash);
21void accesslist_cleanup(void);
22
23/* Scan buf for up to capacity info_hashes in hexadecimal notation, one per
24 line, and return how many were written to dest */
25size_t accesslist_parse_hashes(ot_hash *dest, size_t capacity, const char *buf, size_t len);
26
27extern const char *g_accesslist_filename;
28#ifdef WANT_DYNAMIC_ACCESSLIST
29extern const char *g_accesslist_pipe_add;
30extern const char *g_accesslist_pipe_delete;
31#endif
32
33#else
34#ifdef WANT_DYNAMIC_ACCESSLIST
35#error WANT_DYNAMIC_ACCESSLIST needs either WANT_ACCESSLIST_BLACK or WANT_ACCESSLIST_WHITE
36#endif
37
38#define accesslist_init(accesslist_filename)
39#define accesslist_deinit()
40#define accesslist_hashisvalid(hash) 1
41#endif
42
43/* Test if an address is subset of an ot_net, return value is considered a bool */
44int accesslist_address_in_net(const ot_ip6 address, const ot_net *net);
45
46/* Store a value into a vector of struct { ot_net net, uint8_t[x] value } member;
47 returns NULL
48 if member_size is too small, or
49 if one of the nets inside the vector are a subnet of _net_, or
50 if _net_ is a subnet of one of the nets inside the vector, or
51 if the vector could not be resized
52 returns pointer to new member in vector for success
53 member_size can be sizeof(ot_net) to reduce the lookup to a boolean mapping
54*/
55void *accesslist_set_value_for_net(const ot_net *net, ot_vector *vector, const void *value, const size_t member_size);
56
57/* Takes a vector filled with struct { ot_net net, uint8_t[x] value } member;
58 Returns pointer to _member_ associated with the net, or NULL if not found
59 member_size can be sizeof(ot_net) to reduce the lookup to a boolean mapping
60*/
61void *accesslist_get_value_for_net(const ot_ip6 address, const ot_vector *vector, const size_t member_size);
62
63#ifdef WANT_IP_FROM_PROXY
64int proxylist_add_network(const ot_net *proxy, const ot_net *net);
65int proxylist_check_network(const ot_ip6 *proxy, const ot_ip6 address /* can be NULL to only check proxy */);
66#endif
67
68typedef enum {
69 OT_PERMISSION_MAY_FULLSCRAPE = 0x1,
70 OT_PERMISSION_MAY_STAT = 0x2,
71 OT_PERMISSION_MAY_LIVESYNC = 0x4,
72 OT_PERMISSION_MAY_PROXY = 0x8
73} ot_permissions;
74
75int accesslist_bless_net(ot_net *net, ot_permissions permissions);
76int accesslist_is_blessed(ot_ip6 ip, ot_permissions permissions);
77
78#endif
diff --git a/src/ot_batch.c b/src/ot_batch.c
new file mode 100644
index 0000000..e4dda0b
--- /dev/null
+++ b/src/ot_batch.c
@@ -0,0 +1,156 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <limits.h>
7#include <stdlib.h>
8#include <string.h>
9#include <sys/socket.h>
10#include <sys/uio.h>
11#include <unistd.h>
12
13/* Opentracker */
14#include "ot_batch.h"
15
16#ifndef IOV_MAX
17#define IOV_MAX 1024
18#endif
19
20#define OT_BATCH_MIN_ENTRIES 16
21
22static int batch_room_for(ot_batch *batch, size_t wanted) {
23 size_t space = batch->space ? batch->space : OT_BATCH_MIN_ENTRIES;
24 struct iovec *grown;
25
26 if (batch->count + wanted <= batch->space)
27 return 0;
28
29 /* During a chunked transfer entries are appended while earlier ones are
30 still going out, so the front of the array frees up as we go. Slide the
31 rest down before asking for more. */
32 if (batch->first && batch->count - batch->first + wanted <= batch->space) {
33 memmove(batch->entries, batch->entries + batch->first, (batch->count - batch->first) * sizeof(struct iovec));
34 batch->count -= batch->first;
35 batch->first = 0;
36 return 0;
37 }
38
39 while (space < batch->count + wanted)
40 space *= 2;
41
42 if (!(grown = realloc(batch->entries, space * sizeof(struct iovec))))
43 return -1;
44
45 batch->entries = grown;
46 batch->space = space;
47 return 0;
48}
49
50int batch_add(ot_batch *batch, void *buf, size_t len) {
51 if (batch_room_for(batch, 1)) {
52 free(buf);
53 return -1;
54 }
55
56 batch->entries[batch->count].iov_base = buf;
57 batch->entries[batch->count].iov_len = len;
58 ++batch->count;
59 return 0;
60}
61
62int batch_add_vector(ot_batch *batch, const struct iovec *entries, size_t count) {
63 if (batch_room_for(batch, count)) {
64 while (count--)
65 free(entries[count].iov_base);
66 return -1;
67 }
68
69 memcpy(batch->entries + batch->count, entries, count * sizeof(struct iovec));
70 batch->count += count;
71 return 0;
72}
73
74/* Drop everything the kernel accepted, freeing each buffer as it goes */
75static void batch_consume(ot_batch *batch, size_t written) {
76 while (written) {
77 struct iovec *entry = batch->entries + batch->first;
78 size_t left = entry->iov_len - batch->offset;
79
80 if (written < left) {
81 batch->offset += written;
82 return;
83 }
84
85 free(entry->iov_base);
86 written -= left;
87 batch->offset = 0;
88 ++batch->first;
89 }
90
91 /* Nothing is outstanding, so the array can start over from the front */
92 if (batch->first == batch->count)
93 batch->first = batch->count = 0;
94}
95
96/* A peer that has gone away must come back as an error rather than as a
97 signal that kills the tracker, so ask the kernel not to raise one where it
98 can be asked. macOS cannot, and relies on SIGPIPE being blocked. */
99static ssize_t batch_writev(int s, struct iovec *entries, int count) {
100#ifdef MSG_NOSIGNAL
101 struct msghdr msg;
102
103 memset(&msg, 0, sizeof(msg));
104 msg.msg_iov = entries;
105 msg.msg_iovlen = count;
106 return sendmsg(s, &msg, MSG_NOSIGNAL);
107#else
108 return writev(s, entries, count);
109#endif
110}
111
112ssize_t batch_send(int s, ot_batch *batch) {
113 size_t entries = batch->count - batch->first;
114 ssize_t written;
115
116 if (!batch_pending(batch))
117 return BATCH_DONE;
118
119 if (entries > IOV_MAX)
120 entries = IOV_MAX;
121
122 /* The first entry may be half way out already */
123 batch->entries[batch->first].iov_base = (char *)batch->entries[batch->first].iov_base + batch->offset;
124 batch->entries[batch->first].iov_len -= batch->offset;
125 written = batch_writev(s, batch->entries + batch->first, (int)entries);
126 batch->entries[batch->first].iov_base = (char *)batch->entries[batch->first].iov_base - batch->offset;
127 batch->entries[batch->first].iov_len += batch->offset;
128
129 if (written < 0)
130 return (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ? BATCH_AGAIN : BATCH_FAILED;
131 if (!written)
132 return BATCH_FAILED;
133
134 batch_consume(batch, (size_t)written);
135 return written;
136}
137
138void batch_reset(ot_batch *batch) {
139 while (batch->first < batch->count)
140 free(batch->entries[batch->first++].iov_base);
141
142 free(batch->entries);
143 batch->entries = NULL;
144 batch->count = batch->first = batch->offset = batch->space = 0;
145}
146
147/* For the few constants the chunked encoding needs, which the batch frees
148 along with everything else */
149int batch_add_copy(ot_batch *batch, const void *buf, size_t len) {
150 void *copy = malloc(len);
151
152 if (!copy)
153 return -1;
154 memcpy(copy, buf, len);
155 return batch_add(batch, copy, len);
156}
diff --git a/src/ot_batch.h b/src/ot_batch.h
new file mode 100644
index 0000000..910bea7
--- /dev/null
+++ b/src/ot_batch.h
@@ -0,0 +1,46 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_BATCH_H__
5#define OT_BATCH_H__
6
7#include <stddef.h>
8#include <sys/types.h>
9#include <sys/uio.h>
10
11/* A queue of buffers on their way to one socket. The batch owns every buffer
12 handed to it and frees each one as soon as it has left, so a client that
13 reads slowly costs memory only for what it has not received yet.
14
15 A zeroed ot_batch is ready to use. */
16typedef struct {
17 struct iovec *entries;
18 size_t space;
19 size_t count;
20 size_t first; /* entries before this one are sent and freed */
21 size_t offset; /* bytes of entries[first] already sent */
22} ot_batch;
23
24static inline int batch_pending(const ot_batch *batch) { return batch->first != batch->count; }
25
26/* What batch_send reports instead of a byte count */
27enum { BATCH_DONE = 0, BATCH_AGAIN = -1, BATCH_FAILED = -2 };
28
29/* Queue buf and take ownership of it. Returns 0, or -1 having freed buf. */
30int batch_add(ot_batch *batch, void *buf, size_t len);
31
32/* Write as much as the socket takes. Returns the number of bytes written, or
33 BATCH_DONE, BATCH_AGAIN or BATCH_FAILED. */
34ssize_t batch_send(int s, ot_batch *batch);
35
36/* Queue every entry of a vector, taking ownership of each buffer but not of
37 the vector itself. Returns 0, or -1 having freed all of them. */
38int batch_add_vector(ot_batch *batch, const struct iovec *entries, size_t count);
39
40/* Queue a copy of buf, which the batch then owns. Returns 0, or -1. */
41int batch_add_copy(ot_batch *batch, const void *buf, size_t len);
42
43/* Free whatever has not left yet, along with the batch's own array */
44void batch_reset(ot_batch *batch);
45
46#endif
diff --git a/src/ot_buf.c b/src/ot_buf.c
new file mode 100644
index 0000000..ecd3f8d
--- /dev/null
+++ b/src/ot_buf.c
@@ -0,0 +1,39 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_buf.h"
10
11int buf_cat(ot_buf *buf, const void *src, size_t len) {
12 char *data;
13
14 if (!len)
15 return 0;
16
17 if (buf->size + len < buf->size)
18 return -1;
19
20 if (!(data = realloc(buf->data, buf->size + len)))
21 return -1;
22
23 buf->data = data;
24 memcpy(data + buf->size, src, len);
25 buf->size += len;
26
27 return 0;
28}
29
30void buf_truncate(ot_buf *buf, size_t len) {
31 if (len < buf->size)
32 buf->size = len;
33}
34
35void buf_reset(ot_buf *buf) {
36 free(buf->data);
37 buf->data = NULL;
38 buf->size = 0;
39}
diff --git a/src/ot_buf.h b/src/ot_buf.h
new file mode 100644
index 0000000..7fb944e
--- /dev/null
+++ b/src/ot_buf.h
@@ -0,0 +1,25 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_BUF_H__
5#define OT_BUF_H__
6
7#include <stddef.h>
8
9/* A growable byte buffer, holding an HTTP request that did not arrive in a
10 single packet. Requests that arrive whole are served straight from the
11 worker's input buffer and never come near this. */
12typedef struct {
13 char *data;
14 size_t size;
15} ot_buf;
16
17/* Append len bytes from src. Returns 0, or -1 if the memory could not be
18 had, in which case the buffer keeps whatever it already held. */
19int buf_cat(ot_buf *buf, const void *src, size_t len);
20
21void buf_truncate(ot_buf *buf, size_t len);
22
23void buf_reset(ot_buf *buf);
24
25#endif
diff --git a/src/ot_clean.c b/src/ot_clean.c
new file mode 100644
index 0000000..8eb1da2
--- /dev/null
+++ b/src/ot_clean.c
@@ -0,0 +1,208 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <poll.h>
6#include <pthread.h>
7#include <stdio.h>
8#include <string.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "ot_accesslist.h"
13#include "ot_clean.h"
14#include "ot_mutex.h"
15#include "ot_stats.h"
16#include "ot_vector.h"
17#include "trackerlogic.h"
18
19ot_time g_empty_torrent_timeout = OT_TORRENT_TIMEOUT;
20
21/* Returns amount of removed peers */
22static ssize_t clean_single_bucket(ot_peer *peers, size_t peer_count, size_t peer_size, time_t timedout, size_t *removed_seeders) {
23 ot_peer *last_peer, *insert_point;
24
25 if (!peer_count)
26 return 0;
27
28 last_peer = peers + peer_count * peer_size;
29
30 /* Two scan modes: unless there is one peer removed, just increase ot_peertime */
31 while (peers < last_peer) {
32 time_t timediff = timedout + OT_PEERTIME(peers, peer_size);
33 if (timediff >= OT_PEER_TIMEOUT)
34 break;
35 OT_PEERTIME(peers, peer_size) = timediff;
36 peers += peer_size;
37 }
38
39 /* If we at least remove one peer, we have to copy */
40 for (insert_point = peers; peers < last_peer; peers += peer_size) {
41 time_t timediff = timedout + OT_PEERTIME(peers, peer_size);
42
43 if (timediff < OT_PEER_TIMEOUT) {
44 OT_PEERTIME(peers, peer_size) = timediff;
45 memcpy(insert_point, peers, peer_size);
46 insert_point += peer_size;
47 } else if (OT_PEERFLAG_D(peers, peer_size) & PEER_FLAG_SEEDING)
48 (*removed_seeders)++;
49 }
50
51 return (peers - insert_point) / peer_size;
52}
53
54/* Age one family's peers by timedout minutes. Releases and zeroes the vector
55 once its last peer is gone, so an empty family costs nothing. */
56static void clean_family_vector(ot_vector *peer_vector, size_t peer_size, ot_time timedout, size_t *removed_seeders) {
57 ot_vector *bucket = peer_vector;
58 size_t num_buckets = 1, peer_count;
59
60 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
61 num_buckets = peer_vector->size;
62 bucket = (ot_vector *)peer_vector->data;
63 }
64
65 while (num_buckets--) {
66 size_t removed_peers = clean_single_bucket(bucket->data, bucket->size, peer_size, timedout, removed_seeders);
67 bucket->size -= removed_peers;
68 if (removed_peers)
69 vector_fixup_peers(bucket, peer_size);
70
71 /* Skip to next bucket, a vector containing peers */
72 ++bucket;
73 }
74
75 peer_count = vector_peer_count(peer_vector);
76
77 /* Run dry: release the family (a collapsed bucket list or a plain vector) */
78 if (!peer_count) {
79 free_peer_vector(peer_vector);
80 memset(peer_vector, 0, sizeof(*peer_vector));
81 return;
82 }
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);
87}
88
89/* Clean a single torrent
90 return 1 if torrent timed out
91*/
92int clean_single_torrent(ot_torrent *torrent) {
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;
136}
137
138/* Written to once, by clean_deinit, and never read: the byte stays in and
139 every sleep after it returns at once */
140static int g_clean_pipe[2] = {-1, -1};
141
142static void clean_sleep(void) {
143 struct pollfd pfd;
144
145 pfd.fd = g_clean_pipe[0];
146 pfd.events = POLLIN;
147 pfd.revents = 0;
148
149 poll(&pfd, 1, OT_CLEAN_SLEEP / 1000);
150}
151
152/* Clean up all peers in one bucket, remove timedout pools and torrents */
153static void clean_bucket(size_t bucket) {
154 ot_vector *torrents_list = mutex_bucket_lock((int)bucket);
155 size_t toffs;
156 int delta_torrentcount = 0;
157
158 for (toffs = 0; toffs < torrents_list->size; ++toffs) {
159 ot_torrent *torrent = ((ot_torrent *)(torrents_list->data)) + toffs;
160 if (clean_single_torrent(torrent)) {
161 vector_remove_torrent(torrents_list, torrent);
162 --delta_torrentcount;
163 --toffs;
164 }
165 }
166 mutex_bucket_unlock((int)bucket, delta_torrentcount);
167}
168
169static void *clean_worker(void *args) {
170 (void)args;
171 while (1) {
172 size_t bucket = OT_BUCKET_COUNT;
173 while (bucket) {
174 size_t todo = bucket < OT_CLEAN_BUCKETS_PER_WAKE ? bucket : OT_CLEAN_BUCKETS_PER_WAKE;
175
176 /* One bucket is locked at a time, however many a wake gets through */
177 while (todo--)
178 clean_bucket(--bucket);
179
180 if (!g_opentracker_running)
181 return NULL;
182 clean_sleep();
183 }
184 stats_cleanup();
185#ifdef WANT_ACCESSLIST
186 accesslist_cleanup();
187#endif
188 }
189 return NULL;
190}
191
192static pthread_t thread_id;
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}
199
200void clean_deinit(void) {
201 const char byte = 0;
202
203 (void)!write(g_clean_pipe[1], &byte, 1);
204 pthread_join(thread_id, NULL);
205
206 close(g_clean_pipe[0]);
207 close(g_clean_pipe[1]);
208}
diff --git a/src/ot_clean.h b/src/ot_clean.h
new file mode 100644
index 0000000..0592791
--- /dev/null
+++ b/src/ot_clean.h
@@ -0,0 +1,28 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_CLEAN_H__
5#define OT_CLEAN_H__
6
7#include "trackerlogic.h"
8
9/* The amount of time a clean cycle should take */
10#define OT_CLEAN_INTERVAL_MINUTES 2
11
12/* How often the cleaner may wake. A full sweep takes OT_CLEAN_INTERVAL_MINUTES.
13 The clean operations per wake is goverend by OT_BUCKET_COUNT_BITS,
14 set by the Makefile.
15 At the default of 1024 buckets this works out at one bucket every
16 117 ms. */
17#define OT_CLEAN_MAX_WAKES_PER_SECOND 10
18
19#define OT_CLEAN_WAKE_BUDGET ((OT_CLEAN_INTERVAL_MINUTES) * 60 * (OT_CLEAN_MAX_WAKES_PER_SECOND))
20#define OT_CLEAN_BUCKETS_PER_WAKE (((OT_BUCKET_COUNT) + (OT_CLEAN_WAKE_BUDGET) - 1) / (OT_CLEAN_WAKE_BUDGET))
21#define OT_CLEAN_WAKES ((OT_BUCKET_COUNT) / (OT_CLEAN_BUCKETS_PER_WAKE))
22#define OT_CLEAN_SLEEP (((OT_CLEAN_INTERVAL_MINUTES) * 60 * 1000000) / (OT_CLEAN_WAKES))
23
24void clean_init(void);
25void clean_deinit(void);
26int clean_single_torrent(ot_torrent *torrent);
27
28#endif
diff --git a/src/ot_config.c b/src/ot_config.c
new file mode 100644
index 0000000..e689314
--- /dev/null
+++ b/src/ot_config.c
@@ -0,0 +1,612 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <ctype.h>
6#include <errno.h>
7#include <limits.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <unistd.h>
12
13/* Opentracker */
14#include "ot_accesslist.h"
15#include "ot_event.h"
16#include "ot_config.h"
17#include "ot_http.h"
18#include "ot_ip.h"
19#include "ot_livesync.h"
20#include "ot_scan.h"
21#include "ot_stats.h"
22#include "trackerlogic.h"
23
24const char *g_redirecturl;
25const char *g_serverdir;
26const char *g_serveruser;
27const char *g_statefile;
28
29#define OT_LISTEN_INHERIT (-1)
30
31static ot_listen *g_listen;
32static size_t g_listen_count;
33static int g_listen_shared;
34static int g_listen_workers_udp = 1;
35static int g_listen_workers_tcp = 0;
36
37static void panic(const char *routine) __attribute__((noreturn));
38static void panic(const char *routine) {
39 fprintf(stderr, "%s: %s\n", routine, strerror(errno));
40 exit(111);
41}
42
43static void listen_append(const ot_ip6 ip, uint16_t port, PROTO_FLAG proto, int shared, int workers) {
44 ot_listen *grown = realloc(g_listen, (g_listen_count + 1) * sizeof(ot_listen));
45 ot_listen *entry;
46
47 if (!grown)
48 panic("listen_append");
49 g_listen = grown;
50
51 entry = g_listen + g_listen_count++;
52 memcpy(entry->ip, ip, sizeof(ot_ip6));
53 entry->port = port;
54 entry->proto = proto;
55 entry->shared = shared;
56 entry->workers = workers;
57 entry->sock = -1;
58}
59
60typedef enum { LISTEN_OPTION_UNKNOWN, LISTEN_OPTION_SHARED, LISTEN_OPTION_WORKERS } listen_option_kind;
61
62typedef struct {
63 const char *name;
64 size_t len;
65 listen_option_kind kind;
66 int takes_value;
67} listen_option_key;
68
69#define LISTEN_OPTION_KEY(s, k, v) {s, sizeof(s) - 1, k, v}
70
71static const listen_option_key listen_option_keys[] = {
72 LISTEN_OPTION_KEY("shared", LISTEN_OPTION_SHARED, 0),
73 LISTEN_OPTION_KEY("workers", LISTEN_OPTION_WORKERS, 1),
74};
75static const size_t listen_option_count = sizeof(listen_option_keys) / sizeof(listen_option_keys[0]);
76
77static listen_option_kind parse_listen_option(char **p) {
78 size_t i;
79
80 for (i = 0; i < listen_option_count; ++i) {
81 const listen_option_key *key = &listen_option_keys[i];
82 char delimiter;
83
84 if (strncmp(*p, key->name, key->len))
85 continue;
86 /* The match guarantees *p is at least key->len bytes, so this is in bounds */
87 delimiter = (*p)[key->len];
88 if (key->takes_value ? delimiter != '=' : (delimiter && !isspace((unsigned char)delimiter)))
89 continue;
90
91 *p += key->len + (key->takes_value ? 1 : 0);
92 return key->kind;
93 }
94 return LISTEN_OPTION_UNKNOWN;
95}
96
97/* Options trailing an address in a listen statement, in any order */
98static int listen_scan_options(char *p, int *shared, int *workers) {
99 uint64_t value;
100
101 for (;;) {
102 while (isspace((unsigned char)*p))
103 ++p;
104 if (!*p)
105 return 1;
106
107 switch (parse_listen_option(&p)) {
108 case LISTEN_OPTION_SHARED:
109 *shared = 1;
110 break;
111 case LISTEN_OPTION_WORKERS: {
112 size_t off = scan_uint(p, &value, UINT_MAX);
113
114 if (!off)
115 return 0;
116 *workers = (int)value;
117 p += off;
118 break;
119 }
120 default:
121 return 0;
122 }
123 }
124}
125
126
127static const char *set_config_option(const char **option, char *value) {
128#ifdef _DEBUG
129 fprintf(stderr, "Setting config option: %s\n", value);
130#endif
131 while (isspace((unsigned char)*value))
132 ++value;
133 free((char *)*option);
134 return *option = strdup(value);
135}
136
137static int scan_ip6_port(const char *src, ot_ip6 ip, uint16_t *port) {
138 const char *s = src;
139 uint64_t value;
140 int off, bracket = 0;
141 while (isspace((unsigned char)*s))
142 ++s;
143 if (*s == '[')
144 ++s, ++bracket; /* for v6 style notation */
145 if (!(off = ip_parse(s, ip)))
146 return 0;
147 s += off;
148 if (bracket && *s == ']')
149 ++s;
150 if (*s == 0 || isspace((unsigned char)*s))
151 return s - src;
152 if (!ip_is_v4mapped(ip)) {
153 if (*s != ':' && *s != '.')
154 return 0;
155 if (!bracket && *(s) == ':')
156 return 0;
157 s++;
158 } else {
159 if (*(s++) != ':')
160 return 0;
161 }
162 if (!(off = scan_uint(s, &value, 65535)))
163 return 0;
164 *port = (uint16_t)value;
165 return off + s - src;
166}
167
168static int scan_ip6_net(const char *src, ot_net *net) {
169 const char *s = src;
170 uint64_t value;
171 int off;
172 while (isspace((unsigned char)*s))
173 ++s;
174 if (!(off = ip_parse(s, net->address)))
175 return 0;
176 s += off;
177 if (*s != '/')
178 net->bits = 128;
179 else {
180 s++;
181 if (!(off = scan_uint(s, &value, 128)))
182 return 0;
183 net->bits = (int)value;
184 if (ip_is_v4mapped(net->address))
185 net->bits += 96;
186 if (net->bits > 128)
187 return 0;
188 s += off;
189 }
190 return off + s - src;
191}
192
193typedef enum {
194 CONFIG_UNKNOWN,
195 CONFIG_TRACKER_ROOTDIR,
196 CONFIG_TRACKER_USER,
197 CONFIG_TRACKER_EMPTY_TIMEOUT,
198 CONFIG_LISTEN_TCP_UDP,
199 CONFIG_LISTEN_TCP,
200 CONFIG_LISTEN_UDP,
201 CONFIG_LISTEN_UDP_WORKERS,
202 CONFIG_LISTEN_TCP_WORKERS,
203 CONFIG_LISTEN_SHARED,
204 CONFIG_ACCESS_WHITELIST,
205 CONFIG_ACCESS_BLACKLIST,
206 CONFIG_ACCESS_FIFO_ADD,
207 CONFIG_ACCESS_FIFO_DELETE,
208 CONFIG_ACCESS_STATS,
209 CONFIG_ACCESS_STATS_PATH,
210 CONFIG_ACCESS_PROXY,
211 CONFIG_ACCESS_FULLSCRAPE,
212 CONFIG_TRACKER_REDIRECT_URL,
213 CONFIG_LIVESYNC_CLUSTER_NODE_IP,
214 CONFIG_LIVESYNC_CLUSTER_LISTEN,
215 CONFIG_LIVESYNC_CLUSTER_GROUP,
216} config_kind;
217
218typedef struct {
219 const char *name;
220 size_t len;
221 config_kind kind;
222} config_key;
223
224#define CONFIG_KEY(s, k) { s, sizeof(s) - 1, k }
225
226static const config_key config_keys[] = {
227 CONFIG_KEY("tracker.rootdir", CONFIG_TRACKER_ROOTDIR),
228 CONFIG_KEY("tracker.user", CONFIG_TRACKER_USER),
229 CONFIG_KEY("tracker.empty_torrent_timeout", CONFIG_TRACKER_EMPTY_TIMEOUT),
230 CONFIG_KEY("listen.tcp_udp", CONFIG_LISTEN_TCP_UDP),
231 CONFIG_KEY("listen.tcp", CONFIG_LISTEN_TCP),
232 CONFIG_KEY("listen.udp", CONFIG_LISTEN_UDP),
233 CONFIG_KEY("listen.udp.workers", CONFIG_LISTEN_UDP_WORKERS),
234 CONFIG_KEY("listen.tcp.workers", CONFIG_LISTEN_TCP_WORKERS),
235 CONFIG_KEY("listen.shared", CONFIG_LISTEN_SHARED),
236#ifdef WANT_ACCESSLIST_WHITE
237 CONFIG_KEY("access.whitelist", CONFIG_ACCESS_WHITELIST),
238#elif defined(WANT_ACCESSLIST_BLACK)
239 CONFIG_KEY("access.blacklist", CONFIG_ACCESS_BLACKLIST),
240#endif
241#ifdef WANT_DYNAMIC_ACCESSLIST
242 CONFIG_KEY("access.fifo_add", CONFIG_ACCESS_FIFO_ADD),
243 CONFIG_KEY("access.fifo_delete", CONFIG_ACCESS_FIFO_DELETE),
244#endif
245#ifdef WANT_RESTRICT_STATS
246 CONFIG_KEY("access.stats", CONFIG_ACCESS_STATS),
247#endif
248 CONFIG_KEY("access.stats_path", CONFIG_ACCESS_STATS_PATH),
249#ifdef WANT_IP_FROM_PROXY
250 CONFIG_KEY("access.proxy", CONFIG_ACCESS_PROXY),
251#endif
252#ifdef WANT_RESTRICT_FULLSCRAPE
253 CONFIG_KEY("access.fullscrape", CONFIG_ACCESS_FULLSCRAPE),
254#endif
255 CONFIG_KEY("tracker.redirect_url", CONFIG_TRACKER_REDIRECT_URL),
256#ifdef WANT_SYNC_LIVE
257 CONFIG_KEY("livesync.cluster.node_ip", CONFIG_LIVESYNC_CLUSTER_NODE_IP),
258 CONFIG_KEY("livesync.cluster.listen", CONFIG_LIVESYNC_CLUSTER_LISTEN),
259 CONFIG_KEY("livesync.cluster.group", CONFIG_LIVESYNC_CLUSTER_GROUP),
260#endif
261};
262static const size_t config_entry_count = sizeof(config_keys) / sizeof(config_keys[0]);
263
264static config_kind parse_config_key(char **p) {
265 size_t i;
266 for (i = 0; i < config_entry_count; ++i) {
267 const config_key *key = &config_keys[i];
268 if (strncmp(*p, key->name, key->len) == 0 && isspace((unsigned char)(*p)[key->len])) {
269 *p += key->len + 1;
270 /* Skip white spaces */
271 while (isspace((unsigned char)**p))
272 ++(*p);
273 return key->kind;
274 }
275 }
276 return CONFIG_UNKNOWN;
277}
278
279static int parse_configfile(char *config_filename) {
280 FILE *config_file_handle;
281 char inbuf[512];
282 ot_ip6 tmpip;
283#if defined(WANT_RESTRICT_STATS) || defined(WANT_RESTRICT_FULLSCRAPE) || defined(WANT_IP_FROM_PROXY) || defined(WANT_SYNC_LIVE)
284 ot_net tmpnet;
285#endif
286 int bound = 0;
287
288 config_file_handle = fopen(config_filename, "r");
289
290 if (config_file_handle == NULL) {
291 fprintf(stderr, "Warning: Can't open config file: %s.", config_filename);
292 return 0;
293 }
294
295 while (fgets(inbuf, sizeof(inbuf), config_file_handle)) {
296 char *p = inbuf, *end;
297 uint64_t value;
298 uint16_t tmpport = 6969;
299 config_kind kind;
300
301 /* Skip white spaces */
302 while (isspace((unsigned char)*p))
303 ++p;
304
305 /* Ignore comments and empty lines */
306 if ((*p == '#') || (*p == '\n') || (*p == 0))
307 continue;
308
309 /* consume trailing new lines and spaces */
310 end = p + strlen(p);
311 while (end > p && isspace((unsigned char)end[-1]))
312 *--end = 0;
313
314 /* Scan for commands */
315 kind = parse_config_key(&p);
316 switch (kind) {
317 case CONFIG_TRACKER_ROOTDIR:
318 set_config_option(&g_serverdir, p);
319 break;
320 case CONFIG_TRACKER_USER:
321 set_config_option(&g_serveruser, p);
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;
328 case CONFIG_LISTEN_TCP_UDP:
329 case CONFIG_LISTEN_TCP:
330 case CONFIG_LISTEN_UDP: {
331 int shared = OT_LISTEN_INHERIT;
332 int workers = OT_LISTEN_INHERIT;
333 int off = scan_ip6_port(p, tmpip, &tmpport);
334
335 if (!off || !listen_scan_options(p + off, &shared, &workers))
336 exerr("listen.tcp, listen.udp and listen.tcp_udp want an address, optionally a port and options.");
337 if (kind != CONFIG_LISTEN_UDP)
338 listen_append(tmpip, tmpport, FLAG_TCP, shared, workers), ++bound;
339 if (kind != CONFIG_LISTEN_TCP)
340 listen_append(tmpip, tmpport, FLAG_UDP, shared, workers), ++bound;
341 break;
342 }
343 case CONFIG_LISTEN_UDP_WORKERS:
344 if (!scan_uint(p, &value, UINT_MAX))
345 goto parse_error;
346 g_listen_workers_udp = (int)value;
347 break;
348 case CONFIG_LISTEN_TCP_WORKERS:
349 if (!scan_uint(p, &value, UINT_MAX))
350 goto parse_error;
351 g_listen_workers_tcp = (int)value;
352 break;
353 case CONFIG_LISTEN_SHARED:
354 if (!scan_uint(p, &value, 1))
355 goto parse_error;
356 g_listen_shared = (int)value;
357 break;
358#ifdef WANT_ACCESSLIST_WHITE
359 case CONFIG_ACCESS_WHITELIST:
360 set_config_option(&g_accesslist_filename, p);
361 break;
362#elif defined(WANT_ACCESSLIST_BLACK)
363 case CONFIG_ACCESS_BLACKLIST:
364 set_config_option(&g_accesslist_filename, p);
365 break;
366#endif
367#ifdef WANT_DYNAMIC_ACCESSLIST
368 case CONFIG_ACCESS_FIFO_ADD:
369 set_config_option(&g_accesslist_pipe_add, p);
370 break;
371 case CONFIG_ACCESS_FIFO_DELETE:
372 set_config_option(&g_accesslist_pipe_delete, p);
373 break;
374#endif
375#ifdef WANT_RESTRICT_STATS
376 case CONFIG_ACCESS_STATS:
377 if (!scan_ip6_net(p, &tmpnet))
378 goto parse_error;
379 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_STAT);
380 break;
381#endif
382 case CONFIG_ACCESS_STATS_PATH:
383 set_config_option(&g_stats_path, p);
384 break;
385#ifdef WANT_IP_FROM_PROXY
386 case CONFIG_ACCESS_PROXY:
387 if (!scan_ip6_net(p, &tmpnet))
388 goto parse_error;
389 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_PROXY);
390 break;
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
399 case CONFIG_TRACKER_REDIRECT_URL:
400 set_config_option(&g_redirecturl, p);
401 break;
402#ifdef WANT_SYNC_LIVE
403 case CONFIG_LIVESYNC_CLUSTER_GROUP:
404 if (!ip_parse(p, tmpip) || livesync_set_group(tmpip) == -1)
405 exerr("livesync.cluster.group wants a multicast address, out of 224.0.0.0/4.");
406 break;
407 case CONFIG_LIVESYNC_CLUSTER_NODE_IP:
408 if (!scan_ip6_net(p, &tmpnet))
409 goto parse_error;
410 accesslist_bless_net(&tmpnet, OT_PERMISSION_MAY_LIVESYNC);
411 break;
412 case CONFIG_LIVESYNC_CLUSTER_LISTEN:
413 tmpport = LIVESYNC_PORT;
414 {
415 int shared = OT_LISTEN_INHERIT, dummy = OT_LISTEN_INHERIT;
416 int off = scan_ip6_port(p, tmpip, &tmpport);
417
418 if (!off || !listen_scan_options(p + off, &shared, &dummy))
419 goto parse_error;
420 listen_append(tmpip, tmpport, FLAG_MCA, shared, OT_LISTEN_INHERIT);
421 }
422 break;
423#endif
424 default:
425 fprintf(stderr, "Unhandled line in config file: %s\n", inbuf);
426 break;
427 parse_error:
428 fprintf(stderr, "Parse error in config file: %s\n", inbuf);
429 }
430 }
431 fclose(config_file_handle);
432 return bound;
433}
434
435static void usage(char *name) {
436 fprintf(stderr,
437 "Usage: %s [-i ip] [-p port] [-P port] [-r redirect] [-d dir] [-u user] [-A ip[/bits]] [-f config] [-s livesyncport]"
438#ifdef WANT_ACCESSLIST_BLACK
439 " [-b blacklistfile]"
440#elif defined(WANT_ACCESSLIST_WHITE)
441 " [-w whitelistfile]"
442#endif
443 "\n",
444 name);
445}
446
447#define HELPLINE(opt, desc) fprintf(stderr, "\t%-10s%s\n", opt, desc)
448static void help(char *name) {
449 usage(name);
450
451 HELPLINE("-f config", "include and execute the config file");
452 HELPLINE("-i ip", "specify ip to bind to with next -[pP] (default: any, overrides preceeding ones)");
453 HELPLINE("-p port", "do bind to tcp port (default: 6969, you may specify more than one)");
454 HELPLINE("-P port", "do bind to udp port (default: 6969, you may specify more than one)");
455 HELPLINE("-r redirecturl", "specify url where / should be redirected to (default none)");
456 HELPLINE("-d dir", "specify directory to try to chroot to (default: \".\")");
457 HELPLINE("-u user", "specify user under whose privileges opentracker should run (default: \"nobody\")");
458 HELPLINE("-A ip[/bits]", "bless an ip address or net as admin address (e.g. to allow syncs from this address)");
459 HELPLINE("-v", "report version, event mechanism and the feature flags opentracker was built with");
460#ifdef WANT_ACCESSLIST_BLACK
461 HELPLINE("-b file", "specify blacklist file.");
462#elif defined(WANT_ACCESSLIST_WHITE)
463 HELPLINE("-w file", "specify whitelist file.");
464#endif
465
466 fprintf(stderr, "\nExample: ./opentracker -i 127.0.0.1 -p 6969 -P 6969 -f ./opentracker.conf -i 10.1.1.23 -p 2710 -p 80\n");
467 fprintf(stderr, " Here -i 127.0.0.1 selects the ip address for the next -p 6969 and -P 6969.\n");
468 fprintf(stderr, " If no port is bound from config file or command line, the last address given\n");
469 fprintf(stderr, " is used on port 6969, and every interface if none was given.\n");
470}
471#undef HELPLINE
472
473
474static void listen_resolve_defaults(void) {
475 size_t i;
476
477 for (i = 0; i < g_listen_count; ++i) {
478 ot_listen *entry = g_listen + i;
479
480 if (entry->shared == OT_LISTEN_INHERIT)
481 entry->shared = g_listen_shared;
482 if (entry->workers == OT_LISTEN_INHERIT)
483 entry->workers = entry->proto == FLAG_TCP ? g_listen_workers_tcp : g_listen_workers_udp;
484
485 /* A tcp worker hands a connection it cannot finish to the event loop,
486 which only one thread may touch where the set is ours rather than the
487 kernel's */
488 if (entry->proto == FLAG_TCP && entry->workers > 0 && !event_can_share()) {
489 fprintf(stderr, "Warning: tcp workers impossible on this platform with event mechanism %s chosen.\n",
490 event_mechanism());
491 entry->workers = 0;
492 }
493 }
494}
495
496ot_listen *config_listen_entries(size_t *count) {
497 *count = g_listen_count;
498 return g_listen;
499}
500
501void config_parse(int argc, char **argv) {
502 ot_ip6 serverip;
503 ot_net tmpnet;
504 int bound = 0, scanon = 1;
505 uint64_t value;
506
507 memset(serverip, 0, sizeof(ot_ip6));
508#ifdef WANT_V4_ONLY
509 serverip[10] = serverip[11] = -1;
510#endif
511
512 while (scanon) {
513 switch (getopt(argc, argv,
514 ":i:p:A:P:d:u:r:s:f:l:v"
515#ifdef WANT_ACCESSLIST_BLACK
516 "b:"
517#elif defined(WANT_ACCESSLIST_WHITE)
518 "w:"
519#endif
520 "h")) {
521 case -1:
522 scanon = 0;
523 break;
524 case 'i':
525 if (!ip_parse(optarg, serverip)) {
526 usage(argv[0]);
527 exit(1);
528 }
529 break;
530#ifdef WANT_ACCESSLIST_BLACK
531 case 'b':
532 set_config_option(&g_accesslist_filename, optarg);
533 break;
534#elif defined(WANT_ACCESSLIST_WHITE)
535 case 'w':
536 set_config_option(&g_accesslist_filename, optarg);
537 break;
538#endif
539 case 'p':
540 if (!scan_uint(optarg, &value, 65535)) {
541 usage(argv[0]);
542 exit(1);
543 }
544 listen_append(serverip, (uint16_t)value, FLAG_TCP, OT_LISTEN_INHERIT, OT_LISTEN_INHERIT);
545 bound++;
546 break;
547 case 'P':
548 if (!scan_uint(optarg, &value, 65535)) {
549 usage(argv[0]);
550 exit(1);
551 }
552 listen_append(serverip, (uint16_t)value, FLAG_UDP, OT_LISTEN_INHERIT, OT_LISTEN_INHERIT);
553 bound++;
554 break;
555#ifdef WANT_SYNC_LIVE
556 case 's':
557 if (!scan_uint(optarg, &value, 65535)) {
558 usage(argv[0]);
559 exit(1);
560 }
561 listen_append(serverip, (uint16_t)value, FLAG_MCA, OT_LISTEN_INHERIT, OT_LISTEN_INHERIT);
562 break;
563#endif
564 case 'd':
565 set_config_option(&g_serverdir, optarg);
566 break;
567 case 'u':
568 set_config_option(&g_serveruser, optarg);
569 break;
570 case 'r':
571 set_config_option(&g_redirecturl, optarg);
572 break;
573 case 'l':
574 g_statefile = optarg;
575 break;
576 case 'A':
577 if (!scan_ip6_net(optarg, &tmpnet)) {
578 usage(argv[0]);
579 exit(1);
580 }
581 accesslist_bless_net(&tmpnet, 0xffff); /* Allow everything for now */
582 break;
583 case 'f':
584 bound += parse_configfile(optarg);
585 break;
586 case 'h':
587 help(argv[0]);
588 exit(0);
589 case 'v': {
590 char buffer[8192];
591 char *cursor = buffer;
592
593 stats_return_tracker_version(&cursor, buffer + sizeof(buffer) - 1);
594 stats_return_tracker_features(&cursor, buffer + sizeof(buffer) - 1);
595 *cursor = 0;
596 fputs(buffer, stderr);
597 exit(0);
598 }
599 default:
600 case '?':
601 usage(argv[0]);
602 exit(1);
603 }
604 }
605
606 if (!bound) {
607 listen_append(serverip, 6969, FLAG_TCP, OT_LISTEN_INHERIT, OT_LISTEN_INHERIT);
608 listen_append(serverip, 6969, FLAG_UDP, OT_LISTEN_INHERIT, OT_LISTEN_INHERIT);
609 }
610
611 listen_resolve_defaults();
612}
diff --git a/src/ot_config.h b/src/ot_config.h
new file mode 100644
index 0000000..79187ee
--- /dev/null
+++ b/src/ot_config.h
@@ -0,0 +1,33 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_CONFIG_H__
5#define OT_CONFIG_H__
6
7#include <stdint.h>
8
9#include "trackerlogic.h"
10
11/* An address opentracker was asked to listen on. Options the statement did
12 not name have been filled in from the file wide defaults by the time these
13 are handed out. sock is filled in by whoever binds them. */
14typedef struct {
15 ot_ip6 ip;
16 uint16_t port;
17 PROTO_FLAG proto;
18 int shared;
19 int workers;
20 int64_t sock;
21} ot_listen;
22
23extern const char *g_redirecturl;
24extern const char *g_serverdir;
25extern const char *g_serveruser;
26extern const char *g_statefile;
27
28/* Reads the command line and every config file it names. Exits on error. */
29void config_parse(int argc, char **argv);
30
31ot_listen *config_listen_entries(size_t *count);
32
33#endif
diff --git a/src/ot_event.c b/src/ot_event.c
new file mode 100644
index 0000000..cc575f6
--- /dev/null
+++ b/src/ot_event.c
@@ -0,0 +1,356 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <stdlib.h>
7#include <string.h>
8#include <unistd.h>
9
10/* Opentracker */
11#include "ot_event.h"
12
13/* One caller waits, so the scratch the mechanism needs is kept here rather
14 than allocated per call. */
15
16/* poll works everywhere and is what the BSDs get until kqueue is written.
17 Defining OT_EVENT_FORCE_POLL picks it on a platform that would otherwise
18 use something better, which is how both are exercised by the tests. */
19#if defined(OT_EVENT_FORCE_POLL)
20#define OT_EVENT_POLL
21#elif defined(OT_EVENT_FORCE_KQUEUE)
22#define OT_EVENT_KQUEUE
23#elif defined(__linux__)
24#define OT_EVENT_EPOLL
25#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__APPLE__)
26#define OT_EVENT_KQUEUE
27#else
28#define OT_EVENT_POLL
29#endif
30
31#ifdef OT_EVENT_EPOLL
32/* ------------------------------------------------------------- epoll */
33
34#include <sys/epoll.h>
35
36static int g_epoll = -1;
37static struct epoll_event *g_ready;
38static int g_ready_space;
39
40const char *event_mechanism(void) { return "epoll"; }
41/* The set lives in the kernel, and epoll_ctl during another thread's
42 epoll_wait is what it is for */
43int event_can_share(void) { return 1; }
44
45int event_init(void) {
46 g_ready = NULL;
47 g_ready_space = 0;
48 return (g_epoll = epoll_create1(EPOLL_CLOEXEC)) == -1 ? -1 : 0;
49}
50
51void event_deinit(void) {
52 if (g_epoll != -1)
53 close(g_epoll);
54 free(g_ready);
55 g_epoll = -1;
56 g_ready = NULL;
57 g_ready_space = 0;
58}
59
60static int event_ctl(int op, int fd, int what, uint32_t generation) {
61 struct epoll_event ev;
62
63 memset(&ev, 0, sizeof(ev));
64 ev.events = (what & EVENT_IN ? (uint32_t)EPOLLIN : 0) | (what & EVENT_OUT ? (uint32_t)EPOLLOUT : 0);
65 /* The generation rides along inside the kernel, so an event says which
66 connection it belongs to without anybody looking it up */
67 ev.data.u64 = ((uint64_t)generation << 32) | (uint32_t)fd;
68 return epoll_ctl(g_epoll, op, fd, &ev);
69}
70
71int event_add(int fd, int what, uint32_t generation) { return event_ctl(EPOLL_CTL_ADD, fd, what, generation); }
72int event_modify(int fd, int what, uint32_t generation) { return event_ctl(EPOLL_CTL_MOD, fd, what, generation); }
73int event_del(int fd) { return epoll_ctl(g_epoll, EPOLL_CTL_DEL, fd, NULL); }
74
75/* A descriptor leaves the interest list when the last reference to its open
76 file description is closed, and the tracker never duplicates one */
77int event_close(int fd) { return close(fd); }
78
79int event_wait(ot_event *out, int max, int timeout_ms) {
80 int count, i;
81
82 if (max > g_ready_space) {
83 struct epoll_event *grown = realloc(g_ready, (size_t)max * sizeof(struct epoll_event));
84
85 if (!grown)
86 return -1;
87 g_ready = grown;
88 g_ready_space = max;
89 }
90
91 /* An interrupted wait is reported as no events rather than retried here,
92 so that the caller gets to look at whatever the signal was about */
93 if ((count = epoll_wait(g_epoll, g_ready, max, timeout_ms)) == -1)
94 return errno == EINTR ? 0 : -1;
95 for (i = 0; i < count; ++i) {
96 uint32_t events = g_ready[i].events;
97
98 out[i].fd = (int)(uint32_t)g_ready[i].data.u64;
99 out[i].generation = (uint32_t)(g_ready[i].data.u64 >> 32);
100 /* A hangup or an error is reported as both, so whichever side the caller
101 was waiting on gets to notice */
102 out[i].what = (events & (EPOLLIN | EPOLLHUP | EPOLLERR) ? EVENT_IN : 0) |
103 (events & (EPOLLOUT | EPOLLHUP | EPOLLERR) ? EVENT_OUT : 0);
104 }
105 return count;
106}
107
108#endif /* OT_EVENT_EPOLL */
109
110#ifdef OT_EVENT_KQUEUE
111/* ------------------------------------------------------------ kqueue */
112
113#include <sys/event.h>
114#include <sys/time.h>
115#include <sys/types.h>
116
117static int g_kqueue = -1;
118static struct kevent *g_ready;
119static int g_ready_space;
120
121const char *event_mechanism(void) { return "kqueue"; }
122/* The set lives in the kernel, and kevent may be called from any thread */
123int event_can_share(void) { return 1; }
124
125int event_init(void) {
126 g_ready = NULL;
127 g_ready_space = 0;
128 return (g_kqueue = kqueue()) == -1 ? -1 : 0;
129}
130
131void event_deinit(void) {
132 if (g_kqueue != -1)
133 close(g_kqueue);
134 free(g_ready);
135 g_kqueue = -1;
136 g_ready = NULL;
137 g_ready_space = 0;
138}
139
140/* kqueue keeps one registration per filter, so reading and writing are two
141 entries. A change of interest is an add of the one wanted and a delete
142 of the one not. The generation travels in udata, which the kernel passes
143 back untouched. */
144static int event_change(int fd, int what, uint32_t generation, int deleting) {
145 struct kevent change[2], result[2];
146 void *udata = (void *)(uintptr_t)generation;
147 int succeeded = 0, count, i;
148
149 EV_SET(&change[0], (uintptr_t)fd, EVFILT_READ,
150 EV_RECEIPT | ((deleting || !(what & EVENT_IN)) ? EV_DELETE : EV_ADD), 0, 0, udata);
151 EV_SET(&change[1], (uintptr_t)fd, EVFILT_WRITE,
152 EV_RECEIPT | ((deleting || !(what & EVENT_OUT)) ? EV_DELETE : EV_ADD), 0, 0, udata);
153
154 if ((count = kevent(g_kqueue, change, 2, result, 2, NULL)) == -1)
155 return -1;
156
157 for (i = 0; i < count && i < 2; ++i) {
158 if (!result[i].data) {
159 ++succeeded;
160 continue;
161 }
162 /* Dropping interest we never registered is not a failure */
163 if ((change[i].flags & EV_DELETE) && result[i].data == ENOENT)
164 continue;
165 errno = (int)result[i].data;
166 return -1;
167 }
168
169 /* Nothing at all was registered or removed, so the descriptor is unknown */
170 if (!succeeded) {
171 errno = ENOENT;
172 return -1;
173 }
174 return 0;
175}
176
177int event_add(int fd, int what, uint32_t generation) { return what ? event_change(fd, what, generation, 0) : 0; }
178int event_modify(int fd, int what, uint32_t generation) { return event_change(fd, what, generation, 0); }
179int event_del(int fd) { return event_change(fd, 0, 0, 1); }
180
181/* Closing a descriptor removes every kevent that references it */
182int event_close(int fd) { return close(fd); }
183
184int event_wait(ot_event *out, int max, int timeout_ms) {
185 struct timespec timeout;
186 struct timespec *deadline = NULL;
187 int count, i;
188
189 if (max > g_ready_space) {
190 struct kevent *grown = realloc(g_ready, (size_t)max * sizeof(struct kevent));
191
192 if (!grown)
193 return -1;
194 g_ready = grown;
195 g_ready_space = max;
196 }
197
198 if (timeout_ms >= 0) {
199 timeout.tv_sec = timeout_ms / 1000;
200 timeout.tv_nsec = (long)(timeout_ms % 1000) * 1000000;
201 deadline = &timeout;
202 }
203
204 /* An interrupted wait is reported as no events rather than retried here,
205 so that the caller gets to look at whatever the signal was about */
206 if ((count = kevent(g_kqueue, NULL, 0, g_ready, max, deadline)) == -1)
207 return errno == EINTR ? 0 : -1;
208 for (i = 0; i < count; ++i) {
209 int eof = (g_ready[i].flags & (EV_EOF | EV_ERROR)) != 0;
210
211 out[i].fd = (int)g_ready[i].ident;
212 out[i].generation = (uint32_t)(uintptr_t)g_ready[i].udata;
213 out[i].what = ((g_ready[i].filter == EVFILT_READ || eof) ? EVENT_IN : 0) |
214 ((g_ready[i].filter == EVFILT_WRITE || eof) ? EVENT_OUT : 0);
215 }
216 return count;
217}
218
219#endif /* OT_EVENT_KQUEUE */
220
221#ifdef OT_EVENT_POLL
222/* -------------------------------------------------------------- poll */
223
224#include <poll.h>
225
226/* poll wants its descriptors packed, so the registered ones live in one
227 array and a second maps a descriptor number to its place in it. */
228static struct pollfd *g_pfds;
229static uint32_t *g_generation;
230static int *g_where;
231static int g_count, g_space, g_where_space;
232
233const char *event_mechanism(void) { return "poll"; }
234/* The arrays below are ours and nothing guards them */
235int event_can_share(void) { return 0; }
236
237int event_init(void) {
238 g_pfds = NULL, g_generation = NULL, g_where = NULL;
239 g_count = g_space = g_where_space = 0;
240 return 0;
241}
242
243void event_deinit(void) {
244 free(g_pfds), free(g_generation), free(g_where);
245 g_pfds = NULL, g_generation = NULL, g_where = NULL;
246 g_count = g_space = g_where_space = 0;
247}
248
249static short event_to_poll(int what) {
250 return (short)((what & EVENT_IN ? POLLIN : 0) | (what & EVENT_OUT ? POLLOUT : 0));
251}
252
253static int event_room_for(int fd) {
254 if (fd >= g_where_space) {
255 int space = g_where_space ? g_where_space : 64;
256 int *grown;
257
258 while (space <= fd)
259 space *= 2;
260 if (!(grown = realloc(g_where, (size_t)space * sizeof(int))))
261 return -1;
262 while (g_where_space < space)
263 grown[g_where_space++] = -1;
264 g_where = grown;
265 }
266
267 if (g_count == g_space) {
268 int space = g_space ? g_space * 2 : 64;
269 struct pollfd *pfds = realloc(g_pfds, (size_t)space * sizeof(struct pollfd));
270 uint32_t *gens;
271
272 if (!pfds)
273 return -1;
274 g_pfds = pfds;
275 if (!(gens = realloc(g_generation, (size_t)space * sizeof(uint32_t))))
276 return -1;
277 g_generation = gens;
278 g_space = space;
279 }
280 return 0;
281}
282
283int event_add(int fd, int what, uint32_t generation) {
284 if (fd < 0 || event_room_for(fd) == -1)
285 return -1;
286 if (g_where[fd] != -1) {
287 errno = EEXIST;
288 return -1;
289 }
290
291 g_pfds[g_count].fd = fd;
292 g_pfds[g_count].events = event_to_poll(what);
293 g_pfds[g_count].revents = 0;
294 g_generation[g_count] = generation;
295 g_where[fd] = g_count++;
296 return 0;
297}
298
299int event_modify(int fd, int what, uint32_t generation) {
300 if (fd < 0 || fd >= g_where_space || g_where[fd] == -1) {
301 errno = ENOENT;
302 return -1;
303 }
304 g_pfds[g_where[fd]].events = event_to_poll(what);
305 g_generation[g_where[fd]] = generation;
306 return 0;
307}
308
309int event_del(int fd) {
310 int at;
311
312 if (fd < 0 || fd >= g_where_space || (at = g_where[fd]) == -1) {
313 errno = ENOENT;
314 return -1;
315 }
316
317 /* The last one moves into the gap, so the array stays packed */
318 g_pfds[at] = g_pfds[--g_count];
319 g_generation[at] = g_generation[g_count];
320 g_where[g_pfds[at].fd] = at;
321 g_where[fd] = -1;
322 return 0;
323}
324
325/* Nothing here lives in the kernel, so the entry has to come out by hand
326 before the descriptor goes, or poll reports POLLNVAL for it forever */
327int event_close(int fd) {
328 event_del(fd);
329 return close(fd);
330}
331
332int event_wait(ot_event *out, int max, int timeout_ms) {
333 int ready, found = 0, i;
334
335 /* An interrupted wait is reported as no events rather than retried here,
336 so that the caller gets to look at whatever the signal was about */
337 if ((ready = poll(g_pfds, (nfds_t)g_count, timeout_ms)) == -1)
338 return errno == EINTR ? 0 : -1;
339 if (ready <= 0)
340 return ready;
341
342 for (i = 0; i < g_count && found < max; ++i) {
343 short revents = g_pfds[i].revents;
344
345 if (!revents)
346 continue;
347 out[found].fd = g_pfds[i].fd;
348 out[found].generation = g_generation[i];
349 out[found].what = (revents & (POLLIN | POLLHUP | POLLERR | POLLNVAL) ? EVENT_IN : 0) |
350 (revents & (POLLOUT | POLLHUP | POLLERR | POLLNVAL) ? EVENT_OUT : 0);
351 ++found;
352 }
353 return found;
354}
355
356#endif /* OT_EVENT_POLL */
diff --git a/src/ot_event.h b/src/ot_event.h
new file mode 100644
index 0000000..cb84ca8
--- /dev/null
+++ b/src/ot_event.h
@@ -0,0 +1,47 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_EVENT_H__
5#define OT_EVENT_H__
6
7#include <stdint.h>
8
9/* Which descriptors have become readable or writable, asked of whichever
10 mechanism the kernel offers. The generation a descriptor was registered
11 with is handed back with every event, so a caller can tell an event for
12 the connection it is holding from one for a connection that has since been
13 closed and had its number reused. */
14
15enum { EVENT_IN = 1, EVENT_OUT = 2 };
16
17typedef struct {
18 int fd;
19 uint32_t generation;
20 int what;
21} ot_event;
22
23int event_init(void);
24void event_deinit(void);
25
26int event_add(int fd, int what, uint32_t generation);
27int event_modify(int fd, int what, uint32_t generation);
28int event_del(int fd);
29
30/* Stop watching a descriptor and close it. Where the kernel drops a closed
31 descriptor from its set by itself, this is one system call where doing the
32 two separately would be two. */
33int event_close(int fd);
34
35/* Waits at most timeout_ms, or indefinitely when that is negative, and fills
36 out with up to max ready descriptors. Returns how many, or -1. */
37int event_wait(ot_event *out, int max, int timeout_ms);
38
39/* Whether the registered set may be changed from another thread while this
40 one is waiting on it. True where the kernel keeps the set, false where
41 this module keeps it in memory of its own. */
42int event_can_share(void);
43
44/* Which mechanism was compiled in, for the version string */
45const char *event_mechanism(void);
46
47#endif
diff --git a/src/ot_fdstate.c b/src/ot_fdstate.c
new file mode 100644
index 0000000..bbb25d2
--- /dev/null
+++ b/src/ot_fdstate.c
@@ -0,0 +1,202 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdatomic.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <sys/mman.h>
9#include <sys/resource.h>
10#include <sys/types.h>
11
12/* Opentracker */
13#include "ot_fdstate.h"
14
15enum { FD_FREE, FD_IDLE, FD_BUSY, FD_CLOSING };
16
17/* Generation and state share one word so that taking the state is also a
18 check that the generation has not moved */
19#define FD_GEN(w) ((uint32_t)((w) >> 32))
20#define FD_ST(w) ((uint32_t)(((w) >> 24) & 0xff))
21#define FD_WORD(g, s) (((uint64_t)(g) << 32) | ((uint64_t)(s) << 24))
22#define FD_SET_ST(w, s) (((w) & ~(uint64_t)0xff000000) | ((uint64_t)(s) << 24))
23
24typedef struct {
25 _Atomic uint64_t state;
26 _Atomic(void *) cookie;
27 _Atomic unsigned long expiry;
28} ot_fdslot;
29
30/* A descriptor the kernel can hand out is below the limit it was handed out
31 under, but the limit can be raised after we sized the table, so an out of
32 range descriptor is rejected */
33#define FD_SLOTS_MAX (1u << 20)
34
35static ot_fdslot *g_slots;
36static size_t g_slot_count;
37/* Descriptors are handed out lowest first, so a sweep only has to walk as
38 far as the highest one ever seen rather than the whole table. */
39static _Atomic size_t g_slot_highest;
40
41int fdstate_init(void) {
42 struct rlimit limit;
43 size_t count = FD_SLOTS_MAX;
44
45 if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY && limit.rlim_cur < FD_SLOTS_MAX)
46 count = (size_t)limit.rlim_cur;
47
48 g_slots = mmap(NULL, count * sizeof(ot_fdslot), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
49 if (g_slots == MAP_FAILED) {
50 g_slots = NULL;
51 return -1;
52 }
53
54 g_slot_count = count;
55 atomic_store(&g_slot_highest, 0);
56 return 0;
57}
58
59void fdstate_deinit(void) {
60 if (g_slots)
61 munmap(g_slots, g_slot_count * sizeof(ot_fdslot));
62 g_slots = NULL;
63 g_slot_count = 0;
64 atomic_store(&g_slot_highest, 0);
65}
66
67size_t fdstate_slots(void) { return g_slot_count; }
68
69static ot_fdslot *fdstate_slot(int fd) {
70 if (fd < 0 || (size_t)fd >= g_slot_count)
71 return NULL;
72 return g_slots + fd;
73}
74
75uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry) {
76 ot_fdslot *slot = fdstate_slot(fd);
77 uint64_t word;
78
79 if (!slot)
80 return 0;
81
82 {
83 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed);
84
85 while ((size_t)fd > highest &&
86 !atomic_compare_exchange_weak_explicit(&g_slot_highest, &highest, (size_t)fd, memory_order_relaxed,
87 memory_order_relaxed))
88 ;
89 }
90
91 word = atomic_load_explicit(&slot->state, memory_order_relaxed);
92 atomic_store_explicit(&slot->cookie, cookie, memory_order_release);
93 atomic_store_explicit(&slot->expiry, expiry, memory_order_relaxed);
94 /* Publishes the two above to whoever claims the slot next */
95 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word), FD_IDLE), memory_order_release);
96
97 return FD_GEN(word);
98}
99
100uint32_t fdstate_generation(int fd) {
101 ot_fdslot *slot = fdstate_slot(fd);
102
103 return slot ? FD_GEN(atomic_load_explicit(&slot->state, memory_order_relaxed)) : 0;
104}
105
106int fdstate_claim(int fd, uint32_t generation) {
107 ot_fdslot *slot = fdstate_slot(fd);
108 uint64_t word;
109
110 if (!slot)
111 return 0;
112
113 word = atomic_load_explicit(&slot->state, memory_order_acquire);
114 for (;;) {
115 if (FD_GEN(word) != generation || FD_ST(word) != FD_IDLE)
116 return 0;
117 if (atomic_compare_exchange_weak_explicit(&slot->state, &word, FD_SET_ST(word, FD_BUSY), memory_order_acquire,
118 memory_order_relaxed))
119 return 1;
120 /* word now holds what was really there, so the test above runs again */
121 }
122}
123
124void fdstate_release(int fd) {
125 ot_fdslot *slot = fdstate_slot(fd);
126 uint64_t word;
127
128 if (!slot)
129 return;
130
131 word = atomic_load_explicit(&slot->state, memory_order_relaxed);
132 atomic_store_explicit(&slot->state, FD_SET_ST(word, FD_IDLE), memory_order_release);
133}
134
135int fdstate_claim_expired(int fd, unsigned long now) {
136 ot_fdslot *slot = fdstate_slot(fd);
137 uint64_t word;
138 unsigned long expiry;
139
140 if (!slot)
141 return 0;
142
143 /* Reading before asking for the slot keeps the common case, a descriptor
144 that has not expired, off the bus entirely */
145 word = atomic_load_explicit(&slot->state, memory_order_relaxed);
146 if (FD_ST(word) != FD_IDLE)
147 return 0;
148 expiry = atomic_load_explicit(&slot->expiry, memory_order_relaxed);
149 if (!expiry || expiry > now)
150 return 0;
151
152 /* Nothing can move the expiry while the slot sits at FD_IDLE, so winning
153 the slot is the last word */
154 return atomic_compare_exchange_strong_explicit(&slot->state, &word, FD_SET_ST(word, FD_CLOSING), memory_order_acquire,
155 memory_order_relaxed);
156}
157
158void fdstate_close(int fd) {
159 ot_fdslot *slot = fdstate_slot(fd);
160 uint64_t word;
161
162 if (!slot)
163 return;
164
165 word = atomic_load_explicit(&slot->state, memory_order_relaxed);
166 atomic_store_explicit(&slot->cookie, NULL, memory_order_relaxed);
167 atomic_store_explicit(&slot->expiry, 0, memory_order_relaxed);
168 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word) + 1, FD_FREE), memory_order_release);
169}
170
171int fdstate_next_expired(unsigned long now, int *cursor) {
172 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed);
173
174 for (; (size_t)*cursor <= highest; ++*cursor)
175 if (fdstate_claim_expired(*cursor, now))
176 return (*cursor)++;
177
178 return -1;
179}
180
181void *fdstate_cookie(int fd) {
182 ot_fdslot *slot = fdstate_slot(fd);
183
184 /* Pairs with the release in fdstate_set_cookie and fdstate_open */
185 return slot ? atomic_load_explicit(&slot->cookie, memory_order_acquire) : NULL;
186}
187
188void fdstate_set_cookie(int fd, void *cookie) {
189 ot_fdslot *slot = fdstate_slot(fd);
190
191 /* Publishes what the cookie points at to whoever reads it next, which may
192 be another thread entirely */
193 if (slot)
194 atomic_store_explicit(&slot->cookie, cookie, memory_order_release);
195}
196
197void fdstate_set_expiry(int fd, unsigned long expiry) {
198 ot_fdslot *slot = fdstate_slot(fd);
199
200 if (slot)
201 atomic_store_explicit(&slot->expiry, expiry, memory_order_relaxed);
202}
diff --git a/src/ot_fdstate.h b/src/ot_fdstate.h
new file mode 100644
index 0000000..20f469d
--- /dev/null
+++ b/src/ot_fdstate.h
@@ -0,0 +1,62 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_FDSTATE_H__
5#define OT_FDSTATE_H__
6
7#include <stdint.h>
8
9#include "trackerlogic.h"
10
11/* What the tracker knows about a file descriptor: who owns it, when it
12 should be given up on, and whether anyone is working on it right now.
13
14 A descriptor number says nothing about identity, since the kernel hands
15 the same number out again as soon as it is closed. Every slot therefore
16 carries a generation that is bumped when the descriptor is given up, and
17 every caller that was told about a descriptor has to say which generation
18 it was told about. A caller holding a stale generation is turned away
19 instead of being handed somebody else's connection.
20
21 The table is sized once from RLIMIT_NOFILE and never moves, so looking a
22 descriptor up needs no synchronisation at all. */
23
24int fdstate_init(void);
25void fdstate_deinit(void);
26size_t fdstate_slots(void);
27
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. */
30uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry);
31
32/* Which generation a descriptor currently carries, to check an event that
33 was handed out earlier against the connection living there now. */
34uint32_t fdstate_generation(int fd);
35
36/* Ask for exclusive use. Returns 0 if the descriptor has been recycled since
37 generation was handed out, or if somebody else is using it. */
38int fdstate_claim(int fd, uint32_t generation);
39void fdstate_release(int fd);
40
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. */
43int fdstate_claim_expired(int fd, unsigned long now);
44
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
47 quoting the old generation are still in flight. */
48void fdstate_close(int fd);
49
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
52 sweepers can run without sharing anything. */
53int fdstate_next_expired(unsigned long now, int *cursor);
54
55/* Both only valid while the caller holds the descriptor. */
56void *fdstate_cookie(int fd);
57
58/* Hand the slot a different cookie, for a connection whose state has moved */
59void fdstate_set_cookie(int fd, void *cookie);
60void fdstate_set_expiry(int fd, unsigned long expiry);
61
62#endif
diff --git a/src/ot_fmt.c b/src/ot_fmt.c
new file mode 100644
index 0000000..362c9b5
--- /dev/null
+++ b/src/ot_fmt.c
@@ -0,0 +1,40 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdarg.h>
6#include <stdio.h>
7#include <string.h>
8
9/* Opentracker */
10#include "ot_fmt.h"
11
12void fmt_append(char **cursor, const char *end, const char *format, ...) {
13 va_list arguments;
14 size_t room;
15 int written;
16
17 if (*cursor >= end) {
18 *cursor = (char *)end;
19 return;
20 }
21
22 room = (size_t)(end - *cursor);
23 va_start(arguments, format);
24 written = vsnprintf(*cursor, room, format, arguments);
25 va_end(arguments);
26
27 if (written < 0)
28 return;
29 *cursor = (size_t)written >= room ? (char *)end : *cursor + written;
30}
31
32void fmt_bytes(char **cursor, const char *end, const void *bytes, size_t length) {
33 if (*cursor >= end || (size_t)(end - *cursor) < length) {
34 *cursor = (char *)end;
35 return;
36 }
37
38 memcpy(*cursor, bytes, length);
39 *cursor += length;
40}
diff --git a/src/ot_fmt.h b/src/ot_fmt.h
new file mode 100644
index 0000000..214cbc4
--- /dev/null
+++ b/src/ot_fmt.h
@@ -0,0 +1,19 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_FMT_H__
5#define OT_FMT_H__
6
7#include <stddef.h>
8
9/* Appending to a cursor that walks a fixed buffer. Both take the cursor by
10 reference and advance it, so a reply is written as a run of statements and
11 no caller does pointer arithmetic of its own. */
12
13void fmt_append(char **cursor, const char *end, const char *format, ...) __attribute__((format(printf, 3, 4)));
14
15/* Append raw bytes for the binary stretches of a bencoded reply.
16 Either everything is appended or nothing at all */
17void fmt_bytes(char **cursor, const char *end, const void *bytes, size_t length);
18
19#endif
diff --git a/src/ot_fullscrape.c b/src/ot_fullscrape.c
new file mode 100644
index 0000000..00c08e0
--- /dev/null
+++ b/src/ot_fullscrape.c
@@ -0,0 +1,467 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifdef WANT_FULLSCRAPE
5
6/* System */
7#include <arpa/inet.h>
8#include <pthread.h>
9#include <stdio.h>
10#include <string.h>
11#ifdef WANT_COMPRESSION_GZIP
12#include <zlib.h>
13#endif
14#ifdef WANT_COMPRESSION_ZSTD
15#include <zstd.h>
16#endif
17
18/* Opentracker */
19#include "ot_fmt.h"
20#include "ot_hex.h"
21#include "ot_fullscrape.h"
22#include "ot_iovec.h"
23#include "ot_mutex.h"
24#include "ot_workqueue.h"
25#include "ot_urlencoded.h"
26#include "trackerlogic.h"
27
28/* Fetch full scrape info for all torrents
29 Full scrapes usually are huge and one does not want to
30 allocate more memory. So lets get them in 512k units
31*/
32#define OT_SCRAPE_CHUNK_SIZE (1024 * 1024)
33
34/* "d8:completei%zde10:downloadedi%zde10:incompletei%zdee" */
35#define OT_SCRAPE_MAXENTRYLEN 256
36
37/* Forward declaration */
38static void fullscrape_make(int taskid, ot_tasktype mode);
39#ifdef WANT_COMPRESSION_GZIP
40static void fullscrape_make_gzip(int taskid, ot_tasktype mode);
41#endif
42#ifdef WANT_COMPRESSION_ZSTD
43static void fullscrape_make_zstd(int taskid, ot_tasktype mode);
44#endif
45
46/* This is the entry point into this worker thread
47 It grabs tasks from mutex_tasklist and delivers results back
48*/
49static void *fullscrape_worker(void *args) {
50 (void)args;
51
52 while (g_opentracker_running) {
53 ot_tasktype tasktype = TASK_FULLSCRAPE;
54 ot_taskid taskid = workqueue_poptask(&tasktype);
55 if (!taskid)
56 break;
57#ifdef WANT_COMPRESSION_ZSTD
58 if (tasktype & TASK_FLAG_ZSTD)
59 fullscrape_make_zstd(taskid, tasktype);
60 else
61#endif
62#ifdef WANT_COMPRESSION_GZIP
63 if (tasktype & TASK_FLAG_GZIP)
64 fullscrape_make_gzip(taskid, tasktype);
65 else
66#endif
67 fullscrape_make(taskid, tasktype);
68 workqueue_pushchunked(taskid, NULL);
69 }
70 return NULL;
71}
72
73static pthread_t thread_id;
74void fullscrape_init(void) {
75 if (pthread_create(&thread_id, NULL, fullscrape_worker, NULL))
76 exerr("Cannot create fullscrape worker thread.");
77}
78
79void fullscrape_deinit(void) {
80 workqueue_wakeall();
81 pthread_join( thread_id, NULL );
82}
83
84void fullscrape_deliver( int64_t sock, ot_tasktype tasktype ) {
85 workqueue_pushtask( sock, TASK_FULLSCRAPE | tasktype );
86}
87
88static void fullscrape_write_one( ot_tasktype mode, char **cursor, ot_torrent *torrent, ot_hash *hash ) {
89 /* Callers guarantee this much room: the chunk writer keeps its low
90 watermark that far from the end, the compressors hand over a buffer of
91 exactly that size */
92 char *r = *cursor;
93 const char *r_end = r + OT_SCRAPE_MAXENTRYLEN;
94 size_t seed_count = torrent_seed_count(torrent);
95 size_t peer_count = torrent_peer_count(torrent);
96 size_t down_count = torrent->down_count;
97
98 switch (mode & TASK_TASK_MASK) {
99 case TASK_FULLSCRAPE:
100 default:
101 /* push hash as bencoded string */
102 *r++ = '2';
103 *r++ = '0';
104 *r++ = ':';
105 memcpy(r, hash, sizeof(ot_hash));
106 r += sizeof(ot_hash);
107 /* push rest of the scrape string */
108 fmt_append(&r, r_end, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee", seed_count, down_count, peer_count - seed_count);
109
110 break;
111 case TASK_FULLSCRAPE_TPB_ASCII:
112 hex_from_hash(r, *hash);
113 r += 2 * sizeof(ot_hash);
114 fmt_append(&r, r_end, ":%zd:%zd\n", seed_count, peer_count - seed_count);
115 break;
116 case TASK_FULLSCRAPE_TPB_ASCII_PLUS:
117 hex_from_hash(r, *hash);
118 r += 2 * sizeof(ot_hash);
119 fmt_append(&r, r_end, ":%zd:%zd:%zd\n", seed_count, peer_count - seed_count, down_count);
120 break;
121 case TASK_FULLSCRAPE_TPB_BINARY:
122 memcpy(r, *hash, sizeof(ot_hash));
123 r += sizeof(ot_hash);
124 pack_uint32(&r, (uint32_t)seed_count);
125 pack_uint32(&r, (uint32_t)(peer_count - seed_count));
126 break;
127 case TASK_FULLSCRAPE_TPB_URLENCODED:
128 r += urlencoded_format(r, *hash, sizeof(ot_hash));
129 fmt_append(&r, r_end, ":%zd:%zd\n", seed_count, peer_count - seed_count);
130 break;
131 case TASK_FULLSCRAPE_TRACKERSTATE:
132 hex_from_hash(r, *hash);
133 r += 2 * sizeof(ot_hash);
134 fmt_append(&r, r_end, ":%zd:%zd\n", (ssize_t)(time_wall_minutes() - time_since_minutes(torrent->base)), down_count);
135 break;
136 }
137 *cursor = r;
138}
139
140static void fullscrape_make(int taskid, ot_tasktype mode) {
141 size_t bucket;
142 char *r, *re;
143 struct iovec iovector = {NULL, 0};
144
145 /* Setup return vector... */
146 r = iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
147 if (!r)
148 return;
149
150 /* re points to low watermark */
151 re = r + OT_SCRAPE_CHUNK_SIZE - OT_SCRAPE_MAXENTRYLEN;
152
153 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE)
154 fmt_append(&r, (char *)iovector.iov_base + OT_SCRAPE_CHUNK_SIZE, "d5:filesd");
155
156 /* For each bucket... */
157 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
158 /* Get exclusive access to that bucket */
159 ot_vector *torrents_list = mutex_bucket_lock(bucket);
160 ot_torrent *torrents = (ot_torrent *)(torrents_list->data);
161 size_t i;
162
163 /* For each torrent in this bucket.. */
164 for (i = 0; i < torrents_list->size; ++i) {
165 fullscrape_write_one(mode, &r, torrents + i, &torrents[i].hash);
166
167 if (r > re) {
168 iovector.iov_len = r - (char *)iovector.iov_base;
169
170 if (workqueue_pushchunked(taskid, &iovector)) {
171 free(iovector.iov_base);
172 mutex_bucket_unlock(bucket, 0);
173 return;
174 }
175 /* Allocate a fresh output buffer */
176 r = iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
177 if (!r) {
178 mutex_bucket_unlock(bucket, 0);
179 return;
180 }
181
182 /* re points to low watermark */
183 re = r + OT_SCRAPE_CHUNK_SIZE - OT_SCRAPE_MAXENTRYLEN;
184 }
185 }
186
187 /* All torrents done: release lock on current bucket */
188 mutex_bucket_unlock(bucket, 0);
189
190 /* Parent thread died? */
191 if (!g_opentracker_running) {
192 free(iovector.iov_base);
193 return;
194 }
195 }
196
197 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE)
198 fmt_append(&r, (char *)iovector.iov_base + OT_SCRAPE_CHUNK_SIZE, "ee");
199
200 /* Send rest of data */
201 iovector.iov_len = r - (char *)iovector.iov_base;
202 if (workqueue_pushchunked(taskid, &iovector))
203 free(iovector.iov_base);
204}
205
206#ifdef WANT_COMPRESSION_GZIP
207
208static void fullscrape_make_gzip(int taskid, ot_tasktype mode) {
209 size_t bucket;
210 char *r;
211 struct iovec iovector = {NULL, 0};
212 int zres;
213 z_stream strm;
214 /* Setup return vector... */
215 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
216 if (!iovector.iov_base)
217 return;
218
219 memset(&strm, 0, sizeof(strm));
220 strm.next_out = (uint8_t *)iovector.iov_base;
221 strm.avail_out = OT_SCRAPE_CHUNK_SIZE;
222 if (deflateInit2(&strm, 7, Z_DEFLATED, 31, 9, Z_DEFAULT_STRATEGY) != Z_OK) {
223 free(iovector.iov_base);
224 return;
225 }
226
227 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
228 strm.next_in = (uint8_t *)"d5:filesd";
229 strm.avail_in = strlen("d5:filesd");
230 zres = deflate(&strm, Z_NO_FLUSH);
231 }
232
233 /* For each bucket... */
234 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
235 /* Get exclusive access to that bucket */
236 ot_vector *torrents_list = mutex_bucket_lock(bucket);
237 ot_torrent *torrents = (ot_torrent *)(torrents_list->data);
238 size_t i;
239
240 /* For each torrent in this bucket.. */
241 for (i = 0; i < torrents_list->size; ++i) {
242 char compress_buffer[OT_SCRAPE_MAXENTRYLEN];
243 r = compress_buffer;
244 fullscrape_write_one(mode, &r, torrents + i, &torrents[i].hash);
245 strm.next_in = (uint8_t *)compress_buffer;
246 strm.avail_in = r - compress_buffer;
247 zres = deflate(&strm, Z_NO_FLUSH);
248 if ((zres < Z_OK) && (zres != Z_BUF_ERROR))
249 fprintf(stderr, "deflate() failed while in fullscrape_make().\n");
250
251 /* Check if there still is enough buffer left */
252 while (!strm.avail_out) {
253 iovector.iov_len = (char *)strm.next_out - (char *)iovector.iov_base;
254
255 if (workqueue_pushchunked(taskid, &iovector)) {
256 free(iovector.iov_base);
257 deflateEnd(&strm);
258 mutex_bucket_unlock(bucket, 0);
259 return;
260 }
261 /* Allocate a fresh output buffer */
262 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
263 if (!iovector.iov_base) {
264 fprintf(stderr, "Out of memory trying to claim ouput buffer\n");
265 deflateEnd(&strm);
266 mutex_bucket_unlock(bucket, 0);
267 return;
268 }
269 strm.next_out = (uint8_t *)iovector.iov_base;
270 strm.avail_out = OT_SCRAPE_CHUNK_SIZE;
271 zres = deflate(&strm, Z_NO_FLUSH);
272 if ((zres < Z_OK) && (zres != Z_BUF_ERROR))
273 fprintf(stderr, "deflate() failed while in fullscrape_make().\n");
274 }
275 }
276
277 /* All torrents done: release lock on current bucket */
278 mutex_bucket_unlock(bucket, 0);
279
280 /* Parent thread died? */
281 if (!g_opentracker_running) {
282 free(iovector.iov_base);
283 deflateEnd(&strm);
284 return;
285 }
286 }
287
288 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
289 strm.next_in = (uint8_t *)"ee";
290 strm.avail_in = strlen("ee");
291 }
292
293 if (deflate(&strm, Z_FINISH) < Z_OK)
294 fprintf(stderr, "deflate() failed while in fullscrape_make()'s endgame.\n");
295
296 iovector.iov_len = (char *)strm.next_out - (char *)iovector.iov_base;
297 if (workqueue_pushchunked(taskid, &iovector)) {
298 free(iovector.iov_base);
299 deflateEnd(&strm);
300 return;
301 }
302
303 /* Check if there's a last batch of data in the zlib buffer */
304 if (!strm.avail_out) {
305 /* Allocate a fresh output buffer */
306 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
307
308 if (!iovector.iov_base) {
309 fprintf(stderr, "Problem with iovec_next_chunk\n");
310 deflateEnd(&strm);
311 return;
312 }
313 strm.next_out = iovector.iov_base;
314 strm.avail_out = OT_SCRAPE_CHUNK_SIZE;
315 if (deflate(&strm, Z_FINISH) < Z_OK)
316 fprintf(stderr, "deflate() failed while in fullscrape_make()'s endgame.\n");
317
318 /* Only pass the new buffer if there actually was some data left in the buffer */
319 iovector.iov_len = (char *)strm.next_out - (char *)iovector.iov_base;
320 if (!iovector.iov_len || workqueue_pushchunked(taskid, &iovector))
321 free(iovector.iov_base);
322 }
323
324 deflateEnd(&strm);
325}
326/* WANT_COMPRESSION_GZIP */
327#endif
328
329#ifdef WANT_COMPRESSION_ZSTD
330
331static void fullscrape_make_zstd(int taskid, ot_tasktype mode) {
332 int bucket;
333 char *r;
334 struct iovec iovector = {NULL, 0};
335 ZSTD_CCtx *zstream = ZSTD_createCCtx();
336 ZSTD_inBuffer inbuf;
337 ZSTD_outBuffer outbuf;
338 size_t more_bytes;
339
340 if (!zstream)
341 return;
342
343 /* Setup return vector... */
344 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
345 if (!iovector.iov_base) {
346 ZSTD_freeCCtx(zstream);
347 return;
348 }
349
350 /* Working with a compression level 6 is half as fast as level 3, but
351 seems to be the last reasonable bump that's worth extra cpu */
352 ZSTD_CCtx_setParameter(zstream, ZSTD_c_compressionLevel, 6);
353
354 outbuf.dst = iovector.iov_base;
355 outbuf.size = OT_SCRAPE_CHUNK_SIZE;
356 outbuf.pos = 0;
357
358 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
359 inbuf.src = (const void *)"d5:filesd";
360 inbuf.size = strlen("d5:filesd");
361 inbuf.pos = 0;
362 ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_continue);
363 }
364
365 /* For each bucket... */
366 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
367 /* Get exclusive access to that bucket */
368 ot_vector *torrents_list = mutex_bucket_lock(bucket);
369 ot_torrent *torrents = (ot_torrent *)(torrents_list->data);
370 size_t i;
371
372 /* For each torrent in this bucket.. */
373 for (i = 0; i < torrents_list->size; ++i) {
374 char compress_buffer[OT_SCRAPE_MAXENTRYLEN];
375 r = compress_buffer;
376 fullscrape_write_one(mode, &r, torrents + i, &torrents[i].hash);
377 inbuf.src = compress_buffer;
378 inbuf.size = r - compress_buffer;
379 inbuf.pos = 0;
380 ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_continue);
381
382 /* Check if there still is enough buffer left */
383 while (outbuf.pos + OT_SCRAPE_MAXENTRYLEN > outbuf.size) {
384 iovector.iov_len = outbuf.pos;
385
386 if (workqueue_pushchunked(taskid, &iovector)) {
387 free(iovector.iov_base);
388 ZSTD_freeCCtx(zstream);
389 return mutex_bucket_unlock(bucket, 0);
390 }
391 /* Allocate a fresh output buffer */
392 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
393 if (!iovector.iov_base) {
394 fprintf(stderr, "Out of memory trying to claim ouput buffer\n");
395 ZSTD_freeCCtx(zstream);
396 return mutex_bucket_unlock(bucket, 0);
397 }
398
399 outbuf.dst = iovector.iov_base;
400 outbuf.size = OT_SCRAPE_CHUNK_SIZE;
401 outbuf.pos = 0;
402
403 ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_continue);
404 }
405 }
406
407 /* All torrents done: release lock on current bucket */
408 mutex_bucket_unlock(bucket, 0);
409
410 /* Parent thread died? */
411 if (!g_opentracker_running) {
412 free(iovector.iov_base);
413 ZSTD_freeCCtx(zstream);
414 return;
415 }
416 }
417
418 if ((mode & TASK_TASK_MASK) == TASK_FULLSCRAPE) {
419 inbuf.src = (const void *)"ee";
420 inbuf.size = strlen("ee");
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;
427 }
428
429 more_bytes = ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end);
430
431 iovector.iov_len = outbuf.pos;
432 if (workqueue_pushchunked(taskid, &iovector)) {
433 free(iovector.iov_base);
434 ZSTD_freeCCtx(zstream);
435 return;
436 }
437
438 /* Check if there's a last batch of data in the zlib buffer */
439 if (more_bytes) {
440 /* Allocate a fresh output buffer */
441 iovector.iov_base = malloc(OT_SCRAPE_CHUNK_SIZE);
442
443 if (!iovector.iov_base) {
444 fprintf(stderr, "Problem with iovec_next_chunk\n");
445 ZSTD_freeCCtx(zstream);
446 return;
447 }
448
449 outbuf.dst = iovector.iov_base;
450 outbuf.size = OT_SCRAPE_CHUNK_SIZE;
451 outbuf.pos = 0;
452
453 ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end);
454
455 /* Only pass the new buffer if there actually was some data left in the buffer */
456 iovector.iov_len = outbuf.pos;
457 if (!iovector.iov_len || workqueue_pushchunked(taskid, &iovector))
458 free(iovector.iov_base);
459 }
460
461 ZSTD_freeCCtx(zstream);
462}
463/* WANT_COMPRESSION_ZSTD */
464#endif
465
466/* WANT_FULLSCRAPE */
467#endif
diff --git a/src/ot_fullscrape.h b/src/ot_fullscrape.h
new file mode 100644
index 0000000..8d11cd3
--- /dev/null
+++ b/src/ot_fullscrape.h
@@ -0,0 +1,23 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_FULLSCRAPE_H__
5#define OT_FULLSCRAPE_H__
6
7#ifdef WANT_FULLSCRAPE
8
9#include "ot_mutex.h"
10#include "ot_workqueue.h"
11
12void fullscrape_init(void);
13void fullscrape_deinit(void);
14void fullscrape_deliver(int64_t sock, ot_tasktype tasktype);
15
16#else
17
18#define fullscrape_init()
19#define fullscrape_deinit()
20
21#endif
22
23#endif
diff --git a/src/ot_hex.c b/src/ot_hex.c
new file mode 100644
index 0000000..b537094
--- /dev/null
+++ b/src/ot_hex.c
@@ -0,0 +1,56 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_hex.h"
10
11int hex_value(int c) {
12 unsigned char u = (unsigned char)c;
13
14 if (u >= '0' && u <= '9')
15 return u - '0';
16 u |= 0x20; /* fold upper case onto lower, digits are already handled */
17 if (u >= 'a' && u <= 'f')
18 return u - 'a' + 10;
19 return -1;
20}
21
22int hex_isdigit(int c) { return hex_value(c) >= 0; }
23
24char *hex_from_hash(char *dest, const uint8_t *hash) {
25 static const char digits[] = "0123456789ABCDEF";
26 char *d = dest;
27 size_t i;
28
29 for (i = 0; i < sizeof(ot_hash); ++i) {
30 *d++ = digits[hash[i] >> 4];
31 *d++ = digits[hash[i] & 15];
32 }
33 *d = 0;
34 return dest;
35}
36
37int hex_to_hash(ot_hash hash, const char *src) {
38 uint8_t decoded[sizeof(ot_hash)];
39 size_t i;
40
41 for (i = 0; i < sizeof(ot_hash); ++i) {
42 int high, low;
43
44 /* Tested one character at a time so that a string ending early stops us
45 at its terminator rather than one byte past it */
46 if ((high = hex_value((unsigned char)src[2 * i])) < 0)
47 return 0;
48 if ((low = hex_value((unsigned char)src[2 * i + 1])) < 0)
49 return 0;
50
51 decoded[i] = (uint8_t)((high << 4) | low);
52 }
53
54 memcpy(hash, decoded, sizeof(decoded));
55 return 1;
56}
diff --git a/src/ot_hex.h b/src/ot_hex.h
new file mode 100644
index 0000000..ddbbb44
--- /dev/null
+++ b/src/ot_hex.h
@@ -0,0 +1,27 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_HEX_H__
5#define OT_HEX_H__
6
7#include <stdint.h>
8
9#include "trackerlogic.h"
10
11/* Write hash as forty upper case hex digits followed by a terminating zero.
12 dest must have room for forty one bytes. Returns dest. */
13char *hex_from_hash(char *dest, const uint8_t *hash);
14
15/* Read forty hex digits from src into hash. Returns non-zero on success.
16 On failure hash is left untouched and no byte of src beyond the offending
17 character is read, so src need not be forty characters long. */
18int hex_to_hash(ot_hash hash, const char *src);
19
20/* Non-zero if c is a hexadecimal digit, in either case. */
21int hex_isdigit(int c);
22
23/* The value of a hexadecimal digit, or -1 if c is not one. Shared with the
24 address scanner so that both agree on what a digit is. */
25int hex_value(int c);
26
27#endif
diff --git a/src/ot_http.c b/src/ot_http.c
new file mode 100644
index 0000000..2e21546
--- /dev/null
+++ b/src/ot_http.c
@@ -0,0 +1,831 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#define _GNU_SOURCE
6#include <arpa/inet.h>
7#include <errno.h>
8#include <pthread.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <strings.h>
13#include <sys/types.h>
14#include <unistd.h>
15
16/* Opentracker */
17#include "ot_accesslist.h"
18#include "ot_fullscrape.h"
19#include "ot_http.h"
20#include "ot_iovec.h"
21#include "ot_ip.h"
22#include "ot_mutex.h"
23#include "ot_workqueue.h"
24#include "ot_scan.h"
25#include "ot_event.h"
26#include "ot_fdstate.h"
27#include "ot_vector.h"
28#include "ot_fmt.h"
29#include "ot_stats.h"
30#include "ot_urlencoded.h"
31#include "trackerlogic.h"
32
33#define OT_MAXMULTISCRAPE_COUNT 64
34extern const char *g_redirecturl;
35
36const char *g_stats_path;
37ssize_t g_stats_path_len;
38
39enum { SUCCESS_HTTP_HEADER_LENGTH = 80, SUCCESS_HTTP_SIZE_OFF = 17 };
40
41struct http_data *http_adopt(const int64_t sock) {
42 struct http_data *cookie = fdstate_cookie(sock), *heap;
43 int interest;
44
45 if (!cookie || !(cookie->flag & STRUCT_HTTP_FLAG_ONSTACK))
46 return cookie;
47
48 if (!(heap = malloc(sizeof(*heap))))
49 return NULL;
50
51 *heap = *cookie;
52 heap->flag &= ~STRUCT_HTTP_FLAG_ONSTACK;
53
54 /* Publishing the cookie is what lets another thread reach this connection,
55 so nothing may touch it afterwards, not even to read what it asked for */
56 interest = heap->interest;
57 fdstate_set_cookie((int)sock, heap);
58
59 if (event_add((int)sock, interest, fdstate_generation((int)sock)) == -1) {
60 fdstate_set_cookie((int)sock, cookie);
61 free(heap);
62 return NULL;
63 }
64 return heap;
65}
66
67/* Give up a connection: the one place that knows everything hanging off it. */
68void http_close(const int64_t sock) {
69 struct http_data *cookie = fdstate_cookie(sock);
70
71 fdstate_close((int)sock);
72
73 if (cookie) {
74 if (cookie->batch)
75 batch_reset(cookie->batch);
76 free(cookie->batch);
77 buf_reset(&cookie->request);
78 if (cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER))
79 workqueue_canceltask(sock);
80 if (!(cookie->flag & STRUCT_HTTP_FLAG_ONSTACK))
81 free(cookie);
82 }
83
84 event_close((int)sock);
85}
86
87static void http_senddata(const int64_t sock, struct ot_workstruct *ws) {
88 struct http_data *cookie = fdstate_cookie(sock);
89 ssize_t written_size;
90
91 if (!cookie) {
92 http_close(sock);
93 return;
94 }
95
96 /* whoever sends data is not interested in its input buffer */
97 if (ws->keep_alive && ws->header_size != ws->request_size) {
98 size_t rest = ws->request_size - ws->header_size;
99 if (cookie->request.data) {
100 memmove(cookie->request.data, ws->request + ws->header_size, rest);
101 buf_truncate(&cookie->request, rest);
102 } else if (buf_cat(&cookie->request, ws->request + ws->header_size, rest)) {
103 /* Without room for what the client pipelined behind this request, answer
104 this one and let the connection close, rather than keeping it open
105 around a request we have silently dropped */
106 buf_reset(&cookie->request);
107 ws->keep_alive = 0;
108 }
109 } else
110 buf_reset(&cookie->request);
111
112 written_size = write(sock, ws->reply, ws->reply_size);
113 /* A send buffer with no room in it is not a failure: nothing went out, so
114 the whole reply goes into the batch below and leaves when the socket
115 drains. Only a real error ends the connection here. */
116 if (written_size < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
117 written_size = 0;
118
119 if ((written_size < 0) || ((written_size == ws->reply_size) && !ws->keep_alive)) {
120 http_close(sock);
121 return;
122 }
123
124 if (written_size < ws->reply_size) {
125 char *outbuf;
126
127 if (!(outbuf = malloc(ws->reply_size - written_size))) {
128 http_close(sock);
129 return;
130 }
131
132 memcpy(outbuf, ws->reply + written_size, ws->reply_size - written_size);
133 if (!cookie->batch) {
134 cookie->batch = calloc(1, sizeof(ot_batch));
135 if (!cookie->batch) {
136 free(outbuf);
137 http_close(sock);
138 return;
139 }
140 }
141
142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size);
143
144 /* Reset any connections potentially near their timeout */
145 if (!ws->keep_alive)
146 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
147 http_interest_set(sock, cookie, EVENT_OUT);
148 }
149}
150
151#define HTTPERROR_302 return http_issue_error(sock, ws, CODE_HTTPERROR_302)
152#define HTTPERROR_400 return http_issue_error(sock, ws, CODE_HTTPERROR_400)
153#define HTTPERROR_400_PARAM return http_issue_error(sock, ws, CODE_HTTPERROR_400_PARAM)
154#define HTTPERROR_400_COMPACT return http_issue_error(sock, ws, CODE_HTTPERROR_400_COMPACT)
155#define HTTPERROR_400_DOUBLEHASH return http_issue_error(sock, ws, CODE_HTTPERROR_400_PARAM)
156#define HTTPERROR_402_NOTMODEST return http_issue_error(sock, ws, CODE_HTTPERROR_402_NOTMODEST)
157#define HTTPERROR_403_IP return http_issue_error(sock, ws, CODE_HTTPERROR_403_IP)
158#define HTTPERROR_404 return http_issue_error(sock, ws, CODE_HTTPERROR_404)
159#define HTTPERROR_500 return http_issue_error(sock, ws, CODE_HTTPERROR_500)
160/* A connection is either being read or being written, never both, so what it
161 waits for is set outright rather than added to and taken away again. The
162 event layer only hears about it when the answer changes. */
163void http_interest_set(const int64_t sock, struct http_data *cookie, int what) {
164 if (cookie->interest == what)
165 return;
166 cookie->interest = what;
167 /* Still on a stack, so not in the event loop yet: whoever adopts this
168 connection registers whatever it asked for last */
169 if (cookie->flag & STRUCT_HTTP_FLAG_ONSTACK)
170 return;
171 event_modify((int)sock, what, fdstate_generation((int)sock));
172}
173
174ssize_t http_issue_error(const int64_t sock, struct ot_workstruct *ws, int code) {
175 const char *error_code[] = {"302 Found", "400 Invalid Request", "400 Invalid Request", "400 Invalid Request", "402 Payment Required",
176 "403 Not Modest", "403 Access Denied", "404 Not Found", "500 Internal Server Error"};
177 const char *title = error_code[code];
178
179 ws->reply = ws->outbuf;
180 if (code == CODE_HTTPERROR_302)
181 ws->reply_size = snprintf(ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 302 Found\r\nContent-Length: 0\r\nLocation: %s\r\n\r\n", g_redirecturl);
182 else
183 ws->reply_size = snprintf(ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 %s\r\nContent-Type: text/html\r\nContent-Length: %zd\r\n\r\n<title>%s</title>\n", title,
184 strlen(title) + 16 - 4, title + 4);
185
186#ifdef _DEBUG_HTTPERROR
187 fprintf(stderr, "DEBUG: invalid request was: %s\n", ws->debugbuf);
188#endif
189 stats_issue_event(ws, EVENT_FAILED, FLAG_TCP, code);
190 http_senddata(sock, ws);
191 return ws->reply_size = -2;
192}
193
194ssize_t http_sendiovecdata(const int64_t sock, struct ot_workstruct *ws, size_t iovec_entries, struct iovec *iovector, int is_partial) {
195 struct http_data *cookie = fdstate_cookie(sock);
196 char *header;
197 const char *encoding = "";
198 size_t header_size, size = iovec_length(&iovec_entries, (const struct iovec **)&iovector);
199
200 /* No cookie? Bad socket. Leave. */
201 if (!cookie) {
202 iovec_free(&iovec_entries, &iovector);
203 HTTPERROR_500;
204 }
205
206 /* Descriptor numbers get recycled, so a result can only belong to this
207 connection if this connection is in fact waiting for one. */
208 if (!(cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER))) {
209 iovec_free(&iovec_entries, &iovector);
210 return 0;
211 }
212
213 /* If this socket collected request in a buffer, free it now */
214 buf_reset(&cookie->request);
215
216 /* If we came here, wait for the answer is over */
217 if (cookie->flag & STRUCT_HTTP_FLAG_WAITINGFORTASK) {
218 http_interest_set(sock, cookie, 0);
219 cookie->flag &= ~STRUCT_HTTP_FLAG_WAITINGFORTASK;
220 }
221
222 if (iovec_entries) {
223
224 if (cookie->flag & STRUCT_HTTP_FLAG_ZSTD)
225 encoding = "Content-Encoding: zstd\r\n";
226 else if (cookie->flag & STRUCT_HTTP_FLAG_GZIP)
227 encoding = "Content-Encoding: gzip\r\n";
228 else if (cookie->flag & STRUCT_HTTP_FLAG_BZIP2)
229 encoding = "Content-Encoding: bzip2\r\n";
230
231 if (!(cookie->flag & STRUCT_HTTP_FLAG_CHUNKED))
232 header_size = asprintf(&header, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n%sContent-Length: %zd\r\n\r\n", encoding, size);
233 else {
234 if (!(cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)) {
235 header_size =
236 asprintf(&header, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n%sTransfer-Encoding: chunked\r\n\r\n%zx\r\n", encoding, size);
237 cookie->flag |= STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER;
238 } else
239 header_size = asprintf(&header, "%zx\r\n", size);
240 }
241 if (!header) {
242 iovec_free(&iovec_entries, &iovector);
243 HTTPERROR_500;
244 }
245
246 if (!cookie->batch) {
247 cookie->batch = calloc(1, sizeof(ot_batch));
248 if (!cookie->batch) {
249 free(header);
250 iovec_free(&iovec_entries, &iovector);
251 HTTPERROR_500;
252 }
253 }
254
255 batch_add(cookie->batch, header, header_size);
256 batch_add_vector(cookie->batch, iovector, iovec_entries);
257 free(iovector);
258
259 if (cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)
260 batch_add_copy(cookie->batch, "\r\n", 2);
261 }
262
263 if ((cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER) && cookie->batch && !is_partial) {
264 batch_add_copy(cookie->batch, "0\r\n\r\n", 5);
265 cookie->flag &= ~STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER;
266 }
267
268 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
269 http_interest_set(sock, cookie, EVENT_OUT);
270 return 0;
271}
272
273static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
274 static const ot_keywords keywords_main[] = {{"mode", 1}, {"format", 2}, {"info_hash", 3}, {NULL, -3}};
275 static const ot_keywords keywords_mode[] = {{"peer", TASK_STATS_PEERS},
276 {"conn", TASK_STATS_CONNS},
277 {"scrp", TASK_STATS_SCRAPE},
278 {"udp4", TASK_STATS_UDP},
279 {"tcp4", TASK_STATS_TCP},
280 {"torr", TASK_STATS_TORRENTS},
281 {"fscr", TASK_STATS_FULLSCRAPE},
282 {"tpbs", TASK_STATS_TPB},
283 {"herr", TASK_STATS_HTTPERRORS},
284 {"completed", TASK_STATS_COMPLETED},
285 {"top100", TASK_STATS_TOP100},
286 {"top10", TASK_STATS_TOP10},
287 {"renew", TASK_STATS_RENEW},
288 {"syncs", TASK_STATS_SYNCS},
289 {"everything", TASK_STATS_EVERYTHING},
290 {"statedump", TASK_FULLSCRAPE_TRACKERSTATE},
291 {"woodpeckers", TASK_STATS_WOODPECKERS},
292#ifdef WANT_LOG_NUMWANT
293 {"numwants", TASK_STATS_NUMWANTS},
294#endif
295 {NULL, -3}};
296 static const ot_keywords keywords_format[] = {{"bin", TASK_FULLSCRAPE_TPB_BINARY}, {"ben", TASK_FULLSCRAPE},
297 {"url", TASK_FULLSCRAPE_TPB_URLENCODED}, {"txt", TASK_FULLSCRAPE_TPB_ASCII},
298 {"txtp", TASK_FULLSCRAPE_TPB_ASCII_PLUS}, {NULL, -3}};
299
300 struct http_data *cookie = fdstate_cookie(sock);
301 char *reply;
302 int mode = TASK_STATS_PEERS, scanon = 1, format = 0;
303
304 /* A socket without one is a dead socket, which is what http_sendiovecdata
305 already answers 500 to. */
306 if (!cookie)
307 HTTPERROR_500;
308
309#ifdef WANT_RESTRICT_STATS
310 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_STAT))
311 HTTPERROR_403_IP;
312#endif
313
314 while (scanon) {
315 switch (urlencoded_match_keyword(keywords_main, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
316 case -2:
317 scanon = 0;
318 break; /* TERMINATOR */
319 case -1:
320 HTTPERROR_400_PARAM; /* PARSE ERROR */
321 case -3:
322 urlencoded_skip_value(&read_ptr);
323 break;
324 case 1: /* matched "mode" */
325 if ((mode = urlencoded_match_keyword(keywords_mode, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
326 HTTPERROR_400_PARAM;
327 break;
328 case 2: /* matched "format" */
329 if ((format = urlencoded_match_keyword(keywords_format, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
330 HTTPERROR_400_PARAM;
331 break;
332 case 3:
333 HTTPERROR_400_PARAM; /* If the stats URL was mistakenly added as announce URL, return a 400 */
334 }
335 }
336
337#ifdef WANT_FULLSCRAPE
338 if (mode == TASK_FULLSCRAPE_TRACKERSTATE) {
339 format = mode;
340 mode = TASK_STATS_TPB;
341 }
342
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
348#ifdef WANT_COMPRESSION_GZIP
349 ws->request[ws->request_size - 1] = 0;
350#ifndef WANT_COMPRESSION_GZIP_ALWAYS
351 if (strstr(read_ptr - 1, "gzip")) {
352#endif
353 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
354 format |= TASK_FLAG_GZIP;
355#ifndef WANT_COMPRESSION_GZIP_ALWAYS
356 }
357#endif
358#endif
359 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED;
360
361 /* Clients waiting for us should not easily timeout */
362 fdstate_set_expiry(sock, 0);
363 http_interest_set(sock, cookie, 0);
364
365 /* Everything this connection needs has been written, so it can be given
366 a home of its own and only then be made reachable by a worker thread */
367 if (!http_adopt(sock))
368 HTTPERROR_500;
369 ws->handed_off = 1;
370 fullscrape_deliver(sock, format);
371 return ws->reply_size = -2;
372 }
373#endif
374
375 /* default format for now */
376 if ((mode & TASK_CLASS_MASK) == TASK_STATS) {
377
378 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK;
379
380 /* Complex stats also include expensive memory debugging tools */
381 fdstate_set_expiry(sock, 0);
382 http_interest_set(sock, cookie, 0);
383
384 if (!http_adopt(sock))
385 HTTPERROR_500;
386 ws->handed_off = 1;
387 stats_deliver(sock, mode);
388 return ws->reply_size = -2;
389 }
390
391 /* Simple stats can be answerred immediately */
392 reply = ws->reply;
393 return_stats_for_tracker(&reply, ws->outbuf + G_OUTBUF_SIZE, mode, 0);
394 return ws->reply_size = reply - ws->reply;
395}
396
397#ifdef WANT_MODEST_FULLSCRAPES
398static pthread_mutex_t g_modest_fullscrape_mutex = PTHREAD_MUTEX_INITIALIZER;
399static ot_vector g_modest_fullscrape_timeouts;
400typedef struct {
401 ot_ip6 ip;
402 ot_time last_fullscrape;
403} ot_scrape_log;
404#endif
405
406#ifdef WANT_FULLSCRAPE
407static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct *ws) {
408 struct http_data *cookie = fdstate_cookie(sock);
409 int format = 0;
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
419#ifdef WANT_MODEST_FULLSCRAPES
420 {
421 ot_scrape_log this_peer, *new_peer;
422 int exactmatch;
423 memcpy(this_peer.ip, cookie->ip, sizeof(ot_ip6));
424 this_peer.last_fullscrape = time_now_seconds();
425 pthread_mutex_lock(&g_modest_fullscrape_mutex);
426 new_peer = vector_find_or_insert(&g_modest_fullscrape_timeouts, &this_peer, sizeof(ot_scrape_log), sizeof(ot_ip6), &exactmatch);
427 if (!new_peer) {
428 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
429 HTTPERROR_500;
430 }
431 if (exactmatch && time_since_seconds(new_peer->last_fullscrape) < OT_MODEST_PEER_TIMEOUT) {
432 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
433 HTTPERROR_402_NOTMODEST;
434 }
435 memcpy(new_peer, &this_peer, sizeof(ot_scrape_log));
436 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
437 }
438#endif
439
440
441#if defined(WANT_COMPRESSION_GZIP) || defined(WANT_COMPRESSION_ZSTD)
442 ws->request[ws->request_size - 1] = 0;
443#ifdef WANT_COMPRESSION_GZIP
444 if (strstr(ws->request, "gzip")) {
445 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
446 format |= TASK_FLAG_GZIP;
447 }
448#endif
449#ifdef WANT_COMPRESSION_ZSTD
450 if (strstr(ws->request, "zstd")) {
451 cookie->flag |= STRUCT_HTTP_FLAG_ZSTD;
452 format |= TASK_FLAG_ZSTD;
453 }
454#endif
455
456#if defined(WANT_COMPRESSION_ZSTD) && defined(WANT_COMPRESSION_ZSTD_ALWAYS)
457 cookie->flag |= STRUCT_HTTP_FLAG_ZSTD;
458 format |= TASK_FLAG_ZSTD;
459#endif
460
461#if defined(WANT_COMPRESSION_GZIP) && defined(WANT_COMPRESSION_GZIP_ALWAYS)
462 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
463 format |= TASK_FLAG_GZIP;
464#endif
465#endif
466
467 stats_issue_event(ws, EVENT_FULLSCRAPE_REQUEST, 0, (uintptr_t)cookie->ip);
468
469#ifdef _DEBUG_HTTPERROR
470 fprintf(stderr, "%s", ws->debugbuf);
471#endif
472
473 /* Pass this task to the worker thread */
474 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED;
475 /* Clients waiting for us should not easily timeout */
476 fdstate_set_expiry(sock, 0);
477 http_interest_set(sock, cookie, 0);
478
479 if (!http_adopt(sock))
480 HTTPERROR_500;
481 ws->handed_off = 1;
482 fullscrape_deliver(sock, format);
483 return ws->reply_size = -2;
484}
485#endif
486
487static int compare_hash(const void *left, const void *right) { return memcmp(left, right, sizeof(ot_hash)); }
488
489static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
490 static const ot_keywords keywords_scrape[] = {{"info_hash", 1}, {NULL, -3}};
491
492 ot_hash *multiscrape_buf = (ot_hash *)ws->request;
493 char *reply = ws->reply;
494 int scanon = 1;
495 size_t i, unique, numwant = 0;
496
497 /* This is to hack around stupid clients that send "scrape ?info_hash" */
498 if (read_ptr[-1] != '?') {
499 while ((*read_ptr != '?') && (*read_ptr != '\n'))
500 ++read_ptr;
501 if (*read_ptr == '\n')
502 HTTPERROR_400_PARAM;
503 ++read_ptr;
504 }
505
506 while (scanon) {
507 switch (urlencoded_match_keyword(keywords_scrape, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
508 case -2:
509 scanon = 0;
510 break; /* TERMINATOR */
511 default:
512 HTTPERROR_400_PARAM; /* PARSE ERROR */
513 case -3:
514 urlencoded_skip_value(&read_ptr);
515 break;
516 case 1: /* matched "info_hash" */
517 {
518 /* ignore this, when we have less than 20 bytes */
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))
521 HTTPERROR_400_PARAM;
522 } break;
523 }
524 }
525
526 /* No info_hash found? Inform user */
527 if (!numwant)
528 HTTPERROR_400_PARAM;
529
530 /* Limit number of hashes to process */
531 if (numwant > OT_MAXMULTISCRAPE_COUNT)
532 numwant = OT_MAXMULTISCRAPE_COUNT;
533
534 /* A bencoded dictionary has its keys in order and names each one once, so
535 the answer cannot just follow the order the client asked in */
536 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash);
537 for (i = unique = 1; i < numwant; ++i)
538 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash)))
539 memmove(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash));
540 numwant = unique;
541
542 /* Enough for http header + whole scrape string */
543 return_tcp_scrape_for_torrent((const ot_hash *)multiscrape_buf, numwant, &reply, ws->outbuf + G_OUTBUF_SIZE);
544 ws->reply_size = reply - ws->reply;
545 stats_issue_event(ws, EVENT_SCRAPE, FLAG_TCP, ws->reply_size);
546 return ws->reply_size;
547}
548
549#ifdef WANT_LOG_NUMWANT
550unsigned long long numwants[201];
551#endif
552
553#if defined(WANT_KEEPALIVE) || defined(WANT_IP_FROM_PROXY)
554static char *http_header(char *data, size_t byte_count, const char *header) {
555 size_t i;
556 long sl = strlen(header);
557 for (i = 0; i + sl + 2 < byte_count; ++i) {
558 if (data[i] != '\n' || data[i + sl + 1] != ':')
559 continue;
560 if (strncasecmp(data + i + 1, header, sl))
561 continue;
562 data += i + sl + 2;
563 while (*data == ' ' || *data == '\t')
564 ++data;
565 return data;
566 }
567 return 0;
568}
569#endif
570
571static ot_keywords keywords_announce[] = {{"port", 1}, {"left", 2}, {"event", 3}, {"numwant", 4}, {"compact", 5}, {"compact6", 5}, {"info_hash", 6},
572#ifdef WANT_IP_FROM_QUERY_STRING
573 {"ip", 7},
574#endif
575 {"peer_id", 8}, {NULL, -3}};
576static ot_keywords keywords_announce_event[] = {{"completed", 1}, {"stopped", 2}, {NULL, -3}};
577
578/* For the replies that are one fixed string and nothing else, where the only
579 thing the caller wants back is how long it turned out */
580static ssize_t reply_literal(struct ot_workstruct *ws, const char *text) {
581 char *reply = ws->reply;
582
583 fmt_bytes(&reply, ws->outbuf + G_OUTBUF_SIZE, text, strlen(text));
584 return reply - ws->reply;
585}
586
587static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
588 size_t numwant;
589 int64_t tmp;
590 int scanon;
591 unsigned short port = 0;
592 char *write_ptr;
593 ssize_t len;
594 struct http_data *cookie = fdstate_cookie(sock);
595
596 /* This is to hack around stupid clients that send "announce ?info_hash" */
597 if (read_ptr[-1] != '?') {
598 while ((*read_ptr != '?') && (*read_ptr != '\n'))
599 ++read_ptr;
600 if (*read_ptr == '\n')
601 HTTPERROR_400_PARAM;
602 ++read_ptr;
603 }
604
605#ifdef WANT_IP_FROM_PROXY
606 if (accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_PROXY)) {
607 ot_ip6 proxied_ip;
608 char *fwd = http_header(ws->request, ws->header_size, "x-forwarded-for");
609 if (fwd && ip_parse(fwd, proxied_ip)) {
610 OT_SETIP(ws->peer, proxied_ip);
611 } else
612 OT_SETIP(ws->peer, cookie->ip);
613 } else
614#endif
615 OT_SETIP(ws->peer, cookie->ip);
616
617 ws->peer_id = NULL;
618 ws->hash = NULL;
619
620 OT_SETPORT(ws->peer, &port);
621 OT_PEERFLAG(ws->peer) = 0;
622 numwant = 50;
623 scanon = 1;
624
625 while (scanon) {
626 switch (urlencoded_match_keyword(keywords_announce, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
627 case -2:
628 scanon = 0;
629 break; /* TERMINATOR */
630 case -1:
631 HTTPERROR_400_PARAM; /* PARSE ERROR */
632 case -3:
633 urlencoded_skip_value(&read_ptr);
634 break;
635 case 1: /* matched "port" */
636 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
637 if ((len <= 0) || scan_int(write_ptr, len, &tmp) || (tmp < 0) || (tmp > 0xffff))
638 HTTPERROR_400_PARAM;
639 port = htons((uint16_t)tmp);
640 OT_SETPORT(&ws->peer, &port);
641 break;
642 case 2: /* matched "left" */
643 if ((len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
644 HTTPERROR_400_PARAM;
645 if (scan_int(write_ptr, len, &tmp))
646 tmp = 0;
647 if (!tmp)
648 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_SEEDING;
649 break;
650 case 3: /* matched "event" */
651 switch (urlencoded_match_keyword(keywords_announce_event, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) {
652 case -1:
653 HTTPERROR_400_PARAM;
654 case 1: /* matched "completed" */
655 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_COMPLETED;
656 break;
657 case 2: /* matched "stopped" */
658 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_STOPPED;
659 break;
660 default:
661 break;
662 }
663 break;
664 case 4: /* matched "numwant" */
665 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
666 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
667 HTTPERROR_400_PARAM;
668 if (tmp < 0)
669 tmp = 50;
670 if (tmp > 200)
671 tmp = 200;
672 numwant = (size_t)tmp;
673 break;
674 case 5: /* matched "compact" */
675 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
676 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
677 HTTPERROR_400_PARAM;
678 if (!tmp)
679 HTTPERROR_400_COMPACT;
680 break;
681 case 6: /* matched "info_hash" */
682 if (ws->hash)
683 HTTPERROR_400_DOUBLEHASH;
684 /* ignore this, when we have less than 20 bytes */
685 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
686 HTTPERROR_400_PARAM;
687 ws->hash = (ot_hash *)write_ptr;
688 break;
689#ifdef WANT_IP_FROM_QUERY_STRING
690 case 7: /* matched "ip" */
691 {
692 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16;
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;
697 tmp_buf2[len] = 0;
698 if (ip_parse(tmp_buf2, tmp_buf1) != (size_t)len)
699 HTTPERROR_400_PARAM;
700 OT_SETIP(&ws->peer, tmp_buf1);
701 } break;
702#endif
703 case 8: /* matched "peer_id" */
704 /* ignore this, when we have less than 20 bytes */
705 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
706 HTTPERROR_400_PARAM;
707 ws->peer_id = write_ptr;
708 break;
709 }
710 }
711
712#ifdef WANT_LOG_NUMWANT
713 numwants[numwant]++;
714#endif
715
716 /* XXX DEBUG
717 stats_issue_event(ws, EVENT_ACCEPT, FLAG_TCP, (uintptr_t)ws->reply );
718 */
719
720 /* Scanned whole query string */
721 if (!ws->hash)
722 return ws->reply_size = reply_literal(ws, "d14:failure reason80:Your client forgot to send your torrent's info_hash. Please upgrade your client.e");
723
724 if (OT_PEERFLAG(&ws->peer) & PEER_FLAG_STOPPED)
725 ws->reply_size = remove_peer_from_torrent(FLAG_TCP, ws);
726 else
727 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, numwant);
728
729 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_TCP, ws->reply_size);
730 return ws->reply_size;
731}
732
733ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
734 ssize_t reply_off, len;
735 char *read_ptr = ws->request, *write_ptr;
736
737#ifdef _DEBUG_HTTPERROR
738 reply_off = ws->request_size;
739 if (ws->request_size >= G_DEBUGBUF_SIZE)
740 reply_off = G_DEBUGBUF_SIZE - 1;
741 memcpy(ws->debugbuf, ws->request, reply_off);
742 ws->debugbuf[reply_off] = 0;
743#endif
744
745 /* Tell subroutines where to put reply data */
746 ws->reply = ws->outbuf + SUCCESS_HTTP_HEADER_LENGTH;
747
748 /* Find out if the client wants to keep this connection alive, before any
749 subroutine gets to answer: an error reply finishes with the connection
750 on its way out, and ws outlives the connection it was serving */
751 ws->keep_alive = 0;
752 ws->handed_off = 0;
753#ifdef WANT_KEEPALIVE
754 if ((write_ptr = http_header(ws->request, ws->header_size, "connection")) && (*write_ptr == 'K' || *write_ptr == 'k'))
755 ws->keep_alive = 1;
756#endif
757 {
758 struct http_data *connection = fdstate_cookie(sock);
759 if (connection) {
760 if (ws->keep_alive)
761 connection->flag |= STRUCT_HTTP_FLAG_KEEPALIVE;
762 else
763 connection->flag &= ~STRUCT_HTTP_FLAG_KEEPALIVE;
764 }
765 }
766
767 /* The request need not be NUL terminated and can be shorter than the literal */
768 if (ws->request_size < 5 || memcmp(read_ptr, "GET /", 5))
769 HTTPERROR_400;
770
771 /* Skip leading '/' */
772 for (read_ptr += 4; *read_ptr == '/'; ++read_ptr)
773 ;
774
775 /* Try to parse the request.
776 In reality we abandoned requiring the url to be correct. This now
777 only decodes url encoded characters, we check for announces and
778 scrapes by looking for "a*" or "sc" */
779 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_PATH);
780
781 /* If parsing returned an error, leave with not found */
782 if (g_redirecturl && (len == -2))
783 HTTPERROR_302;
784 if (len <= 0)
785 HTTPERROR_404;
786
787 /* This is the hardcore match for announce*/
788 if ((*write_ptr == 'a') || (*write_ptr == '?'))
789 http_handle_announce(sock, ws, read_ptr);
790#ifdef WANT_FULLSCRAPE
791 else if (ws->request + ws->request_size - write_ptr >= 12 && !memcmp(write_ptr, "scrape HTTP/", 12))
792 http_handle_fullscrape(sock, ws);
793#endif
794 /* This is the hardcore match for scrape */
795 else if (!memcmp(write_ptr, "sc", 2))
796 http_handle_scrape(sock, ws, read_ptr);
797 /* All the rest is matched the standard way */
798 else if (len == g_stats_path_len && !memcmp(write_ptr, g_stats_path, len))
799 http_handle_stats(sock, ws, read_ptr);
800 else
801 HTTPERROR_404;
802
803 /* If routines handled sending themselves, just return */
804 if (ws->reply_size == -2)
805 return 0;
806 /* If routine failed, let http error take over */
807 if (ws->reply_size <= 0)
808 HTTPERROR_500;
809
810 /* This one is rather ugly, so I take you step by step through it.
811
812 1. In order to avoid having two buffers, one for header and one for content, we allow all above functions from trackerlogic to
813 write to a fixed location, leaving SUCCESS_HTTP_HEADER_LENGTH bytes in our work buffer, which is enough for the static string
814 plus dynamic space needed to expand our Content-Length value. We reserve SUCCESS_HTTP_SIZE_OFF for its expansion and calculate
815 the space NOT needed to expand in reply_off
816 */
817 reply_off = SUCCESS_HTTP_SIZE_OFF - snprintf(ws->outbuf, 0, "%zd", ws->reply_size);
818 ws->reply = ws->outbuf + reply_off;
819
820 /* 2. Now we write the header so that its terminating '\0' lands exactly one byte before the content starts. The bound is the
821 space step 1 reserved, so the '\0' falls where step 3 expects it. Complete packet size is increased by size of header plus
822 one byte '\n', we will copy over '\0' in next step */
823 ws->reply_size += 1 + snprintf(ws->reply, (size_t)(SUCCESS_HTTP_HEADER_LENGTH - reply_off),
824 "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %zd\r\n\r", ws->reply_size);
825
826 /* 3. Finally we join both blocks neatly */
827 ws->outbuf[SUCCESS_HTTP_HEADER_LENGTH - 1] = '\n';
828
829 http_senddata(sock, ws);
830 return ws->reply_size;
831}
diff --git a/src/ot_http.h b/src/ot_http.h
new file mode 100644
index 0000000..fb56c64
--- /dev/null
+++ b/src/ot_http.h
@@ -0,0 +1,53 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_HTTP_H__
5#define OT_HTTP_H__
6
7#include <stdint.h>
8#include <sys/types.h>
9#include <sys/uio.h>
10
11#include "ot_batch.h"
12#include "ot_event.h"
13#include "ot_buf.h"
14#include "trackerlogic.h"
15
16typedef enum {
17 STRUCT_HTTP_FLAG_WAITINGFORTASK = 1,
18 STRUCT_HTTP_FLAG_GZIP = 2,
19 STRUCT_HTTP_FLAG_BZIP2 = 4,
20 STRUCT_HTTP_FLAG_ZSTD = 8,
21 STRUCT_HTTP_FLAG_CHUNKED = 16,
22 STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER = 32,
23 STRUCT_HTTP_FLAG_KEEPALIVE = 64,
24 STRUCT_HTTP_FLAG_ONSTACK = 128
25} STRUCT_HTTP_FLAG;
26
27struct http_data {
28 ot_buf request;
29 int interest; /* EVENT_IN and EVENT_OUT as asked for */
30 ot_batch *batch;
31 ot_ip6 ip;
32 STRUCT_HTTP_FLAG flag;
33};
34
35/* What this connection is waiting for: EVENT_IN, EVENT_OUT, or nothing */
36void http_interest_set(const int64_t s, struct http_data *cookie, int what);
37
38/* Close a connection and release everything that belongs to it */
39void http_close(const int64_t s);
40
41/* Promote a stack cookie to a heap one, for persistence and for handing it
42 over to the event loop or to another thread. Does nothing to one that is
43 already on the heap. Returns the connection's state, or NULL. */
44struct http_data *http_adopt(const int64_t s);
45
46ssize_t http_handle_request(const int64_t s, struct ot_workstruct *ws);
47ssize_t http_sendiovecdata(const int64_t s, struct ot_workstruct *ws, size_t iovec_entries, struct iovec *iovector, int is_partial);
48ssize_t http_issue_error(const int64_t s, struct ot_workstruct *ws, int code);
49
50extern const char *g_stats_path;
51extern ssize_t g_stats_path_len;
52
53#endif
diff --git a/src/ot_iovec.c b/src/ot_iovec.c
new file mode 100644
index 0000000..328f160
--- /dev/null
+++ b/src/ot_iovec.c
@@ -0,0 +1,87 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <sys/uio.h>
7
8/* Opentracker */
9#include "ot_iovec.h"
10
11void *iovec_new_chunk(size_t *iovec_entries, struct iovec **iovector, size_t new_alloc) {
12 void *new_data;
13 size_t new_entries = 1 + *iovec_entries;
14 struct iovec *new_vec = realloc(*iovector, new_entries * sizeof(struct iovec));
15
16 if (!new_vec)
17 return NULL;
18
19 *iovector = new_vec;
20
21 /* Only allocate after we have a place to store the pointer */
22 new_data = malloc(new_alloc);
23 if (!new_data)
24 return NULL;
25
26 new_vec[new_entries - 1].iov_base = new_data;
27 new_vec[new_entries - 1].iov_len = new_alloc;
28
29 ++*iovec_entries;
30 return new_data;
31}
32
33void *iovec_append(size_t *iovec_entries, struct iovec **iovector, struct iovec *append_iovector) {
34 size_t new_entries = *iovec_entries + 1;
35 struct iovec *new_vec = realloc(*iovector, new_entries * sizeof(struct iovec));
36 if (!new_vec)
37 return NULL;
38
39 /* Take over data from appended iovec */
40 new_vec[*iovec_entries].iov_base = append_iovector->iov_base;
41 new_vec[*iovec_entries].iov_len = append_iovector->iov_len;
42
43 append_iovector->iov_base = NULL;
44 append_iovector->iov_len = 0;
45
46 *iovector = new_vec;
47 *iovec_entries = new_entries;
48
49 return new_vec;
50}
51
52void iovec_free(size_t *iovec_entries, struct iovec **iovector) {
53 size_t i;
54 for (i = 0; i < *iovec_entries; ++i)
55 free(((*iovector)[i]).iov_base);
56 free(*iovector);
57 *iovector = NULL;
58 *iovec_entries = 0;
59}
60
61void iovec_trim_last(size_t *iovec_entries, struct iovec **iovector, void *last_ptr) {
62 if (*iovec_entries) {
63 char *base = (char *)((*iovector)[*iovec_entries - 1]).iov_base;
64 size_t new_alloc = ((char *)last_ptr) - base;
65
66 ((*iovector)[*iovec_entries - 1]).iov_base = realloc(base, new_alloc);
67 ((*iovector)[*iovec_entries - 1]).iov_len = new_alloc;
68 }
69}
70
71void *iovec_next_chunk(size_t *iovec_entries, struct iovec **iovector, void *last_ptr, size_t new_alloc) {
72 void *new_data;
73
74 iovec_trim_last(iovec_entries, iovector, last_ptr);
75
76 if (!(new_data = iovec_new_chunk(iovec_entries, iovector, new_alloc)))
77 iovec_free(iovec_entries, iovector);
78
79 return new_data;
80}
81
82size_t iovec_length(const size_t *iovec_entries, const struct iovec **iovector) {
83 size_t i, length = 0;
84 for (i = 0; i < *iovec_entries; ++i)
85 length += ((*iovector)[i]).iov_len;
86 return length;
87}
diff --git a/src/ot_iovec.h b/src/ot_iovec.h
new file mode 100644
index 0000000..4a8abbb
--- /dev/null
+++ b/src/ot_iovec.h
@@ -0,0 +1,18 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_IOVEC_H__
5#define OT_IOVEC_H__
6
7#include <sys/uio.h>
8
9void *iovec_new_chunk(size_t *iovec_entries, struct iovec **iovector, size_t new_alloc);
10void *iovec_append(size_t *iovec_entries, struct iovec **iovector, struct iovec *append_iovector);
11void iovec_trim_last(size_t *iovec_entries, struct iovec **iovector, void *last_ptr);
12void iovec_free(size_t *iovec_entries, struct iovec **iovector);
13
14size_t iovec_length(const size_t *iovec_entries, const struct iovec **iovector);
15
16void *iovec_next_chunk(size_t *iovec_entries, struct iovec **iovector, void *last_ptr, size_t new_alloc);
17
18#endif
diff --git a/src/ot_ip.c b/src/ot_ip.c
new file mode 100644
index 0000000..9c76290
--- /dev/null
+++ b/src/ot_ip.c
@@ -0,0 +1,199 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_hex.h"
10#include "ot_ip.h"
11
12const char ip_v4mapped_prefix[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
13
14/* The dotted quad is only ever reached through the v4 mapped form, so both
15 halves of it stay in here */
16
17static size_t ip4_format(char *dest, const uint8_t *ip) {
18 char *d = dest;
19 int i;
20
21 for (i = 0; i < 4; ++i) {
22 unsigned int octet = ip[i];
23
24 if (i)
25 *d++ = '.';
26 if (octet >= 100)
27 *d++ = (char)('0' + octet / 100);
28 if (octet >= 10)
29 *d++ = (char)('0' + (octet / 10) % 10);
30 *d++ = (char)('0' + octet % 10);
31 }
32
33 return (size_t)(d - dest);
34}
35
36static size_t ip4_scan(const char *src, uint8_t ip[4]) {
37 uint8_t octets[4];
38 const char *s = src;
39 int i;
40
41 for (i = 0; i < 4; ++i) {
42 unsigned int value = 0;
43 int digits = 0;
44
45 if (i && *s++ != '.')
46 return 0;
47
48 /* Leading zeros are tolerated, a value beyond one octet is not */
49 while (*s >= '0' && *s <= '9' && digits < 4) {
50 value = value * 10 + (unsigned int)(*s++ - '0');
51 ++digits;
52 }
53 if (!digits || value > 255)
54 return 0;
55
56 octets[i] = (uint8_t)value;
57 }
58
59 memcpy(ip, octets, sizeof(octets));
60 return (size_t)(s - src);
61}
62
63static unsigned int group_at(const char *ip, int n) { return ((unsigned int)(uint8_t)ip[2 * n] << 8) | (uint8_t)ip[2 * n + 1]; }
64
65size_t ip_format(char *dest, const ot_ip6 ip) {
66 static const char hexdigit[] = "0123456789abcdef";
67 char *d = dest;
68 int best_start = 0, best_len = 0, i = 0;
69
70 if (ip_is_v4mapped(ip))
71 return ip4_format(dest, (const uint8_t *)ip + sizeof(ip_v4mapped_prefix));
72
73 /* RFC 5952 4.2: the longest run of zero groups becomes "::", never a run
74 of one, and the first of two equal runs wins */
75 while (i < 8) {
76 int j = i;
77
78 if (group_at(ip, i)) {
79 ++i;
80 continue;
81 }
82 while (j < 8 && !group_at(ip, j))
83 ++j;
84 if (j - i > best_len) {
85 best_len = j - i;
86 best_start = i;
87 }
88 i = j;
89 }
90 if (best_len < 2)
91 best_len = 0;
92
93 for (i = 0; i < 8; ++i) {
94 unsigned int group;
95 int shift = 12;
96
97 if (best_len && i == best_start) {
98 *d++ = ':';
99 if (i + best_len == 8)
100 *d++ = ':'; /* nothing follows, so close the run */
101 i += best_len - 1;
102 continue;
103 }
104
105 if (i)
106 *d++ = ':';
107
108 group = group_at(ip, i);
109 while (shift && !(group >> shift))
110 shift -= 4; /* RFC 5952 4.1: no leading zeros */
111 for (;; shift -= 4) {
112 *d++ = hexdigit[(group >> shift) & 15];
113 if (!shift)
114 break;
115 }
116 }
117
118 return (size_t)(d - dest);
119}
120
121size_t ip_parse(const char *src, ot_ip6 ip) {
122 uint8_t prefix[16], suffix[16];
123 size_t prefixlen = 0, suffixlen = 0;
124 const char *s = src;
125 int have_gap = 0;
126 int need_colon = 0;
127
128 /* A plain IPv4 address is an address too, stored v4 mapped */
129 {
130 size_t consumed = ip4_scan(src, prefix);
131 if (consumed) {
132 memcpy(ip, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix));
133 memcpy(ip + sizeof(ip_v4mapped_prefix), prefix, 4);
134 return consumed;
135 }
136 }
137
138 for (;;) {
139 unsigned int value = 0;
140 int digits = 0, nibble;
141 uint8_t *into = have_gap ? suffix : prefix;
142 size_t *fill = have_gap ? &suffixlen : &prefixlen;
143
144 /* RFC 4291 2.2: one run of zero groups may be written "::" */
145 if (s[0] == ':' && s[1] == ':') {
146 if (have_gap)
147 return 0;
148 have_gap = 1;
149 need_colon = 0;
150 s += 2;
151 continue;
152 }
153
154 if (need_colon) {
155 if (*s != ':')
156 break;
157 ++s;
158 }
159
160 /* RFC 4291 2.2 form 3: the final two groups may be a dotted quad */
161 if (prefixlen + suffixlen + 4 <= 16) {
162 size_t consumed = ip4_scan(s, into + *fill);
163 if (consumed) {
164 *fill += 4;
165 s += consumed;
166 break;
167 }
168 }
169
170 while (digits < 4 && (nibble = hex_value(*s)) >= 0) {
171 value = value * 16 + (unsigned int)nibble;
172 ++digits;
173 ++s;
174 }
175 if (!digits) {
176 if (need_colon)
177 --s; /* leave the separator we ate for the caller */
178 break;
179 }
180
181 if (prefixlen + suffixlen + 2 > 16)
182 return 0;
183
184 into[(*fill)++] = (uint8_t)(value >> 8);
185 into[(*fill)++] = (uint8_t)value;
186 need_colon = 1;
187 }
188
189 if (!prefixlen && !suffixlen && !have_gap)
190 return 0;
191 if (!have_gap && prefixlen + suffixlen != 16)
192 return 0; /* without "::" every group has to be spelled out */
193
194 memset(ip, 0, 16);
195 memcpy(ip, prefix, prefixlen);
196 memcpy(ip + 16 - suffixlen, suffix, suffixlen);
197
198 return (size_t)(s - src);
199}
diff --git a/src/ot_ip.h b/src/ot_ip.h
new file mode 100644
index 0000000..533403e
--- /dev/null
+++ b/src/ot_ip.h
@@ -0,0 +1,31 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_IP_H__
5#define OT_IP_H__
6
7#include <stddef.h>
8#include <string.h>
9
10#include "trackerlogic.h"
11
12/* opentracker holds every address as sixteen bytes, writing IPv4 as the v4
13 mapped form of RFC 4291 section 2.5.5.2. */
14extern const char ip_v4mapped_prefix[12];
15
16static inline int ip_is_v4mapped(const void *ip) { return !memcmp(ip, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix)); }
17
18/* Read an address and return how many characters it took, or zero if src
19 does not start with one. A plain IPv4 address is accepted and stored in
20 its v4 mapped form.
21
22 The count lets the caller carry on where the address ended, which is how
23 "address:port" and "address/bits" are read. */
24size_t ip_parse(const char *src, ot_ip6 ip);
25
26/* Write an address and return how many characters it took. Nothing is
27 terminated, so a caller may keep appending. A v4 mapped address is written
28 as the plain dotted quad rather than "::ffff:1.2.3.4". */
29size_t ip_format(char *dest, const ot_ip6 ip);
30
31#endif
diff --git a/src/ot_livesync.c b/src/ot_livesync.c
new file mode 100644
index 0000000..1381b3b
--- /dev/null
+++ b/src/ot_livesync.c
@@ -0,0 +1,271 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <pthread.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sys/socket.h>
11#include <sys/types.h>
12#include <unistd.h>
13
14/* Opentracker */
15#include "ot_accesslist.h"
16#include "ot_ip.h"
17#include "ot_socket.h"
18#include "ot_livesync.h"
19#include "ot_mutex.h"
20#include "ot_stats.h"
21#include "trackerlogic.h"
22
23#ifdef WANT_SYNC_LIVE
24
25/* The multicast group, legacy opentrackers joined by default 224.0.23.5, so it
26 stays the default */
27static ot_ip6 g_group = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 224, 0, 23, 5};
28static uint16_t g_port = LIVESYNC_PORT;
29
30#define LIVESYNC_INCOMING_BUFFSIZE (256 * 256)
31
32#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480
33#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_hash) + OT_PEER_SIZE6)
34
35#define LIVESYNC_MAXDELAY 15 /* seconds */
36
37enum { OT_SYNC_PEER4, OT_SYNC_PEER6 };
38
39/* Forward declaration */
40static void *livesync_worker(void *args);
41
42/* For incoming packets */
43static int g_socket_in = -1;
44
45/* For outgoing packets */
46static int g_socket_out = -1;
47
48static pthread_mutex_t g_outbuf_mutex = PTHREAD_MUTEX_INITIALIZER;
49typedef struct {
50 uint8_t data[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
51 size_t fill;
52 ot_time next_packet_time;
53} sync_buffer;
54
55static sync_buffer g_v6_buf;
56static sync_buffer g_v4_buf;
57
58static pthread_t thread_id;
59static int thread_started;
60static _Atomic int thread_left;
61void livesync_init(void) {
62 uint32_t packet_type6 = htonl(OT_SYNC_PEER6);
63 uint32_t packet_type4 = htonl(OT_SYNC_PEER4);
64
65 if (g_socket_in == -1)
66 return;
67
68 /* Prepare outgoing peers buffer */
69 memcpy(g_v6_buf.data, &g_tracker_id, sizeof(g_tracker_id));
70 memcpy(g_v4_buf.data, &g_tracker_id, sizeof(g_tracker_id));
71
72 memcpy(g_v6_buf.data + sizeof(g_tracker_id), &packet_type6, sizeof(packet_type6));
73 memcpy(g_v4_buf.data + sizeof(g_tracker_id), &packet_type4, sizeof(packet_type4));
74
75 g_v6_buf.fill = sizeof(g_tracker_id) + sizeof(uint32_t);
76 g_v4_buf.fill = sizeof(g_tracker_id) + sizeof(uint32_t);
77
78 g_v6_buf.next_packet_time = time_future_seconds(LIVESYNC_MAXDELAY);
79 g_v4_buf.next_packet_time = time_future_seconds(LIVESYNC_MAXDELAY);
80
81 thread_started = !pthread_create(&thread_id, NULL, livesync_worker, NULL);
82}
83
84void livesync_deinit(void) {
85 if (thread_started) {
86 /* Repeats so it interrupts a read already under way */
87 while (!atomic_load(&thread_left)) {
88 pthread_kill(thread_id, OT_SIGNAL_WAKE);
89 usleep(1000);
90 }
91 pthread_join(thread_id, NULL);
92 thread_started = 0;
93 }
94
95 if (g_socket_in != -1)
96 close(g_socket_in);
97 if (g_socket_out != -1)
98 close(g_socket_out);
99}
100
101int livesync_set_group(const ot_ip6 group) {
102 /* v4 multicast is 224.0.0.0/4, and the socket layer has nothing else */
103 if (!ip_is_v4mapped(group) || (group[12] & 0xf0) != 0xe0)
104 return -1;
105 memcpy(g_group, group, sizeof(ot_ip6));
106 return 0;
107}
108
109void livesync_bind_mcast(ot_ip6 ip, uint16_t port) {
110 if (!ip_is_v4mapped(ip))
111 exerr("v6 mcast support not yet available.");
112
113 if (g_socket_in != -1)
114 exerr("Error: Livesync listen ip specified twice.");
115
116 g_port = port;
117
118 if ((g_socket_in = socket_mcast_join(g_group, ip, port)) == -1)
119 exerr("Error: Cant bind live sync incoming socket.");
120
121 if ((g_socket_out = socket_mcast_bind(ip, port, 0)) == -1)
122 exerr("Error: Cant bind live sync outgoing socket.");
123}
124
125/* Caller MUST hold g_outbuf_mutex. Returns with g_outbuf_mutex unlocked */
126static void livesync_issue_peersync(sync_buffer *buf) {
127 char mycopy[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
128 size_t fill = buf->fill;
129
130 /* The flush watermark keeps fill within the buffer */
131 if (fill > LIVESYNC_OUTGOING_BUFFSIZE_PEERS)
132 fill = LIVESYNC_OUTGOING_BUFFSIZE_PEERS;
133
134 memcpy(mycopy, buf->data, fill);
135 buf->fill = sizeof(g_tracker_id) + sizeof(uint32_t);
136 buf->next_packet_time = time_future_seconds(LIVESYNC_MAXDELAY);
137
138 /* From now this thread has a local copy of the buffer and
139 has modified the protected element */
140 pthread_mutex_unlock(&g_outbuf_mutex);
141
142 socket_mcast_send(g_socket_out, mycopy, fill, g_group, g_port);
143}
144
145static void livesync_handle_peersync(struct ot_workstruct *ws, size_t peer_size) {
146 size_t off = sizeof(g_tracker_id) + sizeof(uint32_t);
147
148 /* Prepare peer record for v4mapped expansion */
149 if (peer_size == OT_PEER_SIZE4)
150 memcpy(&ws->peer, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix));
151
152 /* Now basic sanity checks have been done on the live sync packet
153 We might add more testing and logging. */
154 while ((ssize_t)(off + sizeof(ot_hash) + peer_size) <= ws->request_size) {
155 char *peer_ip = ws->request + off + sizeof(ot_hash);
156 if (peer_size == OT_PEER_SIZE4)
157 memcpy(&ws->peer[0] + sizeof(ip_v4mapped_prefix), peer_ip, peer_size);
158 else
159 memcpy(&ws->peer, peer_ip, peer_size);
160 ws->hash = (ot_hash *)(ws->request + off);
161
162 if (!g_opentracker_running)
163 return;
164
165 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED)
166 remove_peer_from_torrent(FLAG_MCA, ws);
167 else
168 add_peer_to_torrent_and_return_peers(FLAG_MCA, ws, /* amount = */ 0);
169
170 off += sizeof(ot_hash) + peer_size;
171 }
172
173 stats_issue_event(ws, EVENT_SYNC, 0, (ws->request_size - sizeof(g_tracker_id) - sizeof(uint32_t)) / ((ssize_t)sizeof(ot_hash) + peer_size));
174}
175
176/* Tickle the live sync module from time to time, so no events get
177 stuck when there's not enough traffic to fill udp packets fast
178 enough */
179void livesync_ticker(void) {
180 if (g_socket_out == -1)
181 return;
182
183 /* livesync_issue_peersync sets g_next_packet_time */
184 pthread_mutex_lock(&g_outbuf_mutex);
185 if (time_is_past(g_v6_buf.next_packet_time) && g_v6_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t))
186 livesync_issue_peersync(&g_v6_buf);
187 else
188 pthread_mutex_unlock(&g_outbuf_mutex);
189
190 pthread_mutex_lock(&g_outbuf_mutex);
191 if (time_is_past(g_v4_buf.next_packet_time) && g_v4_buf.fill > sizeof(g_tracker_id) + sizeof(uint32_t))
192 livesync_issue_peersync(&g_v4_buf);
193 else
194 pthread_mutex_unlock(&g_outbuf_mutex);
195}
196
197/* Inform live sync about whats going on. */
198void livesync_tell(struct ot_workstruct *ws) {
199 size_t peer_size; /* initialized in next line */
200 ot_peer *peer_src;
201 sync_buffer *dest_buf;
202
203 if (g_socket_out == -1)
204 return;
205
206 peer_src = peer_from_peer6(&ws->peer, &peer_size);
207 dest_buf = peer_size == OT_PEER_SIZE6 ? &g_v6_buf : &g_v4_buf;
208
209 pthread_mutex_lock(&g_outbuf_mutex);
210
211 memcpy(dest_buf->data + dest_buf->fill, ws->hash, sizeof(ot_hash));
212 dest_buf->fill += sizeof(ot_hash);
213
214 memcpy(dest_buf->data + dest_buf->fill, peer_src, peer_size);
215 dest_buf->fill += peer_size;
216
217 if (dest_buf->fill >= LIVESYNC_OUTGOING_BUFFSIZE_PEERS - LIVESYNC_OUTGOING_WATERMARK_PEERS)
218 livesync_issue_peersync(dest_buf);
219 else
220 pthread_mutex_unlock(&g_outbuf_mutex);
221}
222
223static void *livesync_worker(void *args) {
224 struct ot_workstruct ws;
225 ot_ip6 in_ip;
226 uint16_t in_port;
227
228 (void)args;
229
230 if (workstruct_init(&ws, LIVESYNC_INCOMING_BUFFSIZE) == -1) {
231 fprintf(stderr, "Warning: live sync could not get its buffers and will not run.\n");
232 atomic_store(&thread_left, 1);
233 return NULL;
234 }
235 ws.request = ws.inbuf;
236
237 while (g_opentracker_running) {
238 uint32_t packet_type;
239
240 ws.request_size = socket_recv(g_socket_in, ws.inbuf, LIVESYNC_INCOMING_BUFFSIZE, in_ip, &in_port);
241
242 /* Expect at least tracker id and packet type */
243 if (ws.request_size <= (ssize_t)(sizeof(g_tracker_id) + sizeof(uint32_t)))
244 continue;
245 if (!accesslist_is_blessed(in_ip, OT_PERMISSION_MAY_LIVESYNC))
246 continue;
247 if (!memcmp(ws.inbuf, &g_tracker_id, sizeof(g_tracker_id))) {
248 /* TODO: log packet coming from ourselves */
249 continue;
250 }
251
252 memcpy(&packet_type, ws.inbuf + sizeof(g_tracker_id), sizeof(packet_type));
253
254 switch (ntohl(packet_type)) {
255 case OT_SYNC_PEER6:
256 livesync_handle_peersync(&ws, OT_PEER_SIZE6);
257 break;
258 case OT_SYNC_PEER4:
259 livesync_handle_peersync(&ws, OT_PEER_SIZE4);
260 break;
261 default:
262 break;
263 }
264 }
265
266 workstruct_deinit(&ws);
267 atomic_store(&thread_left, 1);
268 return NULL;
269}
270
271#endif
diff --git a/ot_livesync.h b/src/ot_livesync.h
index d7490e5..cf3c64c 100644
--- a/ot_livesync.h
+++ b/src/ot_livesync.h
@@ -1,16 +1,14 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org> 1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. 2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4 $id$ */
5 3
6#ifndef OT_LIVESYNC_H__ 4#ifndef OT_LIVESYNC_H__
7#define OT_LIVESYNC_H__ 5#define OT_LIVESYNC_H__
8 6
9#include "io.h"
10#include "trackerlogic.h" 7#include "trackerlogic.h"
11 8
12/* 9/*
13 Syncing is done as udp packets in the multicast domain 224.0.42.5 port 9696 10 Syncing is done as udp packets in the multicast group 224.0.23.5, on the
11 port livesync.cluster.listen names, 9696 by default
14 12
15 Each tracker should join the multicast group and send its live sync packets 13 Each tracker should join the multicast group and send its live sync packets
16 to that group, using a ttl of 1 14 to that group, using a ttl of 1
@@ -28,35 +26,45 @@
28 Each tracker instance accumulates announce requests until its buffer is 26 Each tracker instance accumulates announce requests until its buffer is
29 full or a timeout is reached. Then it broadcasts its live sync packer: 27 full or a timeout is reached. Then it broadcasts its live sync packer:
30 28
31 packet type SYNC_LIVE 29 packet type SYNC_LIVE4
32 [ 0x0008 0x14 info_hash 30 [ 0x0008 0x14 info_hash
33 0x001c 0x04 peer's ipv4 address 31 0x001c 0x04 peer's ipv4 address
34 0x0020 0x02 peer's port 32 0x0020 0x02 peer's port
35 0x0024 0x02 peer flags v1 ( SEEDING = 0x80, COMPLETE = 0x40, STOPPED = 0x20 ) 33 0x0024 0x02 peer flags v1 ( SEEDING = 0x80, COMPLETE = 0x40, STOPPED = 0x20 )
36 ]* 34 ]*
37 35
36 packet type SYNC_LIVE6
37 [ 0x0008 0x14 info_hash
38 0x001c 0x10 peer's ipv6 address
39 0x002c 0x02 peer's port
40 0x002e 0x02 peer flags v1 ( SEEDING = 0x80, COMPLETE = 0x40, STOPPED = 0x20 )
41 ]*
38*/ 42*/
39 43
40#ifdef WANT_SYNC_LIVE 44#ifdef WANT_SYNC_LIVE
41 45
42#define LIVESYNC_PORT 9696 46#define LIVESYNC_PORT 9696
43 47
44void livesync_init(); 48void livesync_init(void);
45void livesync_deinit(); 49void livesync_deinit(void);
50
51/* The group to join and to send to, (defaults to 224.0.23.5).
52 Returns -1 if group is not a v4 multicast address. */
53int livesync_set_group(const ot_ip6 group);
46 54
47/* Join multicast group for listening and create sending socket */ 55/* Join multicast group for listening and create sending socket */
48void livesync_bind_mcast( char *ip, uint16_t port ); 56void livesync_bind_mcast(ot_ip6 ip, uint16_t port);
49 57
50/* Inform live sync about whats going on. */ 58/* Inform live sync about whats going on. */
51void livesync_tell( struct ot_workstruct *ws ); 59void livesync_tell(struct ot_workstruct *ws);
52 60
53/* Tickle the live sync module from time to time, so no events get 61/* Tickle the live sync module from time to time, so no events get
54 stuck when there's not enough traffic to fill udp packets fast 62 stuck when there's not enough traffic to fill udp packets fast
55 enough */ 63 enough */
56void livesync_ticker( ); 64void livesync_ticker(void);
57 65
58/* Handle an incoming live sync packet */ 66/* Handle an incoming live sync packet */
59void handle_livesync( const int64 sock ); 67void handle_livesync(const int64_t sock);
60 68
61#else 69#else
62 70
diff --git a/src/ot_mutex.c b/src/ot_mutex.c
new file mode 100644
index 0000000..884b74c
--- /dev/null
+++ b/src/ot_mutex.c
@@ -0,0 +1,70 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <pthread.h>
7#include <stdatomic.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <unistd.h>
11#include <string.h>
12#include <sys/uio.h>
13
14
15/* Opentracker */
16#include "ot_iovec.h"
17#include "ot_mutex.h"
18#include "ot_stats.h"
19#include "trackerlogic.h"
20
21/* #define MTX_DBG( STRING ) fprintf( stderr, STRING ) */
22#define MTX_DBG(STRING)
23
24/* Our global all torrents list */
25static ot_vector all_torrents[OT_BUCKET_COUNT];
26static pthread_mutex_t bucket_mutex[OT_BUCKET_COUNT];
27/* Every bucket's unlock adjusts this, and a bucket lock only keeps other
28 threads out of that one bucket, so the counter needs its own protection */
29static _Atomic size_t g_torrent_count;
30
31ot_vector *mutex_bucket_lock(int bucket) {
32 pthread_mutex_lock(bucket_mutex + bucket);
33 return all_torrents + bucket;
34}
35
36/* Torrents are spread over buckets by the first four bytes of their info_hash,
37 which may sit at any alignment, hence the memcpy */
38static int bucket_from_hash(ot_hash const hash) {
39 uint32_t bucket;
40 memcpy(&bucket, hash, sizeof(bucket));
41 return ntohl(bucket) >> OT_BUCKET_COUNT_SHIFT;
42}
43
44ot_vector *mutex_bucket_lock_by_hash(ot_hash const hash) { return mutex_bucket_lock(bucket_from_hash(hash)); }
45
46void mutex_bucket_unlock(int bucket, int delta_torrentcount) {
47 pthread_mutex_unlock(bucket_mutex + bucket);
48 if (delta_torrentcount)
49 atomic_fetch_add_explicit(&g_torrent_count, (size_t)delta_torrentcount, memory_order_relaxed);
50}
51
52void mutex_bucket_unlock_by_hash(ot_hash const hash, int delta_torrentcount) {
53 mutex_bucket_unlock(bucket_from_hash(hash), delta_torrentcount);
54}
55
56size_t mutex_get_torrent_count(void) { return atomic_load_explicit(&g_torrent_count, memory_order_relaxed); }
57
58void mutex_init(void) {
59 size_t i;
60 for (i = 0; i < OT_BUCKET_COUNT; ++i)
61 pthread_mutex_init(bucket_mutex + i, NULL);
62 memset(all_torrents, 0, sizeof(all_torrents));
63}
64
65void mutex_deinit(void) {
66 size_t i;
67 for (i = 0; i < OT_BUCKET_COUNT; ++i)
68 pthread_mutex_destroy(bucket_mutex + i);
69 memset(all_torrents, 0, sizeof(all_torrents));
70}
diff --git a/src/ot_mutex.h b/src/ot_mutex.h
new file mode 100644
index 0000000..d7ded92
--- /dev/null
+++ b/src/ot_mutex.h
@@ -0,0 +1,21 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_MUTEX_H__
5#define OT_MUTEX_H__
6
7#include <sys/uio.h>
8#include "trackerlogic.h"
9
10void mutex_init(void);
11void mutex_deinit(void);
12
13ot_vector *mutex_bucket_lock(int bucket);
14ot_vector *mutex_bucket_lock_by_hash(ot_hash const hash);
15
16void mutex_bucket_unlock(int bucket, int delta_torrentcount);
17void mutex_bucket_unlock_by_hash(ot_hash const hash, int delta_torrentcount);
18
19size_t mutex_get_torrent_count(void);
20
21#endif
diff --git a/src/ot_random.c b/src/ot_random.c
new file mode 100644
index 0000000..43f91bb
--- /dev/null
+++ b/src/ot_random.c
@@ -0,0 +1,51 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <stdlib.h>
7
8/* Opentracker */
9#include "ot_random.h"
10
11#ifdef WANT_INSECURE_RANDOM_FALLBACK
12
13#warning WANT_INSECURE_RANDOM_FALLBACK builds without arc4random. UDP connection ids become predictable and announces can be forged. Do not ship this.
14
15#include <time.h>
16
17void random_init(void) {
18#ifdef WANT_DEV_RANDOM
19 srandomdev();
20#else
21 srandom(time(NULL));
22#endif
23}
24
25/* random() yields 31 bits, so one draw can never set the top bit. Combine
26 two of them rather than hand out a value that is quietly half as wide as
27 its type claims. */
28uint32_t random_uint32(void) { return ((uint32_t)random() << 16) ^ (uint32_t)random(); }
29
30void random_bytes(void *buf, size_t len) {
31 uint8_t *out = buf;
32 /* random() leaves the top bit clear and its lowest bits are the weakest,
33 so take a byte from the middle of each draw */
34 while (len--)
35 *out++ = (uint8_t)(random() >> 8);
36}
37
38#else
39
40#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__DragonFly__) && !defined(__APPLE__) && \
41 !(defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 36)))
42#include <bsd/stdlib.h>
43#endif
44
45void random_init(void) {}
46
47uint32_t random_uint32(void) { return arc4random(); }
48
49void random_bytes(void *buf, size_t len) { arc4random_buf(buf, len); }
50
51#endif
diff --git a/src/ot_random.h b/src/ot_random.h
new file mode 100644
index 0000000..c2d0387
--- /dev/null
+++ b/src/ot_random.h
@@ -0,0 +1,17 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_RANDOM_H__
5#define OT_RANDOM_H__
6
7#include <stddef.h>
8#include <stdint.h>
9
10/* Seed whatever generator the build settled on. A no-op when backed by
11 arc4random, which seeds itself from the kernel. */
12void random_init(void);
13
14uint32_t random_uint32(void);
15void random_bytes(void *buf, size_t len);
16
17#endif
diff --git a/ot_rijndael.c b/src/ot_rijndael.c
index f468e2f..3f36bde 100644
--- a/ot_rijndael.c
+++ b/src/ot_rijndael.c
@@ -486,5 +486,3 @@ void rijndaelEncrypt128(const uint32_t rk[44], const uint8_t pt[16], uint8_t ct[
486 rk[43]; 486 rk[43];
487 PUTU32(ct + 12, s3); 487 PUTU32(ct + 12, s3);
488} 488}
489
490const char *g_version_rijndael_c = "$Source$: $Revision$\n";
diff --git a/ot_rijndael.h b/src/ot_rijndael.h
index 54725dc..1235215 100644
--- a/ot_rijndael.h
+++ b/src/ot_rijndael.h
@@ -5,9 +5,7 @@
5 5
6 http://www.cs.ucdavis.edu/~rogaway/ocb/ocb-ref/rijndael-alg-fst.c 6 http://www.cs.ucdavis.edu/~rogaway/ocb/ocb-ref/rijndael-alg-fst.c
7 7
8 and modified to work with 128 bits (this is 10 rounds) only. 8 and modified to work with 128 bits (this is 10 rounds) only. */
9
10 $id$ */
11 9
12#ifndef OT_RIJNDAEL_H__ 10#ifndef OT_RIJNDAEL_H__
13#define OT_RIJNDAEL_H__ 11#define OT_RIJNDAEL_H__
diff --git a/src/ot_scan.c b/src/ot_scan.c
new file mode 100644
index 0000000..3b8e87c
--- /dev/null
+++ b/src/ot_scan.c
@@ -0,0 +1,65 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <stdint.h>
7#include <stdlib.h>
8
9/* Opentracker */
10#include "ot_scan.h"
11
12size_t scan_uint(const char *src, uint64_t *dest, uint64_t max) {
13 unsigned long long value;
14 char *end;
15
16 if (*src < '0' || *src > '9')
17 return 0;
18
19 errno = 0;
20 value = strtoull(src, &end, 10);
21
22 if (errno == ERANGE || value > (unsigned long long)max)
23 return 0;
24
25 *dest = (uint64_t)value;
26 return (size_t)(end - src);
27}
28
29size_t scan_uint_bencode(const char *src, uint64_t *dest, uint64_t max) {
30 uint64_t value;
31 size_t consumed = scan_uint(src, &value, max);
32
33 /* bencode writes no leading zeros, so anything longer than a single digit
34 must not begin with one. */
35 if (consumed > 1 && *src == '0')
36 return 0;
37
38 if (consumed)
39 *dest = value;
40
41 return consumed;
42}
43
44int scan_int(const char *src, size_t len, int64_t *dest) {
45 int64_t value = 0;
46 int negate = 0;
47
48 if (len && *src == '-')
49 --len, ++src, negate = 1;
50 if (!len)
51 return -1;
52
53 while (len--) {
54 if (*src < '0' || *src > '9')
55 return -1;
56 /* A twenty character field of nines does not fit, and silently wrapping
57 would magically heal a nonsense announce */
58 if (value > (INT64_MAX - (*src - '0')) / 10)
59 return -1;
60 value = 10 * value + (*src++ - '0');
61 }
62
63 *dest = negate ? -value : value;
64 return 0;
65}
diff --git a/src/ot_scan.h b/src/ot_scan.h
new file mode 100644
index 0000000..a79ec13
--- /dev/null
+++ b/src/ot_scan.h
@@ -0,0 +1,25 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_SCAN_H__
5#define OT_SCAN_H__
6
7#include <stddef.h>
8#include <stddef.h>
9#include <stdint.h>
10
11/* Read an unsigned decimal number from src into dest and return how many
12 characters were consumed. Returns zero and leaves dest untouched when src
13 does not begin with a digit, or when the value would exceed max. */
14size_t scan_uint(const char *src, uint64_t *dest, uint64_t max);
15
16/* As scan_uint, but following the bencode integer grammar, which permits a
17 leading zero on zero alone. */
18size_t scan_uint_bencode(const char *src, uint64_t *dest, uint64_t max);
19
20/* Read a signed decimal number that has to take up exactly len characters,
21 which is how a value lifted out of a query string arrives. Returns 0, or
22 -1 leaving dest untouched. */
23int scan_int(const char *src, size_t len, int64_t *dest);
24
25#endif
diff --git a/src/ot_socket.c b/src/ot_socket.c
new file mode 100644
index 0000000..8b17080
--- /dev/null
+++ b/src/ot_socket.c
@@ -0,0 +1,318 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#define _GNU_SOURCE /* accept4 on glibc */
6#include <errno.h>
7#include <fcntl.h>
8#include <netinet/in.h>
9#include <netinet/tcp.h>
10#include <string.h>
11#include <sys/socket.h>
12#include <unistd.h>
13
14/* Opentracker */
15#include "ot_ip.h"
16#include "ot_socket.h"
17
18static void sockaddr_from_ip(struct sockaddr_in6 *sa, const ot_ip6 ip, uint16_t port) {
19 memset(sa, 0, sizeof(*sa));
20 sa->sin6_family = AF_INET6;
21 sa->sin6_port = htons(port);
22 memcpy(&sa->sin6_addr, ip, sizeof(ot_ip6));
23}
24
25/* Linux reports an IPv4 peer on a dual stack socket as a v4 mapped
26 sockaddr_in6, the BSDs and macOS hand back a plain sockaddr_in instead, so
27 both forms have to be read. */
28static void ip_from_sockaddr(ot_ip6 ip, uint16_t *port, const struct sockaddr_storage *ss) {
29 if (ss->ss_family == AF_INET) {
30 const struct sockaddr_in *sa = (const struct sockaddr_in *)ss;
31
32 memcpy(ip, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix));
33 memcpy(ip + sizeof(ip_v4mapped_prefix), &sa->sin_addr, 4);
34 *port = ntohs(sa->sin_port);
35 } else {
36 const struct sockaddr_in6 *sa = (const struct sockaddr_in6 *)ss;
37
38 memcpy(ip, &sa->sin6_addr, sizeof(ot_ip6));
39 *port = ntohs(sa->sin6_port);
40 }
41}
42
43int socket_set_blocking(int s, int blocking) {
44 int flags = fcntl(s, F_GETFL, 0);
45
46 if (flags == -1)
47 return -1;
48 return fcntl(s, F_SETFL, blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK));
49}
50
51static int set_nonblocking(int s) { return socket_set_blocking(s, 0); }
52
53/* Close without letting the failure we are about to report be overwritten */
54static int close_and_fail(int s) {
55 int saved = errno;
56 close(s);
57 errno = saved;
58 return -1;
59}
60
61static int socket_v6(int type) {
62 int s = socket(PF_INET6, type, 0);
63 int zero = 0;
64
65 if (s == -1)
66 return -1;
67
68 /* A tracker that answered only one family would be half a tracker */
69 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1)
70 return close_and_fail(s);
71
72 if (set_nonblocking(s) == -1)
73 return close_and_fail(s);
74
75 return s;
76}
77
78/* SO_REUSEPORT means three different things. Linux spreads datagrams over
79 the group. FreeBSD permits the bind and spreads nothing, which is what
80 SO_REUSEPORT_LB was added for. Darwin hands every datagram to whichever
81 socket bound last, so a group there starves all but one reader. */
82#if defined(SO_REUSEPORT_LB)
83#define OT_BALANCE_OPTION SO_REUSEPORT_LB
84#elif defined(SO_REUSEPORT) && !defined(__APPLE__)
85#define OT_BALANCE_OPTION SO_REUSEPORT
86#endif
87
88int socket_can_balance(void) {
89#ifdef OT_BALANCE_OPTION
90 return 1;
91#else
92 return 0;
93#endif
94}
95
96/* The only place in the tree that needs to know what a kernel calls this */
97static void socket_set_sharing(int s, socket_sharing sharing) {
98 int one = 1;
99
100 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
101#ifdef OT_BALANCE_OPTION
102 if (sharing == SOCKET_BALANCED) {
103 setsockopt(s, SOL_SOCKET, OT_BALANCE_OPTION, &one, sizeof(one));
104 return;
105 }
106#endif
107#ifdef SO_REUSEPORT
108 if (sharing != SOCKET_EXCLUSIVE)
109 setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
110#endif
111}
112
113static int socket_bind_v6(int s, const ot_ip6 ip, uint16_t port, socket_sharing sharing) {
114 struct sockaddr_in6 sa;
115
116 socket_set_sharing(s, sharing);
117
118 sockaddr_from_ip(&sa, ip, port);
119 return bind(s, (struct sockaddr *)&sa, sizeof(sa));
120}
121
122/* Defer the listening socket reporting it to be ready to accept until enough
123 sensible data is available for an accept+read pair. Where available. */
124int socket_defer_accept(int s) {
125#if defined(TCP_DEFER_ACCEPT)
126 int patience = OT_CLIENT_TIMEOUT;
127
128 return setsockopt(s, IPPROTO_TCP, TCP_DEFER_ACCEPT, &patience, sizeof(patience));
129#elif defined(SO_ACCEPTFILTER)
130 struct accept_filter_arg filter;
131 const char name[sizeof(filter.af_name)] = "dataready";
132
133 memset(&filter, 0, sizeof(filter));
134 memcpy(filter.af_name, name, sizeof(name));
135 return setsockopt(s, SOL_SOCKET, SO_ACCEPTFILTER, &filter, sizeof(filter));
136#else
137 (void)s;
138 return -1;
139#endif
140}
141
142int socket_tcp_listen(const ot_ip6 ip, uint16_t port, socket_sharing sharing) {
143 int s = socket_v6(SOCK_STREAM);
144
145 if (s == -1)
146 return -1;
147 if (socket_bind_v6(s, ip, port, sharing) == -1 || listen(s, SOMAXCONN) == -1)
148 return close_and_fail(s);
149
150 return s;
151}
152
153int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing) {
154 int s = socket_v6(SOCK_DGRAM);
155
156 if (s == -1)
157 return -1;
158 if (socket_bind_v6(s, ip, port, sharing) == -1)
159 return close_and_fail(s);
160
161 return s;
162}
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
178int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport) {
179 struct sockaddr_in6 sa;
180 int s = socket_v6(SOCK_STREAM);
181
182 if (s == -1)
183 return -1;
184 if (socket_bind_v6(s, srcip, srcport, SOCKET_EXCLUSIVE) == -1)
185 return close_and_fail(s);
186
187 sockaddr_from_ip(&sa, dstip, dstport);
188 if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) == -1 && errno != EINPROGRESS && errno != EWOULDBLOCK)
189 return close_and_fail(s);
190
191 return s;
192}
193
194int socket_is_connected(int s) {
195 int error = 0;
196 socklen_t len = sizeof(error);
197
198 if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &len) == -1)
199 return 0;
200 if (error) {
201 errno = error;
202 return 0;
203 }
204 return 1;
205}
206
207/* Linux hands over a blocking socket whatever the listening socket was, the
208 BSDs and macOS inherit the listener's flags, so the accepted socket has to
209 be told either way. accept4 carries the flag itself, which saves the two
210 fcntl calls it otherwise takes. Darwin has neither accept4 nor the flag. */
211int socket_accept(int s, ot_ip6 ip, uint16_t *port) {
212 struct sockaddr_storage ss;
213 socklen_t len = sizeof(ss);
214 int fd;
215
216 memset(&ss, 0, sizeof(ss));
217#ifdef SOCK_NONBLOCK
218 if ((fd = accept4(s, (struct sockaddr *)&ss, &len, SOCK_NONBLOCK)) == -1)
219 return -1;
220#else
221 if ((fd = accept(s, (struct sockaddr *)&ss, &len)) == -1)
222 return -1;
223 if (set_nonblocking(fd) == -1)
224 return close_and_fail(fd);
225#endif
226
227 ip_from_sockaddr(ip, port, &ss);
228 return fd;
229}
230
231ssize_t socket_recv(int s, void *buf, size_t len, ot_ip6 ip, uint16_t *port) {
232 struct sockaddr_storage ss;
233 socklen_t sslen = sizeof(ss);
234 ssize_t received;
235
236 memset(&ss, 0, sizeof(ss));
237 received = recvfrom(s, buf, len, 0, (struct sockaddr *)&ss, &sslen);
238 if (received == -1)
239 return -1;
240
241 ip_from_sockaddr(ip, port, &ss);
242 return received;
243}
244
245ssize_t socket_send(int s, const void *buf, size_t len, const ot_ip6 ip, uint16_t port) {
246 struct sockaddr_in6 sa;
247
248 sockaddr_from_ip(&sa, ip, port);
249 return sendto(s, buf, len, 0, (struct sockaddr *)&sa, sizeof(sa));
250}
251
252#ifdef WANT_SYNC_LIVE
253static void sockaddr4_from_ip(struct sockaddr_in *sa, const ot_ip6 ip, uint16_t port) {
254 memset(sa, 0, sizeof(*sa));
255 sa->sin_family = AF_INET;
256 sa->sin_port = htons(port);
257 memcpy(&sa->sin_addr, ip + sizeof(ip_v4mapped_prefix), 4);
258}
259
260/* A multicast group is meant to have several listeners, so these are always
261 shared */
262static int socket_v4_bind(const ot_ip6 ip, uint16_t port) {
263 struct sockaddr_in sa;
264 int s;
265
266 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
267 return -1;
268
269 socket_set_sharing(s, SOCKET_SHARED);
270
271 sockaddr4_from_ip(&sa, ip, port);
272 if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
273 return close_and_fail(s);
274
275 return s;
276}
277
278int socket_mcast_join(const ot_ip6 group, const ot_ip6 interface, uint16_t port) {
279 struct ip_mreq mreq;
280 int s;
281
282 if ((s = socket_v4_bind(group, port)) == -1)
283 return -1;
284
285 memset(&mreq, 0, sizeof(mreq));
286 memcpy(&mreq.imr_multiaddr, group + sizeof(ip_v4mapped_prefix), 4);
287 memcpy(&mreq.imr_interface, interface + sizeof(ip_v4mapped_prefix), 4);
288 if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) == -1)
289 return close_and_fail(s);
290
291 return s;
292}
293
294int socket_mcast_bind(const ot_ip6 interface, uint16_t port, int loopback) {
295 /* The BSDs and macOS want a byte for the IPv4 multicast options, Linux
296 accepts either that or an int. */
297 unsigned char ttl = 1, loop = (unsigned char)(loopback != 0);
298 int s = socket_v4_bind(interface, port);
299
300 if (s == -1)
301 return -1;
302 if (set_nonblocking(s) == -1)
303 return close_and_fail(s);
304
305 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1 ||
306 setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) == -1)
307 return close_and_fail(s);
308
309 return s;
310}
311
312ssize_t socket_mcast_send(int s, const void *buf, size_t len, const ot_ip6 group, uint16_t port) {
313 struct sockaddr_in sa;
314
315 sockaddr4_from_ip(&sa, group, port);
316 return sendto(s, buf, len, 0, (struct sockaddr *)&sa, sizeof(sa));
317}
318#endif
diff --git a/src/ot_socket.h b/src/ot_socket.h
new file mode 100644
index 0000000..33446e4
--- /dev/null
+++ b/src/ot_socket.h
@@ -0,0 +1,58 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_SOCKET_H__
5#define OT_SOCKET_H__
6
7#include <stdint.h>
8#include <sys/types.h>
9
10#include "trackerlogic.h"
11
12/* Every socket opentracker opens is an AF_INET6 socket with IPV6_V6ONLY
13 cleared, so one descriptor serves both families and an IPv4 peer arrives
14 as the v4 mapped address */
15
16/* How an address may be shared with other sockets. Which socket option says
17 so differs between kernels, which is socket_set_sharing's business.
18
19 SHARED lets another socket bind the same address. BALANCED asks the kernel
20 to spread arriving datagrams over the sockets that did, which is a
21 different thing and not everywhere available: ask socket_can_balance
22 before binding a group that depends on it. */
23typedef enum { SOCKET_EXCLUSIVE, SOCKET_SHARED, SOCKET_BALANCED } socket_sharing;
24
25/* Whether this kernel spreads datagrams over a group of sockets bound to one
26 address. Where it does not, binding a group is worse than one socket with
27 several readers, so the caller wants to know first. */
28int socket_can_balance(void);
29
30/* Create, bind and, for TCP, listen. The returned socket is non blocking
31 Returns -1 on failure with errno set */
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);
34
35int socket_udp_is_taken(const ot_ip6 ip, uint16_t port);
36
37int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport);
38int socket_is_connected(int s);
39int socket_accept(int s, ot_ip6 ip, uint16_t *port);
40int socket_set_blocking(int s, int blocking);
41int socket_defer_accept(int s);
42
43ssize_t socket_recv(int s, void *buf, size_t len, ot_ip6 ip, uint16_t *port);
44ssize_t socket_send(int s, const void *buf, size_t len, const ot_ip6 ip, uint16_t port);
45
46#ifdef WANT_SYNC_LIVE
47/*
48 socket_mcast_join takes the wildcard address and names the interface in the
49 join, and hands back a blocking socket, since the thread that reads it does
50 nothing else. socket_mcast_bind hands back a non blocking one, because the
51 thread that sends from it is also serving clients. Incoming datagrams are
52 read with socket_recv */
53int socket_mcast_join(const ot_ip6 group, const ot_ip6 interface, uint16_t port);
54int socket_mcast_bind(const ot_ip6 interface, uint16_t port, int loopback);
55ssize_t socket_mcast_send(int s, const void *buf, size_t len, const ot_ip6 group, uint16_t port);
56#endif
57
58#endif
diff --git a/src/ot_stats.c b/src/ot_stats.c
new file mode 100644
index 0000000..95f3cff
--- /dev/null
+++ b/src/ot_stats.c
@@ -0,0 +1,826 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sys/types.h>
11#include <sys/uio.h>
12#include <unistd.h>
13#ifdef WANT_SYSLOGS
14#include <syslog.h>
15#endif
16
17/* Opentracker */
18#include "ot_accesslist.h"
19#include "ot_event.h"
20#include "ot_hex.h"
21#include "ot_iovec.h"
22#include "ot_ip.h"
23#include "ot_mutex.h"
24#include "ot_workqueue.h"
25#include "ot_fmt.h"
26#include "ot_stats.h"
27#include "trackerlogic.h"
28
29#ifndef NO_FULLSCRAPE_LOGGING
30#define LOG_TO_STDERR(...) fprintf(stderr, __VA_ARGS__)
31#else
32#define LOG_TO_STDERR(...)
33#endif
34
35/* Forward declaration */
36static void stats_make(size_t *iovec_entries, struct iovec **iovector, ot_tasktype mode);
37#define OT_STATS_TMPSIZE 8192
38
39/* Each serving thread keeps its own statistics tally. The list is linked
40 through intrusive next pointers within the workstruct.
41
42 Registration happens once per thread and the adding up once per statistics
43 request, so this lock is never on anybody's hot path. */
44static struct ot_workstruct *g_counter_contexts;
45static ot_counter g_retired[OT_COUNTER_COUNT];
46static pthread_mutex_t g_counter_mutex = PTHREAD_MUTEX_INITIALIZER;
47
48void stats_counters_register(struct ot_workstruct *ws) {
49 pthread_mutex_lock(&g_counter_mutex);
50 ws->counters_next = g_counter_contexts;
51 g_counter_contexts = ws;
52 pthread_mutex_unlock(&g_counter_mutex);
53}
54
55void stats_counters_retire(struct ot_workstruct *ws) {
56 struct ot_workstruct **link;
57 size_t i;
58
59 pthread_mutex_lock(&g_counter_mutex);
60 for (link = &g_counter_contexts; *link; link = &(*link)->counters_next)
61 if (*link == ws) {
62 *link = ws->counters_next;
63 break;
64 }
65
66 /* When retiring a worker thread, collect the counter tally in the global */
67 for (i = 0; i < OT_COUNTER_COUNT; ++i)
68 atomic_fetch_add_explicit(g_retired + i, atomic_load_explicit(ws->counters + i, memory_order_relaxed), memory_order_relaxed);
69 pthread_mutex_unlock(&g_counter_mutex);
70}
71
72/* What every thread has counted so far, added together */
73static void counters_total(unsigned long long *total) {
74 struct ot_workstruct *ws;
75 size_t i;
76
77 pthread_mutex_lock(&g_counter_mutex);
78 for (i = 0; i < OT_COUNTER_COUNT; ++i)
79 total[i] = atomic_load_explicit(g_retired + i, memory_order_relaxed);
80 for (ws = g_counter_contexts; ws; ws = ws->counters_next)
81 for (i = 0; i < OT_COUNTER_COUNT; ++i)
82 total[i] += atomic_load_explicit(ws->counters + i, memory_order_relaxed);
83 pthread_mutex_unlock(&g_counter_mutex);
84}
85
86#define COUNT(index, by) atomic_fetch_add_explicit(ws->counters + (index), (unsigned long)(by), memory_order_relaxed)
87
88static const char *ot_failed_request_names[] = {
89 "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest",
90 "402 Payment Required", "403 Access Denied", "404 Not found", "500 Internal Server Error"};
91
92static time_t ot_start_time;
93
94#ifdef WANT_SPOT_WOODPECKER
95#define STATS_NETWORK_NODE_BITWIDTH 4
96#define STATS_NETWORK_NODE_COUNT (1 << STATS_NETWORK_NODE_BITWIDTH)
97
98#define __BYTE(P, D) (((uint8_t *)(P))[(D) / 8])
99#define __MSK (STATS_NETWORK_NODE_COUNT - 1)
100#define __SHFT(D) (((D) ^ STATS_NETWORK_NODE_BITWIDTH) & STATS_NETWORK_NODE_BITWIDTH)
101
102#define __LDR(P, D) ((__BYTE((P), (D)) >> __SHFT((D))) & __MSK)
103#define __STR(P, D, V) __BYTE((P), (D)) = (__BYTE((P), (D)) & ~(__MSK << __SHFT((D)))) | ((V) << __SHFT((D)))
104
105#if 0
106// XXX
107#define STATS_NETWORK_NODE_MAXDEPTH (68 - STATS_NETWORK_NODE_BITWIDTH)
108#define STATS_NETWORK_NODE_LIMIT (48 - STATS_NETWORK_NODE_BITWIDTH)
109#endif
110#define STATS_NETWORK_NODE_MAXDEPTH (28 - STATS_NETWORK_NODE_BITWIDTH)
111#define STATS_NETWORK_NODE_LIMIT (24 - STATS_NETWORK_NODE_BITWIDTH)
112
113typedef union stats_network_node stats_network_node;
114union stats_network_node {
115 size_t counters[STATS_NETWORK_NODE_COUNT];
116 stats_network_node *children[STATS_NETWORK_NODE_COUNT];
117};
118
119static int stat_increase_network_count(stats_network_node **pnode, int depth, uintptr_t ip) {
120 int foo = __LDR(ip, depth);
121 stats_network_node *node;
122
123 if (!*pnode) {
124 *pnode = malloc(sizeof(stats_network_node));
125 if (!*pnode)
126 return -1;
127 memset(*pnode, 0, sizeof(stats_network_node));
128 }
129 node = *pnode;
130
131 if (depth < STATS_NETWORK_NODE_MAXDEPTH)
132 return stat_increase_network_count(node->children + foo, depth + STATS_NETWORK_NODE_BITWIDTH, ip);
133
134 node->counters[foo]++;
135 return 0;
136}
137
138static int stats_shift_down_network_count(stats_network_node **node, int depth, int shift) {
139 size_t i, rest = 0;
140
141 if (!*node)
142 return 0;
143
144 for (i = 0; i < STATS_NETWORK_NODE_COUNT; ++i)
145 if (depth < STATS_NETWORK_NODE_MAXDEPTH)
146 rest += stats_shift_down_network_count((*node)->children + i, depth + STATS_NETWORK_NODE_BITWIDTH, shift);
147 else
148 rest += (*node)->counters[i] >>= shift;
149
150 if (!rest) {
151 free(*node);
152 *node = NULL;
153 }
154
155 return rest;
156}
157
158static size_t stats_get_highscore_networks(stats_network_node *node, int depth, ot_ip6 node_value, size_t *scores, ot_ip6 *networks, int network_count,
159 int limit) {
160 size_t i, score = 0;
161
162 if (!node)
163 return 0;
164
165 if (depth < limit) {
166 for (i = 0; i < STATS_NETWORK_NODE_COUNT; ++i)
167 if (node->children[i]) {
168 __STR(node_value, depth, i);
169 score += stats_get_highscore_networks(node->children[i], depth + STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit);
170 }
171 return score;
172 }
173
174 if (depth > limit && depth < STATS_NETWORK_NODE_MAXDEPTH) {
175 for (i = 0; i < STATS_NETWORK_NODE_COUNT; ++i)
176 if (node->children[i])
177 score += stats_get_highscore_networks(node->children[i], depth + STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit);
178 return score;
179 }
180
181 if (depth > limit && depth == STATS_NETWORK_NODE_MAXDEPTH) {
182 for (i = 0; i < STATS_NETWORK_NODE_COUNT; ++i)
183 score += node->counters[i];
184 return score;
185 }
186
187 /* if( depth == limit ) */
188 for (i = 0; i < STATS_NETWORK_NODE_COUNT; ++i) {
189 int j = 1;
190 size_t node_score;
191
192 if (depth == STATS_NETWORK_NODE_MAXDEPTH)
193 node_score = node->counters[i];
194 else
195 node_score = stats_get_highscore_networks(node->children[i], depth + STATS_NETWORK_NODE_BITWIDTH, node_value, scores, networks, network_count, limit);
196
197 score += node_score;
198
199 if (node_score <= scores[0])
200 continue;
201
202 __STR(node_value, depth, i);
203 while (j < network_count && node_score > scores[j])
204 ++j;
205 --j;
206
207 memmove(scores, scores + 1, j * sizeof(*scores));
208 memmove(networks, networks + 1, j * sizeof(*networks));
209 scores[j] = node_score;
210 memcpy(networks + j, node_value, sizeof(*networks));
211 }
212
213 return score;
214}
215
216static void stats_return_busy_networks(char **reply, const char *reply_end, stats_network_node *tree, size_t amount, int limit) {
217 ot_ip6 networks[amount];
218 ot_ip6 node_value;
219 size_t scores[amount];
220 size_t i;
221
222 memset(scores, 0, sizeof(scores));
223 memset(networks, 0, sizeof(networks));
224 memset(node_value, 0, sizeof(node_value));
225
226 stats_get_highscore_networks(tree, 0, node_value, scores, networks, amount, limit);
227
228 fmt_append(reply, reply_end, "Networks, limit /%d:\n", limit + STATS_NETWORK_NODE_BITWIDTH);
229 for (i = amount; i > 0; --i) {
230 if (scores[i - 1]) {
231 char ip_readable[64];
232
233 ip_readable[ip_format(ip_readable, networks[i - 1])] = 0;
234 fmt_append(reply, reply_end, "%08zd: %s\n", scores[i - 1], ip_readable);
235 }
236 }
237 fmt_append(reply, reply_end, "\n");
238}
239
240static stats_network_node *stats_woodpeckers_tree;
241static pthread_mutex_t g_woodpeckers_mutex = PTHREAD_MUTEX_INITIALIZER;
242
243static void stats_return_woodpeckers(char **reply, const char *reply_end, int amount) {
244 pthread_mutex_lock(&g_woodpeckers_mutex);
245 stats_return_busy_networks(reply, reply_end, stats_woodpeckers_tree, amount, STATS_NETWORK_NODE_MAXDEPTH);
246 pthread_mutex_unlock(&g_woodpeckers_mutex);
247}
248#endif
249
250typedef struct {
251 unsigned long long torrent_count;
252 unsigned long long peer_count;
253 unsigned long long seed_count;
254} torrent_stats;
255
256static int torrent_statter(ot_torrent *torrent, uintptr_t data) {
257 torrent_stats *stats = (torrent_stats *)data;
258 stats->torrent_count++;
259 stats->peer_count += torrent_peer_count(torrent);
260 stats->seed_count += torrent_seed_count(torrent);
261 return 0;
262}
263
264/* Converter function from memory to human readable hex strings */
265typedef struct {
266 size_t val;
267 ot_hash hash;
268} ot_record;
269
270static inline void stats_insert_into_highscore(size_t val, ot_record* list, size_t amount, ot_hash* hash) {
271 size_t i;
272 for (i = 0; (i < amount) && (list[i].val > val); ++i)
273 {}
274 /* if we score better than a record in the list, we need to make room in the high
275 score array by moving lower scoring entries up */
276 if (i < amount) {
277 memmove(list + i + 1, list + i, (amount - i - 1) * sizeof(ot_record));
278
279 memcpy(&list[i].hash, hash, sizeof(ot_hash));
280 list[i].val = val;
281 }
282}
283
284
285/* Fetches stats from tracker */
286void stats_top_txt(char **reply, const char *reply_end, size_t amount) {
287 size_t j, idx, bucket;
288 ot_record top100s[100], top100c[100], top100l[100];
289 char hex_out[42];
290
291 if (amount > 100)
292 amount = 100;
293
294 memset(top100s, 0, sizeof(top100s));
295 memset(top100c, 0, sizeof(top100c));
296 memset(top100l, 0, sizeof(top100l));
297
298 /* Iterate over complete torrent list */
299 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
300 ot_vector *torrents_list = mutex_bucket_lock(bucket);
301 for (j = 0; j < torrents_list->size; ++j) {
302 ot_torrent *torrent = (ot_torrent *)(torrents_list->data) + j;
303 size_t peer_count = torrent_peer_count(torrent);
304 size_t seed_count = torrent_seed_count(torrent);
305 size_t leech_count = peer_count - seed_count;
306
307 stats_insert_into_highscore(peer_count, top100c, amount, &torrent->hash);
308 stats_insert_into_highscore(seed_count, top100s, amount, &torrent->hash);
309 stats_insert_into_highscore(leech_count, top100l, amount, &torrent->hash);
310 }
311 mutex_bucket_unlock(bucket, 0);
312 if (!g_opentracker_running)
313 return;
314 }
315
316 fmt_append(reply, reply_end, "Top %zd torrents by peers:\n", amount);
317 for (idx = 0; idx < amount; ++idx)
318 if (top100c[idx].val)
319 fmt_append(reply, reply_end, "\t%zd\t%s\n", top100c[idx].val, hex_from_hash(hex_out, top100c[idx].hash));
320 fmt_append(reply, reply_end, "Top %zd torrents by seeds:\n", amount);
321 for (idx = 0; idx < amount; ++idx)
322 if (top100s[idx].val)
323 fmt_append(reply, reply_end, "\t%zd\t%s\n", top100s[idx].val, hex_from_hash(hex_out, top100s[idx].hash));
324 fmt_append(reply, reply_end, "Top %zd torrents by leechers:\n", amount);
325 for (idx = 0; idx < amount; ++idx)
326 if (top100l[idx].val)
327 fmt_append(reply, reply_end, "\t%zd\t%s\n", top100l[idx].val, hex_from_hash(hex_out, top100l[idx].hash));
328}
329
330static unsigned long events_per_time(unsigned long long events, time_t t) { return events / ((unsigned int)t ? (unsigned int)t : 1); }
331
332static void stats_connections_mrtg(char **reply, const char *reply_end) {
333 ot_time t = time_since_seconds(ot_start_time);
334 unsigned long long total[OT_COUNTER_COUNT];
335
336 counters_total(total);
337
338 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker connections, %lu conns/s :: %lu success/s.",
339 total[OT_COUNTER_TCP_CONNECTIONS] + total[OT_COUNTER_UDP_CONNECTIONS],
340 total[OT_COUNTER_TCP_ANNOUNCES] + total[OT_COUNTER_UDP_ANNOUNCES] + total[OT_COUNTER_UDP_CONNECTS], (int)t, (int)(t / 3600),
341 events_per_time(total[OT_COUNTER_TCP_CONNECTIONS] + total[OT_COUNTER_UDP_CONNECTIONS], t),
342 events_per_time(total[OT_COUNTER_TCP_ANNOUNCES] + total[OT_COUNTER_UDP_ANNOUNCES] + total[OT_COUNTER_UDP_CONNECTS], t));
343}
344
345static void stats_udpconnections_mrtg(char **reply, const char *reply_end) {
346 ot_time t = time_since_seconds(ot_start_time);
347 unsigned long long total[OT_COUNTER_COUNT];
348
349 counters_total(total);
350
351 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker udp4 stats, %lu conns/s :: %lu success/s.", total[OT_COUNTER_UDP_CONNECTIONS],
352 total[OT_COUNTER_UDP_ANNOUNCES] + total[OT_COUNTER_UDP_CONNECTS], (int)t, (int)(t / 3600),
353 events_per_time(total[OT_COUNTER_UDP_CONNECTIONS], t),
354 events_per_time(total[OT_COUNTER_UDP_ANNOUNCES] + total[OT_COUNTER_UDP_CONNECTS], t));
355}
356
357static void stats_tcpconnections_mrtg(char **reply, const char *reply_end) {
358 time_t t = time_since_seconds(ot_start_time);
359 unsigned long long total[OT_COUNTER_COUNT];
360
361 counters_total(total);
362
363 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker tcp4 stats, %lu conns/s :: %lu success/s.", total[OT_COUNTER_TCP_CONNECTIONS],
364 total[OT_COUNTER_TCP_ANNOUNCES], (int)t, (int)(t / 3600), events_per_time(total[OT_COUNTER_TCP_CONNECTIONS], t),
365 events_per_time(total[OT_COUNTER_TCP_ANNOUNCES], t));
366}
367
368static void stats_scrape_mrtg(char **reply, const char *reply_end) {
369 time_t t = time_since_seconds(ot_start_time);
370 unsigned long long total[OT_COUNTER_COUNT];
371
372 counters_total(total);
373
374 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker scrape stats, %lu scrape/s (tcp and udp)",
375 total[OT_COUNTER_TCP_SCRAPES], total[OT_COUNTER_UDP_SCRAPES], (int)t, (int)(t / 3600),
376 events_per_time((total[OT_COUNTER_TCP_SCRAPES] + total[OT_COUNTER_UDP_SCRAPES]), t));
377}
378
379static void stats_fullscrapes_mrtg(char **reply, const char *reply_end) {
380 ot_time t = time_since_seconds(ot_start_time);
381 unsigned long long total[OT_COUNTER_COUNT];
382
383 counters_total(total);
384
385 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker full scrape stats, %lu conns/s :: %lu bytes/s.",
386 total[OT_COUNTER_FULLSCRAPES] * 1000, total[OT_COUNTER_FULLSCRAPE_BYTES], (int)t, (int)(t / 3600),
387 events_per_time(total[OT_COUNTER_FULLSCRAPES], t),
388 events_per_time(total[OT_COUNTER_FULLSCRAPE_BYTES], t));
389}
390
391static void stats_peers_mrtg(char **reply, const char *reply_end) {
392 torrent_stats stats = {0, 0, 0};
393
394 iterate_all_torrents(torrent_statter, (uintptr_t)&stats);
395
396 fmt_append(reply, reply_end, "%llu\n%llu\nopentracker serving %llu torrents\nopentracker", stats.peer_count, stats.seed_count,
397 stats.torrent_count);
398}
399
400static void stats_torrents_mrtg(char **reply, const char *reply_end) {
401 size_t torrent_count = mutex_get_torrent_count();
402
403 fmt_append(reply, reply_end, "%zd\n%zd\nopentracker serving %zd torrents\nopentracker", torrent_count, (size_t)0, torrent_count);
404}
405
406static void stats_httperrors_txt(char **reply, const char *reply_end) {
407 unsigned long long total[OT_COUNTER_COUNT];
408
409 counters_total(total);
410
411 fmt_append(reply, reply_end, "302 RED %llu\n400 ... %llu\n400 PAR %llu\n400 COM %llu\n403 IP %llu\n404 INV %llu\n500 SRV %llu\n",
412 total[OT_COUNTER_FAILED + 0], total[OT_COUNTER_FAILED + 1], total[OT_COUNTER_FAILED + 2], total[OT_COUNTER_FAILED + 3],
413 total[OT_COUNTER_FAILED + 4], total[OT_COUNTER_FAILED + 5], total[OT_COUNTER_FAILED + 6]);
414}
415
416static void stats_return_renew_bucket(char **reply, const char *reply_end) {
417 unsigned long long total[OT_COUNTER_COUNT];
418
419 counters_total(total);
420
421 int i;
422
423 for (i = 0; i < OT_PEER_TIMEOUT; ++i)
424 fmt_append(reply, reply_end, "%02i %llu\n", i, total[OT_COUNTER_RENEWED + i]);
425}
426
427static void stats_return_sync_mrtg(char **reply, const char *reply_end) {
428 ot_time t = time_since_seconds(ot_start_time);
429 unsigned long long total[OT_COUNTER_COUNT];
430
431 counters_total(total);
432
433 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker connections, %lu conns/s :: %lu success/s.", total[OT_COUNTER_SYNCS], 0LL,
434 (int)t, (int)(t / 3600), events_per_time(total[OT_COUNTER_TCP_CONNECTIONS] + total[OT_COUNTER_UDP_CONNECTIONS], t),
435 events_per_time(total[OT_COUNTER_TCP_ANNOUNCES] + total[OT_COUNTER_UDP_ANNOUNCES] + total[OT_COUNTER_UDP_CONNECTS], t));
436}
437
438static void stats_return_completed_mrtg(char **reply, const char *reply_end) {
439 ot_time t = time_since_seconds(ot_start_time);
440 unsigned long long total[OT_COUNTER_COUNT];
441
442 counters_total(total);
443
444
445 fmt_append(reply, reply_end, "%llu\n%llu\n%i seconds (%i hours)\nopentracker, %lu completed/h.", total[OT_COUNTER_COMPLETED], 0LL, (int)t, (int)(t / 3600),
446 events_per_time(total[OT_COUNTER_COMPLETED], t / 3600));
447}
448
449#ifdef WANT_LOG_NUMWANT
450extern unsigned long long numwants[201];
451static void stats_return_numwants(char **reply, const char *reply_end) {
452 int i;
453 for (i = 0; i <= 200; ++i)
454 fmt_append(reply, reply_end, "%03d => %llu\n", i, numwants[i]);
455}
456#endif
457
458static void stats_return_everything(char **reply, const char *reply_end) {
459 unsigned long long total[OT_COUNTER_COUNT];
460
461 counters_total(total);
462
463 torrent_stats stats = {0, 0, 0};
464 int i;
465
466 iterate_all_torrents(torrent_statter, (uintptr_t)&stats);
467
468 fmt_append(reply, reply_end, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
469 fmt_append(reply, reply_end, "<stats>\n");
470 fmt_append(reply, reply_end, " <uptime>%llu</uptime>\n", (unsigned long long)time_since_seconds(ot_start_time));
471 fmt_append(reply, reply_end, " <torrents>\n");
472 fmt_append(reply, reply_end, " <count_mutex>%zd</count_mutex>\n", mutex_get_torrent_count());
473 fmt_append(reply, reply_end, " <count_iterator>%llu</count_iterator>\n", stats.torrent_count);
474 fmt_append(reply, reply_end, " </torrents>\n");
475 fmt_append(reply, reply_end, " <peers>\n <count>%llu</count>\n </peers>\n", stats.peer_count);
476 fmt_append(reply, reply_end, " <seeds>\n <count>%llu</count>\n </seeds>\n", stats.seed_count);
477 fmt_append(reply, reply_end, " <completed>\n <count>%llu</count>\n </completed>\n", total[OT_COUNTER_COMPLETED]);
478 fmt_append(reply, reply_end, " <connections>\n");
479 fmt_append(reply, reply_end, " <tcp>\n <accept>%llu</accept>\n <announce>%llu</announce>\n <scrape>%llu</scrape>\n </tcp>\n",
480 total[OT_COUNTER_TCP_CONNECTIONS], total[OT_COUNTER_TCP_ANNOUNCES], total[OT_COUNTER_TCP_SCRAPES]);
481 fmt_append(reply, reply_end, " <udp>\n <overall>%llu</overall>\n <connect>%llu</connect>\n <announce>%llu</announce>\n <scrape>%llu</scrape>\n <missmatch>%llu</missmatch>\n </udp>\n",
482 total[OT_COUNTER_UDP_CONNECTIONS], total[OT_COUNTER_UDP_CONNECTS], total[OT_COUNTER_UDP_ANNOUNCES], total[OT_COUNTER_UDP_SCRAPES],
483 total[OT_COUNTER_UDP_CONNID_MISSMATCH]);
484 fmt_append(reply, reply_end, " <livesync>\n <count>%llu</count>\n </livesync>\n", total[OT_COUNTER_SYNCS]);
485 fmt_append(reply, reply_end, " </connections>\n");
486 fmt_append(reply, reply_end, " <debug>\n");
487 fmt_append(reply, reply_end, " <renew>\n");
488 for (i = 0; i < OT_PEER_TIMEOUT; ++i)
489 fmt_append(reply, reply_end, " <count interval=\"%02i\">%llu</count>\n", i, total[OT_COUNTER_RENEWED + i]);
490 fmt_append(reply, reply_end, " </renew>\n");
491 fmt_append(reply, reply_end, " <http_error>\n");
492 for (i = 0; i < CODE_HTTPERROR_COUNT; ++i)
493 fmt_append(reply, reply_end, " <count code=\"%s\">%llu</count>\n", ot_failed_request_names[i], total[OT_COUNTER_FAILED + i]);
494 fmt_append(reply, reply_end, " </http_error>\n");
495 fmt_append(reply, reply_end, " <mutex_stall>\n <count>%llu</count>\n </mutex_stall>\n", total[OT_COUNTER_STALLS]);
496 fmt_append(reply, reply_end, " </debug>\n");
497 fmt_append(reply, reply_end, "</stats>");
498}
499
500/* The names as the Makefile spells them, so that what a binary reports maps
501 straight back onto the FEATURES lines it was built from */
502static const char *const build_features[] = {
503#ifdef WANT_V4_ONLY
504 "WANT_V4_ONLY",
505#endif
506#ifdef WANT_ACCESSLIST_BLACK
507 "WANT_ACCESSLIST_BLACK",
508#endif
509#ifdef WANT_ACCESSLIST_WHITE
510 "WANT_ACCESSLIST_WHITE",
511#endif
512#ifdef WANT_DYNAMIC_ACCESSLIST
513 "WANT_DYNAMIC_ACCESSLIST",
514#endif
515#ifdef WANT_SYNC_LIVE
516 "WANT_SYNC_LIVE",
517#endif
518#ifdef WANT_IP_FROM_QUERY_STRING
519 "WANT_IP_FROM_QUERY_STRING",
520#endif
521#ifdef WANT_IP_FROM_PROXY
522 "WANT_IP_FROM_PROXY",
523#endif
524#ifdef WANT_COMPRESSION_GZIP
525 "WANT_COMPRESSION_GZIP",
526#endif
527#ifdef WANT_COMPRESSION_GZIP_ALWAYS
528 "WANT_COMPRESSION_GZIP_ALWAYS",
529#endif
530#ifdef WANT_COMPRESSION_ZSTD
531 "WANT_COMPRESSION_ZSTD",
532#endif
533#ifdef WANT_COMPRESSION_ZSTD_ALWAYS
534 "WANT_COMPRESSION_ZSTD_ALWAYS",
535#endif
536#ifdef WANT_FULLSCRAPE
537 "WANT_FULLSCRAPE",
538#endif
539#ifdef WANT_MODEST_FULLSCRAPES
540 "WANT_MODEST_FULLSCRAPES",
541#endif
542#ifdef WANT_KEEPALIVE
543 "WANT_KEEPALIVE",
544#endif
545#ifdef WANT_RESTRICT_STATS
546 "WANT_RESTRICT_STATS",
547#endif
548#ifdef WANT_RESTRICT_FULLSCRAPE
549 "WANT_RESTRICT_FULLSCRAPE",
550#endif
551#ifdef WANT_LOG_NUMWANT
552 "WANT_LOG_NUMWANT",
553#endif
554#ifdef WANT_SPOT_WOODPECKER
555 "WANT_SPOT_WOODPECKER",
556#endif
557#ifdef WANT_SYSLOGS
558 "WANT_SYSLOGS",
559#endif
560#ifdef WANT_DEV_RANDOM
561 "WANT_DEV_RANDOM",
562#endif
563#ifdef WANT_INSECURE_RANDOM_FALLBACK
564 "WANT_INSECURE_RANDOM_FALLBACK",
565#endif
566#ifdef _DEBUG
567 "_DEBUG",
568#endif
569#ifdef _DEBUG_HTTPERROR
570 "_DEBUG_HTTPERROR",
571#endif
572#ifdef _DEBUG_RANDOMTORRENTS
573 "_DEBUG_RANDOMTORRENTS",
574#endif
575 NULL};
576
577void stats_return_tracker_features(char **reply, const char *reply_end) {
578 size_t i;
579
580 fmt_append(reply, reply_end, "events: %s\n", event_mechanism());
581 fmt_append(reply, reply_end, "features:");
582 for (i = 0; build_features[i]; ++i)
583 fmt_append(reply, reply_end, " %s", build_features[i]);
584 if (!build_features[0])
585 fmt_append(reply, reply_end, " none");
586 fmt_append(reply, reply_end, "\n");
587}
588
589void stats_return_tracker_version(char **reply, const char *reply_end) {
590 fmt_append(reply, reply_end, "opentracker %s", OT_VERSION);
591 if (*GIT_VERSION && strcmp(GIT_VERSION, OT_TAG))
592 fmt_append(reply, reply_end, " (%s)", GIT_VERSION);
593 fmt_append(reply, reply_end, "\n");
594 if (*OT_TAG)
595 fmt_append(reply, reply_end, "https://erdgeist.org/gitweb/opentracker/tag/?h=%s\n", OT_TAG);
596}
597
598void return_stats_for_tracker(char **reply, const char *reply_end, int mode, int format) {
599 (void)format;
600 switch (mode & TASK_TASK_MASK) {
601 case TASK_STATS_CONNS:
602 stats_connections_mrtg(reply, reply_end);
603 break;
604 case TASK_STATS_SCRAPE:
605 stats_scrape_mrtg(reply, reply_end);
606 break;
607 case TASK_STATS_UDP:
608 stats_udpconnections_mrtg(reply, reply_end);
609 break;
610 case TASK_STATS_TCP:
611 stats_tcpconnections_mrtg(reply, reply_end);
612 break;
613 case TASK_STATS_FULLSCRAPE:
614 stats_fullscrapes_mrtg(reply, reply_end);
615 break;
616 case TASK_STATS_COMPLETED:
617 stats_return_completed_mrtg(reply, reply_end);
618 break;
619 case TASK_STATS_HTTPERRORS:
620 stats_httperrors_txt(reply, reply_end);
621 break;
622 case TASK_STATS_RENEW:
623 stats_return_renew_bucket(reply, reply_end);
624 break;
625 case TASK_STATS_SYNCS:
626 stats_return_sync_mrtg(reply, reply_end);
627 break;
628#ifdef WANT_LOG_NUMWANT
629 case TASK_STATS_NUMWANTS:
630 stats_return_numwants(reply, reply_end);
631 break;
632#endif
633 default:
634 break;
635 }
636}
637
638static void stats_make(size_t *iovec_entries, struct iovec **iovector, ot_tasktype mode) {
639 char *r;
640 const char *r_end;
641
642 *iovec_entries = 0;
643 *iovector = NULL;
644 if (!(r = iovec_new_chunk(iovec_entries, iovector, OT_STATS_TMPSIZE)))
645 return;
646 r_end = r + OT_STATS_TMPSIZE;
647
648 switch (mode & TASK_TASK_MASK) {
649 case TASK_STATS_TORRENTS:
650 stats_torrents_mrtg(&r, r_end);
651 break;
652 case TASK_STATS_PEERS:
653 stats_peers_mrtg(&r, r_end);
654 break;
655 case TASK_STATS_TOP10:
656 stats_top_txt(&r, r_end, 10);
657 break;
658 case TASK_STATS_TOP100:
659 r = iovec_next_chunk(iovec_entries, iovector, r, 4 * OT_STATS_TMPSIZE);
660 if (!r)
661 return;
662 r_end = r + 4 * OT_STATS_TMPSIZE;
663 stats_top_txt(&r, r_end, 100);
664 break;
665 case TASK_STATS_EVERYTHING:
666 r = iovec_next_chunk(iovec_entries, iovector, r, OT_STATS_TMPSIZE + 64 * OT_PEER_TIMEOUT);
667 if (!r)
668 return;
669 r_end = r + OT_STATS_TMPSIZE + 64 * OT_PEER_TIMEOUT;
670 stats_return_everything(&r, r_end);
671 break;
672#ifdef WANT_SPOT_WOODPECKER
673 case TASK_STATS_WOODPECKERS:
674 stats_return_woodpeckers(&r, r_end, 128);
675 break;
676#endif
677 default:
678 iovec_free(iovec_entries, iovector);
679 return;
680 }
681 iovec_trim_last(iovec_entries, iovector, r);
682}
683
684void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FLAG proto, uintptr_t event_data) {
685 if (!ws)
686 return;
687
688 switch (event) {
689 case EVENT_ACCEPT:
690 if (proto == FLAG_TCP)
691 COUNT(OT_COUNTER_TCP_CONNECTIONS, 1);
692 else
693 COUNT(OT_COUNTER_UDP_CONNECTIONS, 1);
694 break;
695 case EVENT_ANNOUNCE:
696 if (proto == FLAG_TCP)
697 COUNT(OT_COUNTER_TCP_ANNOUNCES, 1);
698 else
699 COUNT(OT_COUNTER_UDP_ANNOUNCES, 1);
700 break;
701 case EVENT_CONNECT:
702 if (proto == FLAG_TCP)
703 COUNT(OT_COUNTER_TCP_CONNECTS, 1);
704 else
705 COUNT(OT_COUNTER_UDP_CONNECTS, 1);
706 break;
707 case EVENT_COMPLETED:
708#ifdef WANT_SYSLOGS
709 {
710 char timestring[64];
711 char hash_hex[42], peerid_hex[42], ip_readable[64];
712 struct tm time_now;
713 time_t ttt;
714
715 time(&ttt);
716 localtime_r(&ttt, &time_now);
717 if (!strftime(timestring, sizeof(timestring), "%FT%T%z", &time_now))
718 timestring[0] = 0;
719
720 hex_from_hash(hash_hex, *ws->hash);
721 if (ws->peer_id)
722 hex_from_hash(peerid_hex, (uint8_t *)ws->peer_id);
723 else {
724 *peerid_hex = 0;
725 }
726
727 ip_readable[ip_format(ip_readable, (char *)&ws->peer)] = 0;
728 syslog(LOG_INFO, "time=%s event=completed info_hash=%s peer_id=%s ip=%s", timestring, hash_hex, peerid_hex, ip_readable);
729 }
730#endif
731 COUNT(OT_COUNTER_COMPLETED, 1);
732 break;
733 case EVENT_SCRAPE:
734 if (proto == FLAG_TCP)
735 COUNT(OT_COUNTER_TCP_SCRAPES, 1);
736 else
737 COUNT(OT_COUNTER_UDP_SCRAPES, 1);
738 break;
739 case EVENT_FULLSCRAPE:
740 COUNT(OT_COUNTER_FULLSCRAPES, 1);
741 COUNT(OT_COUNTER_FULLSCRAPE_BYTES, event_data);
742 break;
743 case EVENT_FULLSCRAPE_REQUEST: {
744 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */
745 char _debug[512];
746 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)time_since_seconds(ot_start_time) / 60);
747 off += ip_format(_debug + off, *ip);
748 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n");
749 (void)!write(2, _debug, off);
750 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1);
751 } break;
752 case EVENT_FULLSCRAPE_REQUEST_GZIP: {
753 ot_ip6 *ip = (ot_ip6 *)event_data; /* ugly hack to transfer ip to stats */
754 char _debug[512];
755 int off = snprintf(_debug, sizeof(_debug), "[%08d] scrp: ", (unsigned int)time_since_seconds(ot_start_time) / 60);
756 off += ip_format(_debug + off, *ip);
757 off += snprintf(_debug + off, sizeof(_debug) - off, " - FULL SCRAPE\n");
758 (void)!write(2, _debug, off);
759 COUNT(OT_COUNTER_FULLSCRAPE_REQUESTS, 1);
760 } break;
761 case EVENT_FAILED:
762 if (event_data < CODE_HTTPERROR_COUNT)
763 COUNT(OT_COUNTER_FAILED + event_data, 1);
764 break;
765 case EVENT_RENEW:
766 if (event_data < OT_PEER_TIMEOUT)
767 COUNT(OT_COUNTER_RENEWED + event_data, 1);
768 break;
769 case EVENT_SYNC:
770 COUNT(OT_COUNTER_SYNCS, event_data);
771 break;
772 case EVENT_BUCKET_LOCKED:
773 COUNT(OT_COUNTER_STALLS, 1);
774 break;
775#ifdef WANT_SPOT_WOODPECKER
776 case EVENT_WOODPECKER:
777 pthread_mutex_lock(&g_woodpeckers_mutex);
778 stat_increase_network_count(&stats_woodpeckers_tree, 0, event_data);
779 pthread_mutex_unlock(&g_woodpeckers_mutex);
780 break;
781#endif
782 case EVENT_CONNID_MISSMATCH:
783 COUNT(OT_COUNTER_UDP_CONNID_MISSMATCH, 1);
784 default:
785 break;
786 }
787}
788
789void stats_cleanup(void) {
790#ifdef WANT_SPOT_WOODPECKER
791 pthread_mutex_lock(&g_woodpeckers_mutex);
792 stats_shift_down_network_count(&stats_woodpeckers_tree, 0, 1);
793 pthread_mutex_unlock(&g_woodpeckers_mutex);
794#endif
795}
796
797static void *stats_worker(void *args) {
798 size_t iovec_entries;
799 struct iovec *iovector;
800
801 (void)args;
802
803 while (g_opentracker_running) {
804 ot_tasktype tasktype = TASK_STATS;
805 ot_taskid taskid = workqueue_poptask(&tasktype);
806 if (!taskid)
807 break;
808 stats_make(&iovec_entries, &iovector, tasktype);
809 if (workqueue_pushresult(taskid, iovec_entries, iovector))
810 iovec_free(&iovec_entries, &iovector);
811 }
812 return NULL;
813}
814
815void stats_deliver(int64_t sock, int tasktype) { workqueue_pushtask(sock, tasktype); }
816
817static pthread_t thread_id;
818void stats_init(void) {
819 ot_start_time = time_now_seconds();
820 pthread_create(&thread_id, NULL, stats_worker, NULL);
821}
822
823void stats_deinit(void) {
824 workqueue_wakeall();
825 pthread_join(thread_id, NULL);
826}
diff --git a/src/ot_stats.h b/src/ot_stats.h
new file mode 100644
index 0000000..45a547e
--- /dev/null
+++ b/src/ot_stats.h
@@ -0,0 +1,40 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_STATS_H__
5#define OT_STATS_H__
6
7#include "trackerlogic.h"
8
9typedef enum {
10 EVENT_ACCEPT,
11 EVENT_READ,
12 EVENT_CONNECT, /* UDP only */
13 EVENT_ANNOUNCE,
14 EVENT_COMPLETED,
15 EVENT_RENEW,
16 EVENT_SYNC,
17 EVENT_SCRAPE,
18 EVENT_FULLSCRAPE_REQUEST,
19 EVENT_FULLSCRAPE_REQUEST_GZIP,
20 EVENT_FULLSCRAPE_REQUEST_ZSTD,
21 EVENT_FULLSCRAPE, /* TCP only */
22 EVENT_FAILED,
23 EVENT_BUCKET_LOCKED,
24 EVENT_WOODPECKER,
25 EVENT_CONNID_MISSMATCH
26} ot_status_event;
27
28void stats_counters_register(struct ot_workstruct *ws);
29void stats_counters_retire(struct ot_workstruct *ws);
30
31void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FLAG proto, uintptr_t event_data);
32void stats_deliver(int64_t sock, int tasktype);
33void stats_cleanup(void);
34void return_stats_for_tracker(char **reply, const char *reply_end, int mode, int format);
35void stats_return_tracker_version(char **reply, const char *reply_end);
36void stats_return_tracker_features(char **reply, const char *reply_end);
37void stats_init(void);
38void stats_deinit(void);
39
40#endif
diff --git a/src/ot_tcp.c b/src/ot_tcp.c
new file mode 100644
index 0000000..67a0ebc
--- /dev/null
+++ b/src/ot_tcp.c
@@ -0,0 +1,202 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <pthread.h>
7#include <stdatomic.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <unistd.h>
12
13/* Opentracker */
14#include "ot_batch.h"
15#include "ot_buf.h"
16#include "ot_event.h"
17#include "ot_fdstate.h"
18#include "ot_http.h"
19#include "ot_mutex.h"
20#include "ot_socket.h"
21#include "ot_worker.h"
22#include "ot_stats.h"
23#include "ot_tcp.h"
24#include "trackerlogic.h"
25
26static ssize_t header_complete(char *request, ssize_t byte_count) {
27 ssize_t i = 0, state = 0;
28
29 for (i = 1; i < byte_count; i += 2)
30 if (request[i] <= 13) {
31 i--;
32 for (state = 0; i < byte_count; ++i) {
33 char c = request[i];
34 if (c == '\r' || c == '\n')
35 state = (state >> 2) | ((c << 6) & 0xc0);
36 else
37 break;
38 if (state >= 0xa0 || state == 0x99)
39 return i + 1;
40 }
41 }
42 return 0;
43}
44
45void tcp_read(const int64_t sock, struct ot_workstruct *ws) {
46 struct http_data *cookie = fdstate_cookie(sock);
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);
59
60 if (byte_count == 0 || (byte_count == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
61 http_close(sock);
62 return;
63 }
64
65 if (byte_count == -1)
66 return;
67
68 ws->request = NULL;
69 ws->request_size = 0;
70 ws->header_size = 0;
71 ws->keep_alive = 0;
72
73 /* If we get the whole request in one packet, handle it without copying */
74 if (!cookie->request.data) {
75 if ((ws->header_size = header_complete(ws->inbuf, byte_count))) {
76 ws->request = ws->inbuf;
77 ws->request_size = byte_count;
78 http_handle_request(sock, ws);
79 } else if (buf_cat(&cookie->request, ws->inbuf, (size_t)byte_count))
80 http_close(sock);
81 return;
82 }
83
84 if (buf_cat(&cookie->request, ws->inbuf, (size_t)byte_count) || cookie->request.size > G_INBUF_SIZE) {
85 http_issue_error(sock, ws, CODE_HTTPERROR_500);
86 return;
87 }
88
89 generation = fdstate_generation((int)sock);
90 while ((ws->header_size = header_complete(cookie->request.data, (ssize_t)cookie->request.size))) {
91 ws->request = cookie->request.data;
92 ws->request_size = (ssize_t)cookie->request.size;
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;
104#ifdef WANT_KEEPALIVE
105 if (!ws->keep_alive)
106#endif
107 return;
108 }
109}
110
111void tcp_write(const int64_t sock) {
112 struct http_data *cookie = fdstate_cookie(sock);
113 int chunked = 0;
114 int keep_alive = 0;
115
116 if (cookie) {
117 chunked = (cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER) != 0;
118 keep_alive = (cookie->flag & STRUCT_HTTP_FLAG_KEEPALIVE) != 0;
119
120 if (cookie->batch) {
121 if (batch_send(sock, cookie->batch) == BATCH_FAILED) {
122 http_close(sock);
123 return;
124 }
125 if (batch_pending(cookie->batch))
126 return;
127 }
128 }
129
130 /* In a chunked transfer, wait for the next piece once everything queued has gone out */
131 if (chunked)
132 http_interest_set(sock, cookie, 0);
133 else if (keep_alive) {
134 /* The reply is out and the client asked to keep the connection, so go
135 back to waiting for the next request */
136 http_interest_set(sock, cookie, EVENT_IN);
137 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT));
138 } else
139 http_close(sock);
140}
141
142/* The fast path, assuming that the complete request has usually arrived by the time a
143 connection is accepted, so it is answered here outside the event loop. The more load
144 a tracker has, the more likely it is that by the time it accepts, the roundtrip to
145 the peer has completed.
146 If the request could not be completely handled, the stack cookie is promoted to heap
147 and the connection handed over to the event loop to finish */
148void tcp_accept(const int64_t serversocket, struct ot_workstruct *ws) {
149 int64_t sock;
150 ot_ip6 ip;
151 uint16_t port;
152
153 while ((sock = socket_accept(serversocket, ip, &port)) != -1) {
154 struct http_data cookie;
155 uint32_t generation;
156
157 memset(&cookie, 0, sizeof(cookie));
158 memcpy(cookie.ip, ip, sizeof(ot_ip6));
159 cookie.interest = EVENT_IN;
160 cookie.flag = STRUCT_HTTP_FLAG_ONSTACK;
161
162 generation = fdstate_open(sock, &cookie, time_future_seconds(OT_CLIENT_TIMEOUT));
163 if (!fdstate_claim((int)sock, generation)) {
164 fdstate_close(sock);
165 event_close((int)sock);
166 continue;
167 }
168
169 stats_issue_event(ws, EVENT_ACCEPT, FLAG_TCP, (uintptr_t)ip);
170
171 tcp_read(sock, ws);
172
173 /* Gone already if it was answered and closed inline */
174 if (fdstate_generation((int)sock) != generation)
175 continue;
176
177 /* Handling it may already have given it a heap home and handed it to
178 another thread, and then it is no longer this frame's to touch */
179 if (fdstate_cookie((int)sock) != &cookie)
180 fdstate_release((int)sock);
181 else if (!http_adopt(sock))
182 http_close(sock);
183 else
184 fdstate_release((int)sock);
185 }
186}
187
188/* A worker blocks in accept and nowhere else: the connection it is handed is
189 non blocking, so a client that stops talking is given to the event loop
190 rather than keeping this thread. */
191static void tcp_run(struct ot_worker *me) {
192 while (g_opentracker_running)
193 tcp_accept(me->sock, &me->ws);
194}
195
196void tcp_worker_install(int64_t sock) {
197 socket_set_blocking((int)sock, 1);
198 socket_defer_accept((int)sock);
199
200 if (worker_start(tcp_run, sock) == -1)
201 fprintf(stderr, "Warning: could not install a tcp worker, this socket stays with the workers already running.\n");
202}
diff --git a/src/ot_tcp.h b/src/ot_tcp.h
new file mode 100644
index 0000000..afed142
--- /dev/null
+++ b/src/ot_tcp.h
@@ -0,0 +1,24 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_TCP_H__
5#define OT_TCP_H__
6
7#include <stdint.h>
8
9#include "trackerlogic.h"
10
11/* Take whatever connections are waiting on a listening socket and answer
12 them, each on this thread's stack, handing a connection that cannot be
13 finished to the event loop */
14void tcp_accept(const int64_t serversocket, struct ot_workstruct *ws);
15
16/* Handler connections in the event loop has become readable or writable */
17void tcp_read(const int64_t sock, struct ot_workstruct *ws);
18void tcp_write(const int64_t sock);
19
20/* One thread accepting on one socket. Called once per worker. */
21void tcp_worker_install(int64_t sock);
22
23
24#endif
diff --git a/src/ot_udp.c b/src/ot_udp.c
new file mode 100644
index 0000000..609089b
--- /dev/null
+++ b/src/ot_udp.c
@@ -0,0 +1,272 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <pthread.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <unistd.h>
11
12/* Opentracker */
13#include "ot_ip.h"
14#include "ot_random.h"
15#include "ot_rijndael.h"
16#include "ot_socket.h"
17#include "ot_worker.h"
18#include "ot_stats.h"
19#include "ot_udp.h"
20#include "trackerlogic.h"
21
22/* BEP 15: "Up to about 74 torrents can be scraped at once" */
23#define OT_MAX_SCRAPE_UDP 74
24
25static uint32_t g_rijndael_round_key[44] = {0};
26static volatile uint32_t g_key_of_the_hour[2] = {0};
27static volatile ot_time g_hour_of_the_key;
28
29
30static void udp_generate_rijndael_round_key(void) {
31 uint32_t key[16];
32 random_bytes(key, sizeof(key));
33 rijndaelKeySetupEnc128(g_rijndael_round_key, (uint8_t *)key);
34
35 g_key_of_the_hour[0] = random_uint32();
36 g_hour_of_the_key = time_now_minutes();
37}
38
39/* Generate current and previous connection id for ip */
40static void udp_make_connectionid(uint32_t connid[2], const ot_ip6 remoteip, int age) {
41 uint32_t plain[4], crypt[4];
42 int i;
43 uint32_t current_key_of_the_hour;
44
45 if (time_since_minutes(g_hour_of_the_key) >= 60) {
46 uint32_t old_key_of_the_hour = g_key_of_the_hour[0];
47 uint32_t new_key_of_the_hour = random_uint32();
48 /* If in the meantime another thread has performed
49 key rotation, do not overwrite their results */
50 if (time_since_minutes(g_hour_of_the_key) >= 60) {
51 /* Upgrade en bloc */
52 g_hour_of_the_key = time_now_minutes();
53 g_key_of_the_hour[0] = new_key_of_the_hour;
54 g_key_of_the_hour[1] = old_key_of_the_hour;
55 }
56 }
57
58 memcpy(plain, remoteip, sizeof(plain));
59 current_key_of_the_hour = g_key_of_the_hour[age];
60 for (i = 0; i < 4; ++i)
61 plain[i] ^= current_key_of_the_hour;
62 rijndaelEncrypt128(g_rijndael_round_key, (uint8_t *)plain, (uint8_t *)crypt);
63 connid[0] = crypt[0] ^ crypt[1];
64 connid[1] = crypt[2] ^ crypt[3];
65}
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
119/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */
120int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
121 ot_ip6 remoteip;
122 const char *request = ws->inbuf;
123 char *reply;
124 uint32_t left, event, numwant;
125 uint32_t connid[2];
126 uint32_t action;
127 uint16_t port, remoteport;
128 size_t byte_count, scrape_count, max_peers, i;
129 ot_hash *hashes;
130
131 ssize_t result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport);
132 if (result <= 0)
133 return 0;
134 byte_count = (size_t)result;
135
136 stats_issue_event(ws, EVENT_ACCEPT, FLAG_UDP, (uintptr_t)remoteip);
137 stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count);
138
139 /* Minimum udp tracker packet size, also catches error */
140 if (byte_count < UDP_REQUEST_HEADER_SIZE)
141 return 1;
142
143 /* Get action to take. Ignore error messages and broken packets */
144 action = udp_read32(request, UDP_REQUEST_ACTION_OFFSET);
145 if (action > UDP_ACTION_SCRAPE)
146 return 1;
147
148 /* Generate the connection id we give out and expect to and from
149 the requesting ip address, this prevents udp spoofing */
150 udp_make_connectionid(connid, remoteip, 0);
151
152 /* Initialise hash pointer */
153 ws->hash = NULL;
154 ws->peer_id = NULL;
155
156 /* If action is not connect, then we expect the derived
157 connection id in first 64 bit */
158 if (action != UDP_ACTION_CONNECT && memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
159 /* If connection id does not match, try the one that was
160 valid in the previous hour. Only if this also does not
161 match, return an error packet */
162 udp_make_connectionid(connid, remoteip, 1);
163 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
164 static const char err_idmiss[] = "Connection ID missmatch.";
165
166 /* Nobody has vouched for this address yet, so it is not sent more
167 than was sent in its name */
168 if (byte_count >= UDP_REPLY_HEADER_SIZE + sizeof(err_idmiss))
169 udp_send_error(serversocket, ws, err_idmiss, remoteip, remoteport);
170 stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, byte_count);
171 return 1;
172 }
173 }
174
175 switch (action) {
176 case UDP_ACTION_CONNECT:
177 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, g_udp_protocol_id, sizeof(g_udp_protocol_id)))
178 return 1;
179
180 reply = udp_reply_header(ws->outbuf, UDP_ACTION_CONNECT, request);
181 memcpy(reply, connid, sizeof(connid));
182 reply += sizeof(connid);
183
184 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
185 stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, reply - ws->outbuf);
186 break;
187
188 case UDP_ACTION_ANNOUNCE:
189 if (byte_count < UDP_ANNOUNCE_SIZE)
190 return 1;
191
192 /* We do only want to know, if it is zero */
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);
197
198 /* The peer keeps its port the way it came over the wire */
199 memcpy(&port, request + UDP_ANNOUNCE_PORT_OFFSET, sizeof(port));
200
201 OT_SETIP(ws->peer, remoteip);
202 OT_SETPORT(ws->peer, &port);
203 OT_PEERFLAG(ws->peer) = 0;
204
205 if (event == UDP_EVENT_COMPLETED)
206 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
207 if (event == UDP_EVENT_STOPPED)
208 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED;
209 if (!left)
210 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;
211
212 ws->reply = udp_reply_header(ws->outbuf, UDP_ACTION_ANNOUNCE, request);
213
214 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */
215 ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws);
216 } else {
217 /* List of peers should fit in a single UDP packet */
218 max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
219 if (numwant > max_peers)
220 numwant = max_peers;
221
222 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant);
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 */
226 if (!ws->reply_size) {
227 udp_send_error(serversocket, ws, "Tracker is out of resources, try again later.", remoteip, remoteport);
228 return 1;
229 }
230 }
231 ws->reply_size += UDP_REPLY_HEADER_SIZE;
232
233 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
234 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size);
235 break;
236
237 case UDP_ACTION_SCRAPE:
238 scrape_count = (byte_count - UDP_SCRAPE_INFO_HASH_OFFSET) / sizeof(ot_hash);
239 if (scrape_count > OT_MAX_SCRAPE_UDP)
240 scrape_count = OT_MAX_SCRAPE_UDP;
241
242 hashes = (ot_hash *)(ws->inbuf + UDP_SCRAPE_INFO_HASH_OFFSET);
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);
246
247 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
248 stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count);
249 break;
250 }
251 return 1;
252}
253
254static void udp_run(struct ot_worker *me) {
255 while (g_opentracker_running)
256 handle_udp6(me->sock, &me->ws);
257}
258
259void udp_init(void) {
260 if (!g_rijndael_round_key[0])
261 udp_generate_rijndael_round_key();
262}
263
264void udp_worker_install(int64_t sock) {
265#ifdef _DEBUG
266 fprintf(stderr, "Installing a worker on udp socket %ld\n", (unsigned long)sock);
267#endif
268 socket_set_blocking((int)sock, 1);
269
270 if (worker_start(udp_run, sock) == -1)
271 fprintf(stderr, "Warning: could not install a udp worker, this socket stays with the workers already running.\n");
272}
diff --git a/src/ot_udp.h b/src/ot_udp.h
new file mode 100644
index 0000000..2710744
--- /dev/null
+++ b/src/ot_udp.h
@@ -0,0 +1,17 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_UDP_H__
5#define OT_UDP_H__
6
7#include <stdint.h>
8
9#include "trackerlogic.h"
10
11void udp_init(void);
12/* One thread reading one socket. Called once per worker. */
13void udp_worker_install(int64_t sock);
14
15int handle_udp6(int64_t serversocket, struct ot_workstruct *ws);
16
17#endif
diff --git a/src/ot_urlencoded.c b/src/ot_urlencoded.c
new file mode 100644
index 0000000..c977adb
--- /dev/null
+++ b/src/ot_urlencoded.c
@@ -0,0 +1,172 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* Opentracker */
5#include "ot_urlencoded.h"
6
7/* System */
8#include <string.h>
9
10/* Idea is to do a in place replacement or guarantee at least
11 strlen( string ) bytes in deststring
12 watch http://www.ietf.org/rfc/rfc2396.txt
13 unreserved = alphanum | mark
14 mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
15 we add '%' to the matrix to not stop at encoded chars.
16 After losing too many requests to being too strict, add the following characters to reserved matrix
17 relax = "+" | "," | "/" | ";" | "<" | ">" | ":"
18*/
19
20/* This matrix holds for each ascii character the information,
21 whether it is a non-terminating character for one of the three
22 scan states we are in, that is 'path', 'param' and 'value' from
23 /path?param=value&param=value, it is encoded in bit 0, 1 and 2
24 respectively
25
26 The top bit of lower nibble indicates, whether this character is
27 a hard terminator, ie. \0, \n or \s, where the whole scanning
28 process should terminate
29 */
30static const unsigned char is_unreserved[256] = {
31 8,0,0,0,0,0,0,0,0,0,8,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
32 8,7,8,8,8,7,0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,4,7,6,
33 4,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,7,
34 8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,7,0,
35 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
36 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
37 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
38 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
39};
40
41/* Do a fast nibble to hex representation conversion */
42static unsigned char fromhex(unsigned char x) {
43 x -= '0';
44 if (x <= 9)
45 return x;
46 x &= ~0x20;
47 x -= 'A' - '0';
48 if (x < 6)
49 return x + 10;
50 return 0xff;
51}
52
53/* Skip the value of a param=value pair */
54void urlencoded_skip_value(char **string) {
55 const unsigned char *s = *(const unsigned char **)string;
56 unsigned char f;
57
58 /* Since we are asked to skip the 'value', we assume to stop at
59 terminators for a 'value' string position */
60 while ((f = is_unreserved[*s++]) & SCAN_SEARCHPATH_VALUE)
61 ;
62
63 /* If we stopped at a hard terminator like \0 or \n, make the
64 next urlencoded_parse encounter it again */
65 if (f & SCAN_SEARCHPATH_TERMINATOR)
66 --s;
67
68 *string = (char *)s;
69}
70
71int urlencoded_match_keyword(const ot_keywords *keywords, char **string, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags) {
72 char *deststring = *string;
73 ssize_t match_length = urlencoded_parse(string, deststring, deststring_end, flags);
74
75 if (match_length < 0)
76 return match_length;
77 if (match_length == 0)
78 return -3;
79
80 /* Compare on the exact decoded length. */
81 while (keywords->key) {
82 if ((size_t)match_length == strlen(keywords->key) && !memcmp(keywords->key, deststring, (size_t)match_length))
83 return keywords->value;
84 keywords++;
85 }
86
87 return -3;
88}
89
90ssize_t urlencoded_parse(char **string, char *deststring, const char *deststring_end, SCAN_SEARCHPATH_FLAG flags) {
91 const unsigned char *s = *(const unsigned char **)string;
92 unsigned char *d = (unsigned char *)deststring;
93 unsigned char b, c;
94
95 /* This is the main decoding loop.
96 'flag' determines, which characters are non-terminating in current context
97 (ie. stop at '=' and '&' if scanning for a 'param'; stop at '?' if scanning for the path )
98 */
99 while (is_unreserved[c = *s++] & flags) {
100
101 /* When encountering an url escaped character, try to decode */
102 if (c == '%') {
103 if ((b = fromhex(*s++)) == 0xff)
104 return -1;
105 if ((c = fromhex(*s++)) == 0xff)
106 return -1;
107 c |= (b << 4);
108 }
109
110 if ((const char *)d >= deststring_end)
111 return -1;
112
113 /* Write (possibly decoded) character to output */
114 *d++ = c;
115 }
116
117 switch (c) {
118 case 0:
119 case '\r':
120 case '\n':
121 case ' ':
122 /* If we started scanning on a hard terminator, indicate we've finished */
123 if (d == (unsigned char *)deststring)
124 return -2;
125
126 /* Else make the next call to urlencoded_parse encounter it again */
127 --s;
128 break;
129 case '?':
130 if (flags != SCAN_PATH)
131 return -1;
132 break;
133 case '=':
134 if (flags != SCAN_SEARCHPATH_PARAM)
135 return -1;
136 break;
137 case '&':
138 if (flags == SCAN_PATH)
139 return -1;
140 if (flags == SCAN_SEARCHPATH_PARAM)
141 --s;
142 break;
143 default:
144 return -1;
145 }
146
147 *string = (char *)s;
148 return d - (unsigned char *)deststring;
149}
150
151
152size_t urlencoded_format(char *dest, const uint8_t *src, size_t len) {
153 static const char safe[] = "$/.=~-_";
154 static const char hexdigit[] = "0123456789abcdef";
155 size_t written = 0, i;
156
157 for (i = 0; i < len; ++i) {
158 uint8_t c = src[i];
159
160 /* strchr would find the terminator, so a zero byte never counts as safe */
161 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c && strchr(safe, c))) {
162 dest[written++] = (char)c;
163 } else {
164 dest[written] = '%';
165 dest[written + 1] = hexdigit[c >> 4];
166 dest[written + 2] = hexdigit[c & 15];
167 written += 3;
168 }
169 }
170
171 return written;
172}
diff --git a/scan_urlencoded_query.h b/src/ot_urlencoded.h
index 06b91f5..053e079 100644
--- a/scan_urlencoded_query.h
+++ b/src/ot_urlencoded.h
@@ -1,16 +1,16 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org> 1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. 2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4 $id$ */
5 3
6#ifndef SCAN_URLENCODED_QUERY_H__ 4#ifndef SCAN_URLENCODED_QUERY_H__
7#define SCAN_URLENCODED_QUERY_H__ 5#define SCAN_URLENCODED_QUERY_H__
8 6
7#include <stddef.h>
8#include <stdint.h>
9#include <sys/types.h> 9#include <sys/types.h>
10 10
11typedef struct { 11typedef struct {
12 char *key; 12 const char *key;
13 int value; 13 int value;
14} ot_keywords; 14} ot_keywords;
15 15
16typedef enum { 16typedef enum {
@@ -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 scan_urlencoded_query(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,18 +38,16 @@ ssize_t scan_urlencoded_query(char **string, char *deststring, SCAN_SEARCHPATH_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 scan_find_keywords( 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
45*/ 45*/
46void scan_urlencoded_skipvalue( char **string ); 46void urlencoded_skip_value(char **string);
47 47
48/* data pointer to len chars of string 48
49 len length of chars in data to parse 49/* The other direction: percent encode len bytes from src into dest and return
50 number number to receive result 50 how many characters were written. dest needs room for three times len. */
51 returns number of bytes not parsed, mostly !=0 means fail 51size_t urlencoded_format(char *dest, const uint8_t *src, size_t len);
52 */
53ssize_t scan_fixed_int( char *data, size_t len, int *number );
54 52
55#endif 53#endif
diff --git a/src/ot_vector.c b/src/ot_vector.c
new file mode 100644
index 0000000..ef38919
--- /dev/null
+++ b/src/ot_vector.c
@@ -0,0 +1,292 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stddef.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10/* Opentracker */
11#include "trackerlogic.h"
12
13static int vector_compare_peer6(const void *peer1, const void *peer2) { return memcmp(peer1, peer2, OT_PEER_COMPARE_SIZE6); }
14static int vector_compare_peer4(const void *peer1, const void *peer2) { return memcmp(peer1, peer2, OT_PEER_COMPARE_SIZE4); }
15
16/* This function gives us a binary search that returns a pointer, even if
17 no exact match is found. In that case it sets exactmatch 0 and gives
18 calling functions the chance to insert data
19*/
20void *vector_binary_search(const void *const key, const void *base, const size_t member_count, const size_t member_size, size_t compare_size, int *exactmatch) {
21 size_t interval = member_count;
22
23 while (interval) {
24 uint8_t *lookat = ((uint8_t *)base) + member_size * (interval / 2);
25 int cmp = memcmp(lookat, key, compare_size);
26 if (cmp == 0) {
27 base = lookat;
28 break;
29 }
30 if (cmp < 0) {
31 base = lookat + member_size;
32 interval--;
33 }
34 interval /= 2;
35 }
36
37 *exactmatch = interval;
38 return (void *)base;
39}
40
41static uint8_t vector_hash_peer(ot_peer const *peer, size_t compare_size, size_t bucket_count) {
42 unsigned int hash = 5381;
43 uint8_t *p = (uint8_t *)peer;
44 while (compare_size--)
45 hash += (hash << 5) + *(p++);
46 return hash % bucket_count;
47}
48
49/* This is the generic insert operation for our vector type.
50 It tries to locate the object at "key" with size "member_size" by comparing its first "compare_size" bytes with
51 those of objects in vector. Our special "vector_binary_search" function does that and either returns the match or a
52 pointer to where the object is to be inserted. vector_find_or_insert makes space for the object and copies it,
53 if it wasn't found in vector. Caller needs to check the passed "exactmatch" variable to see, whether an insert
54 took place. If resizing the vector failed, NULL is returned, else the pointer to the object in vector.
55*/
56void *vector_find_or_insert(ot_vector *vector, void *key, size_t member_size, size_t compare_size, int *exactmatch) {
57 uint8_t *match = vector_binary_search(key, vector->data, vector->size, member_size, compare_size, exactmatch);
58 size_t match_offset, bytes_after;
59
60 if (*exactmatch)
61 return match;
62
63 /* Hold the insertion point as an offset rather than a pointer: it survives
64 the realloc below, and an empty vector has no data pointer to offset from
65 in the first place */
66 match_offset = vector->size ? (size_t)(match - (uint8_t *)vector->data) : 0;
67 bytes_after = member_size * vector->size - match_offset;
68
69 if (vector->size + 1 > vector->space) {
70 size_t new_space = vector->space ? OT_VECTOR_GROW_RATIO * vector->space : OT_VECTOR_MIN_MEMBERS;
71 uint8_t *new_data = realloc(vector->data, new_space * member_size);
72
73 if (!new_data)
74 return NULL;
75
76 vector->data = new_data;
77 vector->space = new_space;
78 }
79
80 match = (uint8_t *)vector->data + match_offset;
81 memmove(match + member_size, match, bytes_after);
82
83 vector->size++;
84 return match;
85}
86
87ot_peer *vector_find_or_insert_peer(ot_vector *vector, ot_peer const *peer, size_t peer_size, int *exactmatch) {
88 ot_peer *match;
89 const size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
90 size_t match_offset, bytes_after;
91
92 /* If space is zero but size is set, we're dealing with a list of vector->size buckets */
93 if (vector->space < vector->size)
94 vector = ((ot_vector *)vector->data) + vector_hash_peer(peer, compare_size, vector->size);
95 match = vector_binary_search(peer, vector->data, vector->size, peer_size, compare_size, exactmatch);
96
97 if (*exactmatch)
98 return match;
99
100 /* Hold the insertion point as an offset rather than a pointer: it survives
101 the realloc below, and an empty vector has no data pointer to offset from
102 in the first place. bytes_after is what has to move up by peer_size to
103 make room for the new peer */
104 match_offset = vector->size ? (size_t)(match - (ot_peer *)vector->data) : 0;
105 bytes_after = vector->size * peer_size - match_offset;
106
107 if (vector->size + 1 > vector->space) {
108 size_t new_space = vector->space ? OT_VECTOR_GROW_RATIO * vector->space : OT_VECTOR_MIN_MEMBERS;
109 ot_peer *new_data = realloc(vector->data, new_space * peer_size);
110
111 if (!new_data)
112 return NULL;
113
114 vector->data = new_data;
115 vector->space = new_space;
116 }
117
118 match = (ot_peer *)vector->data + match_offset;
119 memmove(match + peer_size, match, bytes_after);
120
121 vector->size++;
122 return match;
123}
124
125/* This is the non-generic delete from vector-operation specialized for peers in pools.
126 It returns 0 if no peer was found (and thus not removed)
127 1 if a non-seeding peer was removed
128 2 if a seeding peer was removed
129*/
130int vector_remove_peer(ot_vector *vector, ot_peer const *peer, size_t peer_size) {
131 int exactmatch, was_seeder;
132 ot_peer *match, *end;
133 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
134
135 if (!vector->size)
136 return 0;
137
138 /* If space is zero but size is set, we're dealing with a list of vector->size buckets */
139 if (vector->space < vector->size)
140 vector = ((ot_vector *)vector->data) + vector_hash_peer(peer, compare_size, vector->size);
141
142 end = ((ot_peer *)vector->data) + peer_size * vector->size;
143 match = (ot_peer *)vector_binary_search(peer, vector->data, vector->size, peer_size, compare_size, &exactmatch);
144 if (!exactmatch)
145 return 0;
146
147 was_seeder = (OT_PEERFLAG_D(match, peer_size) & PEER_FLAG_SEEDING) ? 2 : 1;
148 memmove(match, match + peer_size, end - match - peer_size);
149
150 vector->size--;
151 vector_fixup_peers(vector, peer_size);
152 return was_seeder;
153}
154
155void vector_remove_torrent(ot_vector *vector, ot_torrent *match) {
156 ot_torrent *end;
157
158 if (!vector->size)
159 return;
160
161 end = ((ot_torrent *)vector->data) + vector->size;
162
163 free_peerlist(match->peer_list);
164
165 memmove(match, match + 1, sizeof(ot_torrent) * (end - match - 1));
166 if ((--vector->size * OT_VECTOR_SHRINK_THRESH < vector->space) && (vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS)) {
167 void *new_data = realloc(vector->data, (vector->space / OT_VECTOR_SHRINK_RATIO) * sizeof(ot_torrent));
168 if (new_data) {
169 vector->space /= OT_VECTOR_SHRINK_RATIO;
170 vector->data = new_data;
171 }
172 }
173}
174
175void vector_clean_list(ot_vector *vector, size_t num_buckets) {
176 while (num_buckets--)
177 free(vector[num_buckets].data);
178 free(vector);
179 return;
180}
181
182void vector_redistribute_buckets(ot_vector *peer_vector, size_t peer_size, size_t peer_count) {
183 size_t bucket, bucket_size_new, num_buckets_new, num_buckets_old = 1;
184 ot_vector *bucket_list_new, *bucket_list_old = peer_vector;
185 int (*sort_func)(const void *, const void *) = peer_size == OT_PEER_SIZE6 ? &vector_compare_peer6 : &vector_compare_peer4;
186
187 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
188 num_buckets_old = peer_vector->size;
189 bucket_list_old = peer_vector->data;
190 }
191
192 if (peer_count < 255)
193 num_buckets_new = 1;
194 else if (peer_count > 8192)
195 num_buckets_new = 64;
196 else if (peer_count >= 512 && peer_count < 4096)
197 num_buckets_new = 16;
198 else if (peer_count < 512 && num_buckets_old <= 16)
199 num_buckets_new = num_buckets_old;
200 else if (peer_count < 512)
201 num_buckets_new = 1;
202 else if (peer_count < 8192 && num_buckets_old > 1)
203 num_buckets_new = num_buckets_old;
204 else
205 num_buckets_new = 16;
206
207 if (num_buckets_new == num_buckets_old)
208 return;
209
210 /* Assume near perfect distribution */
211 bucket_list_new = calloc(1, num_buckets_new * sizeof(ot_vector));
212 if (!bucket_list_new)
213 return;
214
215 bucket_size_new = OT_VECTOR_MIN_MEMBERS;
216 while (bucket_size_new * num_buckets_new < peer_count)
217 bucket_size_new *= OT_VECTOR_GROW_RATIO;
218
219 /* preallocate vectors to hold all peers */
220 for (bucket = 0; bucket < num_buckets_new; ++bucket) {
221 bucket_list_new[bucket].space = bucket_size_new;
222 bucket_list_new[bucket].data = malloc(bucket_size_new * peer_size);
223 if (!bucket_list_new[bucket].data) {
224 vector_clean_list(bucket_list_new, num_buckets_new);
225 return;
226 }
227 }
228
229 /* Now sort them into the correct bucket */
230 for (bucket = 0; bucket < num_buckets_old; ++bucket) {
231 ot_peer *peers_old = bucket_list_old[bucket].data;
232 size_t peer_count_old = bucket_list_old[bucket].size;
233 while (peer_count_old--) {
234 ot_vector *bucket_dest = bucket_list_new;
235 if (num_buckets_new > 1)
236 bucket_dest += vector_hash_peer(peers_old, OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size), num_buckets_new);
237 if (bucket_dest->size + 1 > bucket_dest->space) {
238 void *tmp = realloc(bucket_dest->data, peer_size * OT_VECTOR_GROW_RATIO * bucket_dest->space);
239 if (!tmp) {
240 vector_clean_list(bucket_list_new, num_buckets_new);
241 return;
242 }
243 bucket_dest->data = tmp;
244 bucket_dest->space *= OT_VECTOR_GROW_RATIO;
245 }
246 memcpy((ot_peer *)bucket_dest->data + peer_size * bucket_dest->size++, peers_old, peer_size);
247 peers_old += peer_size;
248 }
249 }
250
251 /* Now sort each bucket to later allow bsearch */
252 for (bucket = 0; bucket < num_buckets_new; ++bucket)
253 qsort(bucket_list_new[bucket].data, bucket_list_new[bucket].size, peer_size, sort_func);
254
255 /* Everything worked fine. Now link new bucket_list to the vector */
256 if (OT_VECTOR_HASBUCKETS(peer_vector))
257 vector_clean_list((ot_vector *)peer_vector->data, peer_vector->size);
258 else
259 free(peer_vector->data);
260
261 if (num_buckets_new > 1) {
262 peer_vector->data = bucket_list_new;
263 peer_vector->size = num_buckets_new;
264 peer_vector->space = 0; /* Magic marker for "is list of buckets" */
265 } else {
266 peer_vector->data = bucket_list_new->data;
267 peer_vector->size = bucket_list_new->size;
268 peer_vector->space = bucket_list_new->space;
269 free(bucket_list_new);
270 }
271}
272
273void vector_fixup_peers(ot_vector *vector, size_t peer_size) {
274 int need_fix = 0;
275
276 if (!vector->size) {
277 free(vector->data);
278 vector->data = NULL;
279 vector->space = 0;
280 return;
281 }
282
283 while ((vector->size * OT_VECTOR_SHRINK_THRESH < vector->space) && (vector->space >= OT_VECTOR_SHRINK_RATIO * OT_VECTOR_MIN_MEMBERS)) {
284 vector->space /= OT_VECTOR_SHRINK_RATIO;
285 need_fix++;
286 }
287 if (need_fix) {
288 void *new_data = realloc(vector->data, vector->space * peer_size);
289 if (new_data)
290 vector->data = new_data;
291 }
292}
diff --git a/src/ot_vector.h b/src/ot_vector.h
new file mode 100644
index 0000000..1a73fcf
--- /dev/null
+++ b/src/ot_vector.h
@@ -0,0 +1,39 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_VECTOR_H__
5#define OT_VECTOR_H__
6
7#include <stddef.h>
8
9/* These defines control vectors behaviour */
10#define OT_VECTOR_MIN_MEMBERS 2
11#define OT_VECTOR_GROW_RATIO 2
12#define OT_VECTOR_SHRINK_THRESH 4
13#define OT_VECTOR_SHRINK_RATIO 2
14
15#define OT_PEER_BUCKET_MINCOUNT 512
16#define OT_PEER_BUCKET_MAXCOUNT 256
17
18typedef struct {
19 void *data;
20 size_t size;
21 size_t space;
22} ot_vector;
23
24/* trackerlogic.h needs ot_vector, break circular dependency here */
25#include "trackerlogic.h"
26
27void *vector_binary_search(const void *const key, const void *base, const size_t member_count, const size_t member_size, size_t compare_size, int *exactmatch);
28void *vector_find_or_insert(ot_vector *vector, void *key, size_t member_size, size_t compare_size, int *exactmatch);
29ot_peer *vector_find_or_insert_peer(ot_vector *vector, ot_peer const *peer, size_t peer_size, int *exactmatch);
30
31int vector_remove_peer(ot_vector *vector, ot_peer const *peer, size_t peer_size);
32void vector_remove_torrent(ot_vector *vector, ot_torrent *match);
33
34/* For ot_clean.c */
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);
37void vector_clean_list(ot_vector *vector, size_t num_buckets);
38
39#endif
diff --git a/src/ot_worker.c b/src/ot_worker.c
new file mode 100644
index 0000000..ef50945
--- /dev/null
+++ b/src/ot_worker.c
@@ -0,0 +1,73 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "ot_worker.h"
13#include "trackerlogic.h"
14
15static struct ot_worker **g_workers;
16static size_t g_worker_count;
17
18/* Everything a worker needs doing around its own loop, in one place, so that
19 a new kind of worker cannot miss a piece of it. */
20static void *worker_trampoline(void *args) {
21 struct ot_worker *me = args;
22
23 if (workstruct_init(&me->ws, G_INBUF_SIZE) == -1)
24 fprintf(stderr, "Warning: a worker could not get its buffers and will not run.\n");
25 else {
26 me->run(me);
27 workstruct_deinit(&me->ws);
28 }
29
30 atomic_store(&me->left, 1);
31 return NULL;
32}
33
34int worker_start(ot_worker_run run, int64_t sock) {
35 struct ot_worker **grown = realloc(g_workers, (g_worker_count + 1) * sizeof(*g_workers));
36 struct ot_worker *worker;
37
38 if (!grown)
39 return -1;
40 g_workers = grown;
41
42 if (!(worker = calloc(1, sizeof(*worker))))
43 return -1;
44 worker->sock = sock;
45 worker->run = run;
46
47 if (pthread_create(&worker->thread, NULL, worker_trampoline, worker)) {
48 free(worker);
49 return -1;
50 }
51 g_workers[g_worker_count++] = worker;
52 return 0;
53}
54
55void worker_stop_all(void) {
56 size_t i;
57
58 for (i = 0; i < g_worker_count; ++i) {
59 struct ot_worker *worker = g_workers[i];
60
61 /* Repeated because a signal only interrupts a call already under way */
62 while (!atomic_load(&worker->left)) {
63 pthread_kill(worker->thread, OT_SIGNAL_WAKE);
64 usleep(1000);
65 }
66 pthread_join(worker->thread, NULL);
67 free(worker);
68 }
69
70 free(g_workers);
71 g_workers = NULL;
72 g_worker_count = 0;
73}
diff --git a/src/ot_worker.h b/src/ot_worker.h
new file mode 100644
index 0000000..4954773
--- /dev/null
+++ b/src/ot_worker.h
@@ -0,0 +1,37 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_WORKER_H__
5#define OT_WORKER_H__
6
7#include <pthread.h>
8#include <stdatomic.h>
9#include <stdint.h>
10
11#include "trackerlogic.h"
12
13struct ot_worker;
14
15/* What a worker does between being started and being told to stop. It reads
16 worker->sock and works out of worker->ws; everything around it, from the
17 buffers to the counters to saying goodbye, is handled here. */
18typedef void (*ot_worker_run)(struct ot_worker *worker);
19
20/* A thread that serves requests on a socket of its own, with the buffers and
21 counters it needs. Each is allocated on its own, so taking on another one
22 never moves the record a running worker holds. */
23struct ot_worker {
24 pthread_t thread;
25 _Atomic int left;
26 int64_t sock;
27 ot_worker_run run;
28 struct ot_workstruct ws;
29};
30
31/* Start one. Returns -1 if it could not be started. */
32int worker_start(ot_worker_run run, int64_t sock);
33
34/* Wake every worker until it has left, then join it */
35void worker_stop_all(void);
36
37#endif
diff --git a/src/ot_workqueue.c b/src/ot_workqueue.c
new file mode 100644
index 0000000..cdefddc
--- /dev/null
+++ b/src/ot_workqueue.c
@@ -0,0 +1,248 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdlib.h>
7#include <string.h>
8#include <sys/uio.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "ot_fdstate.h"
13#include "ot_iovec.h"
14#include "ot_workqueue.h"
15#include "trackerlogic.h"
16
17/* Pushing a result wakes the thread that will send it */
18extern int g_self_pipe[2];
19
20struct ot_task {
21 ot_taskid taskid;
22 ot_tasktype tasktype;
23 int64_t sock;
24 uint32_t generation;
25 size_t iovec_entries;
26 struct iovec *iovec;
27 struct ot_task *next;
28};
29
30static ot_taskid next_free_taskid = 1;
31static struct ot_task *tasklist;
32static pthread_mutex_t tasklist_mutex;
33static pthread_cond_t tasklist_being_filled;
34
35int workqueue_pushtask(int64_t sock, ot_tasktype tasktype) {
36 struct ot_task **tmptask, *task;
37
38 task = malloc(sizeof(struct ot_task));
39 if (!task)
40 return -1;
41
42 task->taskid = 0;
43 task->tasktype = tasktype;
44 task->sock = sock;
45 task->generation = fdstate_generation((int)sock);
46 task->iovec_entries = 0;
47 task->iovec = NULL;
48 task->next = 0;
49
50 /* Want exclusive access to tasklist */
51 pthread_mutex_lock(&tasklist_mutex);
52
53 /* Skip to end of list */
54 tmptask = &tasklist;
55 while (*tmptask)
56 tmptask = &(*tmptask)->next;
57 *tmptask = task;
58
59 /* Inform waiting workers and release lock */
60 pthread_cond_broadcast(&tasklist_being_filled);
61 pthread_mutex_unlock(&tasklist_mutex);
62 return 0;
63}
64
65void workqueue_canceltask(int64_t sock) {
66 struct ot_task **task;
67
68 /* Want exclusive access to tasklist */
69 pthread_mutex_lock(&tasklist_mutex);
70
71 task = &tasklist;
72 while (*task) {
73 struct ot_task *ptask = *task;
74 size_t i;
75
76 if (ptask->sock != sock) {
77 task = &ptask->next;
78 continue;
79 }
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
90 /* Release lock */
91 pthread_mutex_unlock(&tasklist_mutex);
92}
93
94ot_taskid workqueue_poptask(ot_tasktype *tasktype) {
95 struct ot_task *task;
96 ot_taskid taskid = 0;
97
98 /* Want exclusive access to tasklist */
99 pthread_mutex_lock(&tasklist_mutex);
100
101 while (!taskid) {
102 /* Skip to the first unassigned task this worker wants to do */
103 for (task = tasklist; task; task = task->next)
104 if (!task->taskid && (TASK_CLASS_MASK & task->tasktype) == *tasktype) {
105 /* If we found an outstanding task, assign a taskid to it
106 and leave the loop */
107 task->taskid = taskid = ++next_free_taskid;
108 *tasktype = task->tasktype;
109 break;
110 }
111
112 /* Wait until the next task is being fed, unless the tracker is on its
113 way out, in which case the worker is meant to leave rather than wait */
114 if (!taskid) {
115 if (!g_opentracker_running)
116 break;
117 pthread_cond_wait(&tasklist_being_filled, &tasklist_mutex);
118 }
119 }
120
121 /* Release lock */
122 pthread_mutex_unlock(&tasklist_mutex);
123
124 return taskid;
125}
126
127void workqueue_pushsuccess(ot_taskid taskid) {
128 struct ot_task **task;
129
130 /* Want exclusive access to tasklist */
131 pthread_mutex_lock(&tasklist_mutex);
132
133 for (task = &tasklist; *task; task = &((*task)->next))
134 if ((*task)->taskid == taskid) {
135 struct ot_task *ptask = *task;
136 *task = (*task)->next;
137 free(ptask);
138 break;
139 }
140
141 /* Release lock */
142 pthread_mutex_unlock(&tasklist_mutex);
143}
144
145int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovec) {
146 struct ot_task *task;
147 const char byte = 'o';
148
149 /* Want exclusive access to tasklist */
150 pthread_mutex_lock(&tasklist_mutex);
151
152 for (task = tasklist; task; task = task->next)
153 if (task->taskid == taskid) {
154 task->iovec_entries = iovec_entries;
155 task->iovec = iovec;
156 task->tasktype = TASK_DONE;
157 break;
158 }
159
160 /* Release lock */
161 pthread_mutex_unlock(&tasklist_mutex);
162
163 /* A full pipe has already done this nudge's job, so a failure is fine */
164 (void)!write(g_self_pipe[1], &byte, 1);
165
166 /* Indicate whether the worker has to throw away results */
167 return task ? 0 : -1;
168}
169
170int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec) {
171 struct ot_task *task;
172 const char byte = 'o';
173
174 /* Want exclusive access to tasklist */
175 pthread_mutex_lock(&tasklist_mutex);
176
177 for (task = tasklist; task; task = task->next)
178 if (task->taskid == taskid) {
179 if (iovec) {
180 if (iovec_append(&task->iovec_entries, &task->iovec, iovec))
181 task->tasktype = TASK_DONE_PARTIAL;
182 else
183 task = NULL;
184 } else
185 task->tasktype = TASK_DONE;
186 break;
187 }
188
189 /* Release lock */
190 pthread_mutex_unlock(&tasklist_mutex);
191
192 /* A full pipe has already done this nudge's job, so a failure is fine */
193 (void)!write(g_self_pipe[1], &byte, 1);
194
195 /* Indicate whether the worker has to throw away results */
196 return task ? 0 : -1;
197}
198
199int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is_partial, uint32_t *generation) {
200 struct ot_task **task;
201 int64_t sock = -1;
202
203 *is_partial = 0;
204
205 /* Want exclusive access to tasklist */
206 pthread_mutex_lock(&tasklist_mutex);
207
208 for (task = &tasklist; *task; task = &((*task)->next))
209 if (((*task)->tasktype & TASK_CLASS_MASK) == TASK_DONE) {
210 struct ot_task *ptask = *task;
211 *iovec_entries = ptask->iovec_entries;
212 *iovec = ptask->iovec;
213 sock = ptask->sock;
214 *generation = ptask->generation;
215
216 if ((*task)->tasktype == TASK_DONE) {
217 *task = ptask->next;
218 free(ptask);
219 } else {
220 ptask->iovec_entries = 0;
221 ptask->iovec = NULL;
222 *is_partial = 1;
223 /* Prevent task from showing up immediately again unless new data was added */
224 (*task)->tasktype = TASK_FULLSCRAPE;
225 }
226 break;
227 }
228
229 /* Release lock */
230 pthread_mutex_unlock(&tasklist_mutex);
231 return sock;
232}
233
234void workqueue_wakeall(void) {
235 pthread_mutex_lock(&tasklist_mutex);
236 pthread_cond_broadcast(&tasklist_being_filled);
237 pthread_mutex_unlock(&tasklist_mutex);
238}
239
240void workqueue_init(void) {
241 pthread_mutex_init(&tasklist_mutex, NULL);
242 pthread_cond_init(&tasklist_being_filled, NULL);
243}
244
245void workqueue_deinit(void) {
246 pthread_mutex_destroy(&tasklist_mutex);
247 pthread_cond_destroy(&tasklist_being_filled);
248}
diff --git a/src/ot_workqueue.h b/src/ot_workqueue.h
new file mode 100644
index 0000000..982292e
--- /dev/null
+++ b/src/ot_workqueue.h
@@ -0,0 +1,73 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_WORKQUEUE_H__
5#define OT_WORKQUEUE_H__
6
7#include <stdint.h>
8#include <sys/uio.h>
9
10#include "trackerlogic.h"
11
12/* Work the tracker hands to a thread of its own: a full scrape or an
13 expensive stats page, which take too long to build while a client waits.
14 The task goes in here, the reply comes back out. */
15
16typedef enum {
17 TASK_STATS_CONNS = 0x0001,
18 TASK_STATS_TCP = 0x0002,
19 TASK_STATS_UDP = 0x0003,
20 TASK_STATS_SCRAPE = 0x0004,
21 TASK_STATS_FULLSCRAPE = 0x0005,
22 TASK_STATS_TPB = 0x0006,
23 TASK_STATS_HTTPERRORS = 0x0007,
24 TASK_STATS_RENEW = 0x000a,
25 TASK_STATS_SYNCS = 0x000b,
26 TASK_STATS_COMPLETED = 0x000c,
27 TASK_STATS_NUMWANTS = 0x000d,
28
29 TASK_STATS = 0x0100, /* Mask */
30 TASK_STATS_TORRENTS = 0x0101,
31 TASK_STATS_PEERS = 0x0102,
32 TASK_STATS_TOP10 = 0x0104,
33 TASK_STATS_TOP100 = 0x0105,
34 TASK_STATS_EVERYTHING = 0x0106,
35 TASK_STATS_WOODPECKERS = 0x0108,
36
37 TASK_FULLSCRAPE = 0x0200, /* Default mode */
38 TASK_FULLSCRAPE_TPB_BINARY = 0x0201,
39 TASK_FULLSCRAPE_TPB_ASCII = 0x0202,
40 TASK_FULLSCRAPE_TPB_ASCII_PLUS = 0x0203,
41 TASK_FULLSCRAPE_TPB_URLENCODED = 0x0204,
42 TASK_FULLSCRAPE_TRACKERSTATE = 0x0205,
43
44 TASK_DMEM = 0x0300,
45
46 TASK_DONE = 0x0f00,
47 TASK_DONE_PARTIAL = 0x0f01,
48
49 TASK_FLAG_GZIP = 0x1000,
50 TASK_FLAG_BZIP2 = 0x2000,
51 TASK_FLAG_ZSTD = 0x4000,
52 TASK_FLAG_CHUNKED = 0x8000,
53
54 TASK_TASK_MASK = 0x0fff,
55 TASK_CLASS_MASK = 0x0f00,
56 TASK_FLAGS_MASK = 0xf000
57} ot_tasktype;
58
59typedef unsigned long ot_taskid;
60
61int workqueue_pushtask(int64_t sock, ot_tasktype tasktype);
62void workqueue_canceltask(int64_t sock);
63void workqueue_pushsuccess(ot_taskid taskid);
64ot_taskid workqueue_poptask(ot_tasktype *tasktype);
65int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovector);
66int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec);
67int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovector, int *is_partial, uint32_t *generation);
68
69void workqueue_init(void);
70void workqueue_deinit(void);
71void workqueue_wakeall(void);
72
73#endif
diff --git a/src/proxy.c b/src/proxy.c
new file mode 100644
index 0000000..8589db5
--- /dev/null
+++ b/src/proxy.c
@@ -0,0 +1,871 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* This relays sync traffic between trackers, and between multicast domains
5 that have no route to each other, so that no tracker has to reach out to
6 the outside world by itself. Defunc. */
7
8/* System */
9#include <arpa/inet.h>
10#include <ctype.h>
11#include <errno.h>
12#include <pthread.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
18
19/* Libowfat */
20#include "io.h"
21
22/* Opentracker */
23#include "ot_batch.h"
24#include "ot_fdstate.h"
25#include "ot_ip.h"
26#include "ot_mutex.h"
27#include "ot_random.h"
28#include "ot_scan.h"
29#include "ot_socket.h"
30#include "ot_stats.h"
31#include "ot_vector.h"
32#include "trackerlogic.h"
33
34#include "ot_livesync.h"
35
36ot_ip6 g_serverip;
37uint16_t g_serverport = 9009;
38uint32_t g_tracker_id;
39ot_ip6 groupip_1 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 224, 0, 23, 5};
40int g_self_pipe[2];
41
42/* If you have more than 10 peers, don't use this proxy
43 Use 20 slots for 10 peers to have room for 10 incoming connection slots
44 */
45#define MAX_PEERS 20
46
47#define LIVESYNC_INCOMING_BUFFSIZE (256 * 256)
48#define STREAMSYNC_OUTGOING_BUFFSIZE (256 * 256)
49
50#define LIVESYNC_OUTGOING_BUFFSIZE_PEERS 1480
51#define LIVESYNC_OUTGOING_WATERMARK_PEERS (sizeof(ot_peer) + sizeof(ot_hash))
52#define LIVESYNC_MAXDELAY 15 /* seconds */
53
54/* The amount of time a complete sync cycle should take */
55#define OT_SYNC_INTERVAL_MINUTES 2
56
57/* So after each bucket wait 1 / OT_BUCKET_COUNT intervals */
58#define OT_SYNC_SLEEP (((OT_SYNC_INTERVAL_MINUTES) * 60 * 1000000) / (OT_BUCKET_COUNT))
59
60enum { OT_SYNC_PEER4, OT_SYNC_PEER6 };
61enum { FLAG_SERVERSOCKET = 1 };
62
63/* For incoming packets */
64static int g_socket_in = -1;
65static uint8_t g_inbuffer[LIVESYNC_INCOMING_BUFFSIZE];
66
67/* For outgoing packets */
68static int g_socket_out = -1;
69static uint8_t g_peerbuffer_start[LIVESYNC_OUTGOING_BUFFSIZE_PEERS];
70static uint8_t *g_peerbuffer_pos;
71static uint8_t *g_peerbuffer_highwater = g_peerbuffer_start + LIVESYNC_OUTGOING_BUFFSIZE_PEERS - LIVESYNC_OUTGOING_WATERMARK_PEERS;
72static ot_time g_next_packet_time;
73
74static void *livesync_worker(void *args);
75static void *streamsync_worker(void *args);
76static void livesync_proxytell(uint8_t prefix, uint8_t *info_hash, uint8_t *peer);
77
78void exerr(const char *message) {
79 fprintf(stderr, "%s\n", message);
80 exit(111);
81}
82
83void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FLAG proto, uintptr_t event_data) {
84 (void)ws;
85 (void)event;
86 (void)proto;
87 (void)event_data;
88}
89
90void livesync_bind_mcast(ot_ip6 ip, uint16_t port) {
91 if (!ip_is_v4mapped(ip))
92 exerr("v6 mcast support not yet available.");
93
94 if (g_socket_in != -1)
95 exerr("Error: Livesync listen ip specified twice.");
96
97 if ((g_socket_in = socket_mcast_join(groupip_1, ip, port)) == -1)
98 exerr("Error: Cant bind live sync incoming socket.");
99
100 if ((g_socket_out = socket_mcast_bind(ip, port, 1)) == -1)
101 exerr("Error: Cant bind live sync outgoing socket.");
102}
103
104size_t add_peer_to_torrent_proxy(ot_hash hash, ot_peer *peer, size_t peer_size) {
105 int exactmatch;
106 ot_torrent *torrent;
107 ot_peerlist *peer_list;
108 ot_peer *peer_dest;
109 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash);
110 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
111
112 torrent = vector_find_or_insert(torrents_list, (void *)hash, sizeof(ot_torrent), compare_size, &exactmatch);
113 if (!torrent)
114 return -1;
115
116 if (!exactmatch) {
117 /* Create a new torrent entry, then */
118 memcpy(torrent->hash, hash, sizeof(ot_hash));
119
120 if (!(torrent->peer_list6 = malloc(sizeof(ot_peerlist))) || !(torrent->peer_list4 = malloc(sizeof(ot_peerlist)))) {
121 vector_remove_torrent(torrents_list, torrent);
122 mutex_bucket_unlock_by_hash(hash, 0);
123 return -1;
124 }
125
126 memset(torrent->peer_list6, 0, sizeof(ot_peerlist));
127 memset(torrent->peer_list4, 0, sizeof(ot_peerlist));
128 }
129
130 peer_list = peer_size == OT_PEER_SIZE6 ? torrent->peer_list6 : torrent->peer_list4;
131
132 /* Check for peer in torrent */
133 peer_dest = vector_find_or_insert_peer(&(peer_list->peers), peer, peer_size, &exactmatch);
134 if (!peer_dest) {
135 mutex_bucket_unlock_by_hash(hash, 0);
136 return -1;
137 }
138 /* Tell peer that it's fresh */
139 OT_PEERTIME(peer, peer_size) = 0;
140
141 /* If we hadn't had a match create peer there */
142 if (!exactmatch) {
143 peer_list->peer_count++;
144 if (OT_PEERFLAG_D(peer, peer_size) & PEER_FLAG_SEEDING)
145 peer_list->seed_count++;
146 }
147 memcpy(peer_dest, peer, peer_size);
148 mutex_bucket_unlock_by_hash(hash, 0);
149 return 0;
150}
151
152size_t remove_peer_from_torrent_proxy(ot_hash hash, ot_peer *peer, size_t peer_size) {
153 int exactmatch;
154 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash);
155 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
156
157 if (exactmatch) {
158 ot_peerlist *peer_list = peer_list = peer_size == OT_PEER_SIZE6 ? torrent->peer_list6 : torrent->peer_list4;
159 switch (vector_remove_peer(&peer_list->peers, peer, peer_size)) {
160 case 2:
161 peer_list->seed_count--; /* Intentional fallthrough */
162 case 1:
163 peer_list->peer_count--; /* Intentional fallthrough */
164 default:
165 break;
166 }
167 }
168
169 mutex_bucket_unlock_by_hash(hash, 0);
170 return 0;
171}
172
173void free_peerlist(ot_peerlist *peer_list) {
174 if (peer_list->peers.data) {
175 if (OT_PEERLIST_HASBUCKETS(peer_list)) {
176 ot_vector *bucket_list = (ot_vector *)(peer_list->peers.data);
177
178 while (peer_list->peers.size--)
179 free(bucket_list++->data);
180 }
181 free(peer_list->peers.data);
182 }
183 free(peer_list);
184}
185
186static void livesync_handle_peersync(ssize_t datalen, size_t peer_size) {
187 int off = sizeof(g_tracker_id) + sizeof(uint32_t);
188
189 fprintf(stderr, ".");
190
191 while ((ssize_t)(off + sizeof(ot_hash) + peer_size) <= datalen) {
192 ot_peer *peer = (ot_peer *)(g_inbuffer + off + sizeof(ot_hash));
193 ot_hash *hash = (ot_hash *)(g_inbuffer + off);
194
195 if (OT_PEERFLAG_D(peer, peer_size) & PEER_FLAG_STOPPED)
196 remove_peer_from_torrent_proxy(*hash, peer, peer_size);
197 else
198 add_peer_to_torrent_proxy(*hash, peer, peer_size);
199
200 off += sizeof(ot_hash) + peer_size;
201 }
202}
203
204int usage(char *self) {
205 fprintf(stderr, "Usage: %s -L <livesync_iface_ip> -l <listenip>:<listenport> -c <connectip>:<connectport>\n", self);
206 return 0;
207}
208
209enum {
210 FLAG_OUTGOING = 0x80,
211
212 FLAG_DISCONNECTED = 0x00,
213 FLAG_CONNECTING = 0x01,
214 FLAG_WAITTRACKERID = 0x02,
215 FLAG_CONNECTED = 0x03,
216
217 FLAG_MASK = 0x07
218};
219
220#define PROXYPEER_NEEDSCONNECT(flag) ((flag) == FLAG_OUTGOING)
221#define PROXYPEER_ISCONNECTED(flag) (((flag) & FLAG_MASK) == FLAG_CONNECTED)
222#define PROXYPEER_SETDISCONNECTED(flag) (flag) = (((flag) & FLAG_OUTGOING) | FLAG_DISCONNECTED)
223#define PROXYPEER_SETCONNECTING(flag) (flag) = (((flag) & FLAG_OUTGOING) | FLAG_CONNECTING)
224#define PROXYPEER_SETWAITTRACKERID(flag) (flag) = (((flag) & FLAG_OUTGOING) | FLAG_WAITTRACKERID)
225#define PROXYPEER_SETCONNECTED(flag) (flag) = (((flag) & FLAG_OUTGOING) | FLAG_CONNECTED)
226
227typedef struct {
228 int state; /* Whether we want to connect, how far our handshake is, etc. */
229 ot_ip6 ip; /* The peer to connect to */
230 uint16_t port; /* The peers port */
231 uint8_t indata[8192 * 16]; /* Any data not processed yet */
232 size_t indata_length; /* Length of unprocessed data */
233 uint32_t tracker_id; /* How the other end greeted */
234 int64_t fd; /* A file handle, if connected, <= 0 is disconnected (0 initially, -1 else) */
235 ot_batch outdata; /* The batch containing our sync data */
236
237 size_t packet_tcount; /* Number of unprocessed torrents in packet we currently receive */
238 uint8_t packet_tprefix; /* Prefix byte for all torrents in current packet */
239 uint8_t packet_type; /* Type of current packet */
240 uint32_t packet_tid; /* Tracker id for current packet */
241
242} proxy_peer;
243static void process_indata(proxy_peer *peer);
244
245void reset_info_block(proxy_peer *peer) {
246 peer->indata_length = 0;
247 peer->tracker_id = 0;
248 peer->fd = -1;
249 peer->packet_tcount = 0;
250 batch_reset(&peer->outdata);
251 PROXYPEER_SETDISCONNECTED(peer->state);
252}
253
254/* Number of connections to peers
255 * If a peer's IP is set, we try to reconnect, when the connection drops
256 * If we already have a connected tracker_id in our records for an _incoming_ connection, drop it
257 * Multiple connections to/from the same ip are okay, if tracker_id doesn't match
258 * Reconnect attempts occur only twice a minute
259 */
260static size_t g_connection_count;
261static ot_time g_connection_reconn;
262static proxy_peer g_connections[MAX_PEERS];
263
264static void handle_reconnects(void) {
265 size_t i;
266 for (i = 0; i < g_connection_count; ++i)
267 if (PROXYPEER_NEEDSCONNECT(g_connections[i].state)) {
268 int64_t newfd = socket_tcp_connect(g_serverip, g_serverport, g_connections[i].ip, g_connections[i].port);
269 fprintf(stderr, "(Re)connecting to peer...");
270 if (newfd == -1)
271 continue; /* No socket for you */
272 io_fd(newfd);
273 io_wantwrite(newfd); /* So we will be informed when it is connected */
274 fdstate_open(newfd, g_connections + i, 0);
275
276 /* Prepare connection info block */
277 reset_info_block(g_connections + i);
278 g_connections[i].fd = newfd;
279 PROXYPEER_SETCONNECTING(g_connections[i].state);
280 }
281 g_connection_reconn = time(NULL) + 30;
282}
283
284/* Handle incoming connection requests, check against whitelist */
285static void handle_accept(int64_t serversocket) {
286 int64_t newfd;
287 ot_ip6 ip;
288 uint16_t port;
289
290 while ((newfd = socket_accept(serversocket, ip, &port)) != -1) {
291
292 /* XXX some access control */
293
294 /* Put fd into a non-blocking mode */
295 io_nonblock(newfd);
296
297 if (!io_fd(newfd))
298 io_close(newfd);
299 else {
300 /* Find a new home for our incoming connection */
301 int i;
302 for (i = 0; i < MAX_PEERS; ++i)
303 if (g_connections[i].state == FLAG_DISCONNECTED)
304 break;
305 if (i == MAX_PEERS) {
306 fprintf(stderr, "No room for incoming connection.");
307 close(newfd);
308 continue;
309 }
310
311 /* Prepare connection info block */
312 reset_info_block(g_connections + i);
313 PROXYPEER_SETCONNECTING(g_connections[i].state);
314 g_connections[i].port = port;
315 g_connections[i].fd = newfd;
316
317 fdstate_open(newfd, g_connections + i, 0);
318
319 /* We expect the connecting side to begin with its tracker_id */
320 io_wantread(newfd);
321 }
322 }
323
324 return;
325}
326
327/* New sync data on the stream */
328static void handle_read(int64_t peersocket) {
329 int i;
330 int64_t datalen;
331 uint32_t tracker_id;
332 proxy_peer *peer = fdstate_cookie(peersocket);
333
334 if (!peer) {
335 /* Can't happen ;) */
336 io_close(peersocket);
337 return;
338 }
339 switch (peer->state & FLAG_MASK) {
340 case FLAG_DISCONNECTED:
341 io_close(peersocket);
342 break; /* Shouldnt happen */
343 case FLAG_CONNECTING:
344 case FLAG_WAITTRACKERID:
345 /* We want at least the first four bytes to come at once, to avoid keeping extra states (for now)
346 This also catches 0 bytes reads == EOF and negative values, denoting connection errors */
347 if (io_tryread(peersocket, (void *)&tracker_id, sizeof(tracker_id)) != sizeof(tracker_id))
348 goto close_socket;
349
350 /* See, if we already have a connection to that peer */
351 for (i = 0; i < MAX_PEERS; ++i)
352 if ((g_connections[i].state & FLAG_MASK) == FLAG_CONNECTED && g_connections[i].tracker_id == tracker_id) {
353 fprintf(stderr, "Peer already connected. Closing connection.\n");
354 goto close_socket;
355 }
356
357 /* Also no need for soliloquy */
358 if (tracker_id == g_tracker_id)
359 goto close_socket;
360
361 /* The new connection is good, send our tracker_id on incoming connections */
362 if (peer->state == FLAG_CONNECTING)
363 if (io_trywrite(peersocket, (void *)&g_tracker_id, sizeof(g_tracker_id)) != sizeof(g_tracker_id))
364 goto close_socket;
365
366 peer->tracker_id = tracker_id;
367 PROXYPEER_SETCONNECTED(peer->state);
368
369 if (peer->state & FLAG_OUTGOING)
370 fprintf(stderr, "succeeded.\n");
371 else
372 fprintf(stderr, "Incoming connection successful.\n");
373
374 break;
375 close_socket:
376 fprintf(stderr, "Handshake incomplete, closing socket\n");
377 io_close(peersocket);
378 reset_info_block(peer);
379 break;
380 case FLAG_CONNECTED:
381 /* Here we acutally expect data from peer
382 indata_length should be less than 20+256*7 bytes, for incomplete torrent entries */
383 datalen = io_tryread(peersocket, (void *)(peer->indata + peer->indata_length), sizeof(peer->indata) - peer->indata_length);
384 if (!datalen || datalen < -1) {
385 fprintf(stderr, "Connection closed by remote peer.\n");
386 io_close(peersocket);
387 reset_info_block(peer);
388 } else if (datalen > 0) {
389 peer->indata_length += datalen;
390 process_indata(peer);
391 }
392 break;
393 }
394}
395
396/* Can write new sync data to the stream */
397static void handle_write(int64_t peersocket) {
398 proxy_peer *peer = fdstate_cookie(peersocket);
399
400 if (!peer) {
401 /* Can't happen ;) */
402 io_close(peersocket);
403 return;
404 }
405
406 switch (peer->state & FLAG_MASK) {
407 case FLAG_DISCONNECTED:
408 default: /* Should not happen */
409 io_close(peersocket);
410 break;
411 case FLAG_CONNECTING:
412 /* Ensure that the connection is established and handle connection error */
413 if (peer->state & FLAG_OUTGOING && !socket_is_connected(peersocket)) {
414 fprintf(stderr, "failed\n");
415 reset_info_block(peer);
416 io_close(peersocket);
417 break;
418 }
419
420 if (io_trywrite(peersocket, (void *)&g_tracker_id, sizeof(g_tracker_id)) == sizeof(g_tracker_id)) {
421 PROXYPEER_SETWAITTRACKERID(peer->state);
422 io_dontwantwrite(peersocket);
423 io_wantread(peersocket);
424 } else {
425 fprintf(stderr, "Handshake incomplete, closing socket\n");
426 io_close(peersocket);
427 reset_info_block(peer);
428 }
429 break;
430 case FLAG_CONNECTED:
431 switch (batch_send(peersocket, &peer->outdata)) {
432 case BATCH_DONE:
433 io_dontwantwrite(peersocket);
434 break;
435 case BATCH_FAILED:
436 io_close(peersocket);
437 reset_info_block(peer);
438 break;
439 default: /* Normal operation or eagain */
440 break;
441 }
442 break;
443 }
444
445 return;
446}
447
448static void server_mainloop() {
449 int64_t sock;
450 uint32_t packet_type;
451
452 /* inlined livesync_init() */
453 memset(g_peerbuffer_start, 0, sizeof(g_peerbuffer_start));
454 g_peerbuffer_pos = g_peerbuffer_start;
455 memcpy(g_peerbuffer_pos, &g_tracker_id, sizeof(g_tracker_id));
456 packet_type = htonl(OT_SYNC_PEER);
457 memcpy(g_peerbuffer_pos + sizeof(g_tracker_id), &packet_type, sizeof(packet_type));
458 g_peerbuffer_pos += sizeof(g_tracker_id) + sizeof(uint32_t);
459 g_next_packet_time = time(NULL) + LIVESYNC_MAXDELAY;
460
461 while (1) {
462 /* See if we need to connect to anyone */
463 if (time(NULL) > g_connection_reconn)
464 handle_reconnects();
465
466 /* Wait for io events until next approx reconn check time */
467 io_waituntil2(30 * 1000);
468
469 /* Loop over readable sockets */
470 while ((sock = io_canread()) != -1) {
471 const void *cookie = fdstate_cookie(sock);
472 if ((uintptr_t)cookie == FLAG_SERVERSOCKET)
473 handle_accept(sock);
474 else
475 handle_read(sock);
476 }
477
478 /* Loop over writable sockets */
479 while ((sock = io_canwrite()) != -1)
480 handle_write(sock);
481
482 livesync_ticker();
483 }
484}
485
486static void panic(const char *routine) {
487 fprintf(stderr, "%s: %s\n", routine, strerror(errno));
488 exit(111);
489}
490
491static int64_t ot_try_bind(ot_ip6 ip, uint16_t port) {
492 int64_t sock = socket_tcp_listen(ip, port, SOCKET_EXCLUSIVE);
493
494 if (sock == -1)
495 panic("socket_tcp_listen");
496
497 if (!io_fd(sock))
498 panic("io_fd");
499
500 fdstate_open(sock, (void *)FLAG_SERVERSOCKET, 0);
501 io_wantread(sock);
502 return sock;
503}
504
505static int scan_ip6_port(const char *src, ot_ip6 ip, uint16_t *port) {
506 const char *s = src;
507 uint64_t value;
508 int off, bracket = 0;
509 while (isspace(*s))
510 ++s;
511 if (*s == '[')
512 ++s, ++bracket; /* for v6 style notation */
513 if (!(off = ip_parse(s, ip)))
514 return 0;
515 s += off;
516 if (*s == 0 || isspace(*s))
517 return s - src;
518 if (*s == ']' && bracket)
519 ++s;
520 if (!ip_is_v4mapped(ip)) {
521 if ((bracket && *(s) != ':') || (*(s) != '.'))
522 return 0;
523 s++;
524 } else {
525 if (*(s++) != ':')
526 return 0;
527 }
528 if (!(off = scan_uint(s, &value, 65535)))
529 return 0;
530 *port = (uint16_t)value;
531 return off + s - src;
532}
533
534int main(int argc, char **argv) {
535 static pthread_t sync_in_thread_id;
536 static pthread_t sync_out_thread_id;
537 ot_ip6 serverip;
538 uint16_t tmpport;
539 int scanon = 1, lbound = 0, sbound = 0;
540
541 random_init();
542 if (fdstate_init() == -1)
543 panic("fdstate_init");
544 g_tracker_id = random_uint32();
545
546 while (scanon) {
547 switch (getopt(argc, argv, ":l:c:L:h")) {
548 case -1:
549 scanon = 0;
550 break;
551 case 'l':
552 tmpport = 0;
553 if (!scan_ip6_port(optarg, serverip, &tmpport) || !tmpport) {
554 usage(argv[0]);
555 exit(1);
556 }
557 ot_try_bind(serverip, tmpport);
558 ++sbound;
559 break;
560 case 'c':
561 if (g_connection_count > MAX_PEERS / 2)
562 exerr("Connection limit exceeded.\n");
563 tmpport = 0;
564 if (!scan_ip6_port(optarg, g_connections[g_connection_count].ip, &g_connections[g_connection_count].port) || !g_connections[g_connection_count].port) {
565 usage(argv[0]);
566 exit(1);
567 }
568 g_connections[g_connection_count++].state = FLAG_OUTGOING;
569 break;
570 case 'L':
571 tmpport = 9696;
572 if (!scan_ip6_port(optarg, serverip, &tmpport) || !tmpport) {
573 usage(argv[0]);
574 exit(1);
575 }
576 livesync_bind_mcast(serverip, tmpport);
577 ++lbound;
578 break;
579 default:
580 case '?':
581 usage(argv[0]);
582 exit(1);
583 }
584 }
585
586 if (!lbound)
587 exerr("No livesync port bound.");
588 if (!g_connection_count && !sbound)
589 exerr("No streamsync port bound.");
590 pthread_create(&sync_in_thread_id, NULL, livesync_worker, NULL);
591 pthread_create(&sync_out_thread_id, NULL, streamsync_worker, NULL);
592
593 server_mainloop();
594 return 0;
595}
596
597static void *streamsync_worker(void *args) {
598 (void)args;
599 while (1) {
600 size_t bucket;
601 /* For each bucket... */
602 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
603 /* Get exclusive access to that bucket */
604 ot_vector *torrents_list = mutex_bucket_lock(bucket);
605 size_t tor_offset, count_def = 0, count_one = 0, count_two = 0, count_peers = 0;
606 size_t mem, mem_a = 0, mem_b = 0;
607 uint8_t *ptr = 0, *ptr_a, *ptr_b, *ptr_c;
608
609 if (!torrents_list->size)
610 goto unlock_continue;
611
612 /* For each torrent in this bucket.. */
613 for (tor_offset = 0; tor_offset < torrents_list->size; ++tor_offset) {
614 /* Address torrents members */
615 ot_peerlist *peer_list = (((ot_torrent *)(torrents_list->data))[tor_offset]).peer_list;
616 switch (peer_list->peer_count) {
617 case 2:
618 count_two++;
619 break;
620 case 1:
621 count_one++;
622 break;
623 case 0:
624 break;
625 default:
626 count_def++;
627 count_peers += peer_list->peer_count;
628 }
629 }
630
631 /* Maximal memory requirement: max 3 blocks, max torrents * 20 + max peers * 7 */
632 mem = 3 * (1 + 1 + 2) + (count_one + count_two) * (19 + 1) + count_def * (19 + 8) + (count_one + 2 * count_two + count_peers) * 7;
633
634 fprintf(stderr, "Mem: %zd\n", mem);
635
636 ptr = ptr_a = ptr_b = ptr_c = malloc(mem);
637 if (!ptr)
638 goto unlock_continue;
639
640 if (count_one > 4 || !count_def) {
641 mem_a = 1 + 1 + 2 + count_one * (19 + 7);
642 ptr_b += mem_a;
643 ptr_c += mem_a;
644 ptr_a[0] = 1; /* Offset 0: packet type 1 */
645 ptr_a[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
646 ptr_a[2] = count_one >> 8;
647 ptr_a[3] = count_one & 255;
648 ptr_a += 4;
649 } else
650 count_def += count_one;
651
652 if (count_two > 4 || !count_def) {
653 mem_b = 1 + 1 + 2 + count_two * (19 + 14);
654 ptr_c += mem_b;
655 ptr_b[0] = 2; /* Offset 0: packet type 2 */
656 ptr_b[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
657 ptr_b[2] = count_two >> 8;
658 ptr_b[3] = count_two & 255;
659 ptr_b += 4;
660 } else
661 count_def += count_two;
662
663 if (count_def) {
664 ptr_c[0] = 0; /* Offset 0: packet type 0 */
665 ptr_c[1] = (bucket << 8) >> OT_BUCKET_COUNT_BITS; /* Offset 1: the shared prefix */
666 ptr_c[2] = count_def >> 8;
667 ptr_c[3] = count_def & 255;
668 ptr_c += 4;
669 }
670
671 /* For each torrent in this bucket.. */
672 for (tor_offset = 0; tor_offset < torrents_list->size; ++tor_offset) {
673 /* Address torrents members */
674 ot_torrent *torrent = ((ot_torrent *)(torrents_list->data)) + tor_offset;
675 ot_peerlist *peer_list = torrent->peer_list;
676 ot_peer *peers = (ot_peer *)(peer_list->peers.data);
677 uint8_t **dst;
678
679 /* Determine destination slot */
680 count_peers = peer_list->peer_count;
681 switch (count_peers) {
682 case 0:
683 continue;
684 case 1:
685 dst = mem_a ? &ptr_a : &ptr_c;
686 break;
687 case 2:
688 dst = mem_b ? &ptr_b : &ptr_c;
689 break;
690 default:
691 dst = &ptr_c;
692 break;
693 }
694
695 /* Copy tail of info_hash, advance pointer */
696 memcpy(*dst, ((uint8_t *)torrent->hash) + 1, sizeof(ot_hash) - 1);
697 *dst += sizeof(ot_hash) - 1;
698
699 /* Encode peer count */
700 if (dst == &ptr_c)
701 while (count_peers) {
702 if (count_peers <= 0x7f)
703 *(*dst)++ = count_peers;
704 else
705 *(*dst)++ = 0x80 | (count_peers & 0x7f);
706 count_peers >>= 7;
707 }
708
709 /* Copy peers */
710 count_peers = peer_list->peer_count;
711 while (count_peers--) {
712 memcpy(*dst, peers++, OT_IP_SIZE + 3);
713 *dst += OT_IP_SIZE + 3;
714 }
715 free_peerlist(peer_list);
716 }
717
718 free(torrents_list->data);
719 memset(torrents_list, 0, sizeof(*torrents_list));
720 unlock_continue:
721 mutex_bucket_unlock(bucket, 0);
722
723 if (ptr) {
724 int i;
725
726 if (ptr_b > ptr_c)
727 ptr_c = ptr_b;
728 if (ptr_a > ptr_c)
729 ptr_c = ptr_a;
730 mem = ptr_c - ptr;
731
732 for (i = 0; i < MAX_PEERS; ++i) {
733 if (PROXYPEER_ISCONNECTED(g_connections[i].state)) {
734 void *tmp = malloc(mem);
735 if (tmp) {
736 memcpy(tmp, ptr, mem);
737 batch_add(&g_connections[i].outdata, tmp, mem);
738 io_wantwrite(g_connections[i].fd);
739 }
740 }
741 }
742
743 free(ptr);
744 }
745 usleep(OT_SYNC_SLEEP);
746 }
747 }
748 return 0;
749}
750
751static void livesync_issue_peersync() {
752 socket_mcast_send(g_socket_out, g_peerbuffer_start, (size_t)(g_peerbuffer_pos - g_peerbuffer_start), groupip_1, LIVESYNC_PORT);
753 g_peerbuffer_pos = g_peerbuffer_start + sizeof(g_tracker_id) + sizeof(uint32_t);
754 g_next_packet_time = time(NULL) + LIVESYNC_MAXDELAY;
755}
756
757void livesync_ticker() {
758 /* livesync_issue_peersync sets g_next_packet_time */
759 if (time(NULL) > g_next_packet_time && g_peerbuffer_pos > g_peerbuffer_start + sizeof(g_tracker_id))
760 livesync_issue_peersync();
761}
762
763static void livesync_proxytell(uint8_t prefix, uint8_t *info_hash, uint8_t *peer) {
764 // unsigned int i;
765
766 *g_peerbuffer_pos = prefix;
767 memcpy(g_peerbuffer_pos + 1, info_hash, sizeof(ot_hash) - 1);
768 memcpy(g_peerbuffer_pos + sizeof(ot_hash), peer, sizeof(ot_peer) - 1);
769
770#if 0
771 /* Dump info_hash */
772 for( i=0; i<sizeof(ot_hash); ++i )
773 printf( "%02X", g_peerbuffer_pos[i] );
774 putchar( ':' );
775#endif
776 g_peerbuffer_pos += sizeof(ot_hash);
777#if 0
778 printf( "%hhu.%hhu.%hhu.%hhu:%hu (%02X %02X)\n", g_peerbuffer_pos[0], g_peerbuffer_pos[1], g_peerbuffer_pos[2], g_peerbuffer_pos[3],
779 g_peerbuffer_pos[4] | ( g_peerbuffer_pos[5] << 8 ), g_peerbuffer_pos[6], g_peerbuffer_pos[7] );
780#endif
781 g_peerbuffer_pos += sizeof(ot_peer);
782
783 if (g_peerbuffer_pos >= g_peerbuffer_highwater)
784 livesync_issue_peersync();
785}
786
787static void process_indata(proxy_peer *peer) {
788 size_t consumed, peers;
789 uint8_t *data = peer->indata, *hash;
790 uint8_t *dataend = data + peer->indata_length;
791
792 while (1) {
793 /* If we're not inside of a packet, make a new one */
794 if (!peer->packet_tcount) {
795 /* Ensure the header is complete or postpone processing */
796 if (data + 4 > dataend)
797 break;
798 peer->packet_type = data[0];
799 peer->packet_tprefix = data[1];
800 peer->packet_tcount = data[2] * 256 + data[3];
801 data += 4;
802 printf("type: %hhu, prefix: %02X, torrentcount: %zd\n", peer->packet_type, peer->packet_tprefix, peer->packet_tcount);
803 }
804
805 /* Ensure size for a minimal torrent block */
806 if (data + sizeof(ot_hash) + OT_IP_SIZE + 3 > dataend)
807 break;
808
809 /* Advance pointer to peer count or peers */
810 hash = data;
811 data += sizeof(ot_hash) - 1;
812
813 /* Type 0 has peer count encoded before each peers */
814 peers = peer->packet_type;
815 if (!peers) {
816 int shift = 0;
817 do
818 peers |= (0x7f & *data) << (7 * shift);
819 while (*(data++) & 0x80 && shift++ < 6);
820 }
821#if 0
822printf( "peers: %zd\n", peers );
823#endif
824 /* Ensure enough data being read to hold all peers */
825 if (data + (OT_IP_SIZE + 3) * peers > dataend) {
826 data = hash;
827 break;
828 }
829 while (peers--) {
830 livesync_proxytell(peer->packet_tprefix, hash, data);
831 data += OT_IP_SIZE + 3;
832 }
833 --peer->packet_tcount;
834 }
835
836 consumed = data - peer->indata;
837 memmove(peer->indata, data, peer->indata_length - consumed);
838 peer->indata_length -= consumed;
839}
840
841static void *livesync_worker(void *args) {
842 (void)args;
843 while (1) {
844 ot_ip6 in_ip;
845 uint16_t in_port;
846 uint32_t packet_type;
847 ssize_t datalen = socket_recv(g_socket_in, g_inbuffer, LIVESYNC_INCOMING_BUFFSIZE, in_ip, &in_port);
848
849 /* Expect at least tracker id and packet type */
850 if (datalen <= (ssize_t)(sizeof(g_tracker_id) + sizeof(uint32_t)))
851 continue;
852 if (!memcmp(g_inbuffer, &g_tracker_id, sizeof(g_tracker_id))) {
853 /* drop packet coming from ourselves */
854 continue;
855 }
856 memcpy(&packet_type, g_inbuffer + sizeof(g_tracker_id), sizeof(packet_type));
857
858 switch (ntohl(packet_type)) {
859 case OT_SYNC_PEER4:
860 livesync_handle_peersync(datalen, OT_PEER_SIZE4);
861 break;
862 case OT_SYNC_PEER6:
863 livesync_handle_peersync(datalen, OT_PEER_SIZE6);
864 break;
865 default:
866 // fprintf( stderr, "Received an unknown live sync packet type %u.\n", ntohl( packet_type ) );
867 break;
868 }
869 }
870 return 0;
871}
diff --git a/src/trackerlogic.c b/src/trackerlogic.c
new file mode 100644
index 0000000..0b032e1
--- /dev/null
+++ b/src/trackerlogic.c
@@ -0,0 +1,643 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <stdint.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11
12/* Opentracker */
13#include "ot_accesslist.h"
14#include "ot_clean.h"
15#include "ot_fmt.h"
16#include "ot_fullscrape.h"
17#include "ot_http.h"
18#include "ot_ip.h"
19#include "ot_livesync.h"
20#include "ot_mutex.h"
21#include "ot_workqueue.h"
22#include "ot_random.h"
23#include "ot_stats.h"
24#include "ot_udp.h"
25#include "ot_vector.h"
26#include "trackerlogic.h"
27
28/* Forward declaration */
29size_t return_peers_for_torrent(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto);
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
38void free_peerlist(ot_peerlist *peer_list) {
39 if (!peer_list)
40 return;
41 free_peer_vector(&peer_list->peers6);
42 free_peer_vector(&peer_list->peers4);
43 free(peer_list);
44}
45
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) {
49 int exactmatch;
50 ot_time now = time_now_minutes();
51 ot_torrent *torrent;
52 ot_vector *torrents_list;
53
54 if (age > OT_TORRENT_TIMEOUT)
55 return;
56
57 torrents_list = mutex_bucket_lock_by_hash(hash);
58
59 if (!accesslist_hashisvalid(hash)) {
60 mutex_bucket_unlock_by_hash(hash, 0);
61 return;
62 }
63
64 torrent = vector_find_or_insert(torrents_list, (void *)hash, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
65 if (!torrent || exactmatch) {
66 mutex_bucket_unlock_by_hash(hash, 0);
67 return;
68 }
69
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 */
72 memset(torrent, 0, sizeof(ot_torrent));
73 memcpy(torrent->hash, hash, sizeof(ot_hash));
74 torrent->base = now > age ? (uint32_t)(now - age) : 0;
75 torrent->down_count = (uint32_t)down_count;
76
77 mutex_bucket_unlock_by_hash(hash, 1);
78}
79
80size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount) {
81 int exactmatch, delta_torrentcount = 0, completed = 0;
82 ot_torrent *torrent;
83 ot_peer *peer_dest;
84 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash);
85 ot_peerlist *peer_list;
86 size_t peer_size; /* initialized in next line */
87 ot_peer const *peer_src = peer_from_peer6(&ws->peer, &peer_size);
88
89 if (!accesslist_hashisvalid(*ws->hash)) {
90 mutex_bucket_unlock_by_hash(*ws->hash, 0);
91 if (proto == FLAG_TCP) {
92 const char invalid_hash[] = "d14:failure reason63:Requested download is not authorized for use with this tracker.e";
93 memcpy(ws->reply, invalid_hash, strlen(invalid_hash));
94 return strlen(invalid_hash);
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 }
103 return 0;
104 }
105
106 torrent = vector_find_or_insert(torrents_list, (void *)ws->hash, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
107 if (!torrent) {
108 mutex_bucket_unlock_by_hash(*ws->hash, 0);
109 return 0;
110 }
111
112 if (!exactmatch) {
113 /* Create a new torrent entry, then */
114 memset(torrent, 0, sizeof(ot_torrent));
115 memcpy(torrent->hash, *ws->hash, sizeof(ot_hash));
116 delta_torrentcount = 1;
117 } else
118 clean_single_torrent(torrent);
119
120 torrent->base = time_now_minutes();
121
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;
130
131 /* Check for peer in its family's vector */
132 peer_dest = vector_find_or_insert_peer(peer_size == OT_PEER_SIZE6 ? &peer_list->peers6 : &peer_list->peers4, peer_src, peer_size, &exactmatch);
133 if (!peer_dest) {
134 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount);
135 return 0;
136 }
137
138 /* Tell peer that it's fresh */
139 OT_PEERTIME(ws->peer, OT_PEER_SIZE6) = 0;
140
141 /* Sanitize flags: Whoever claims to have completed download, must be a seeder */
142 if ((OT_PEERFLAG(ws->peer) & (PEER_FLAG_COMPLETED | PEER_FLAG_SEEDING)) == PEER_FLAG_COMPLETED)
143 OT_PEERFLAG(ws->peer) ^= PEER_FLAG_COMPLETED;
144
145 /* If we hadn't had a match create peer there */
146 if (!exactmatch) {
147
148#ifdef WANT_SYNC_LIVE
149 if (proto == FLAG_MCA)
150 OT_PEERFLAG(ws->peer) |= PEER_FLAG_FROM_SYNC;
151 else
152 livesync_tell(ws);
153#endif
154
155 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED) {
156 torrent->down_count++;
157 completed = 1; /* the event, which may syslog, is issued after unlock */
158 }
159 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING)
160 peer_list->seed_count++;
161
162 } else {
163 stats_issue_event(ws, EVENT_RENEW, 0, OT_PEERTIME(peer_dest, peer_size));
164#ifdef WANT_SPOT_WOODPECKER
165 if ((OT_PEERTIME(peer_dest, peer_size) > 0) && (OT_PEERTIME(peer_dest, peer_size) < 20))
166 stats_issue_event(ws, EVENT_WOODPECKER, 0, (uintptr_t)&ws->peer);
167#endif
168#ifdef WANT_SYNC_LIVE
169 /* Won't live sync peers that come back too fast. Only exception:
170 fresh "completed" reports */
171 if (proto != FLAG_MCA) {
172 if (OT_PEERTIME(peer_dest, peer_size) > OT_CLIENT_SYNC_RENEW_BOUNDARY ||
173 (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED)))
174 livesync_tell(ws);
175 }
176#endif
177
178 if ((OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_SEEDING) && !(OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING))
179 peer_list->seed_count--;
180 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_SEEDING) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_SEEDING))
181 peer_list->seed_count++;
182 if (!(OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED) && (OT_PEERFLAG(ws->peer) & PEER_FLAG_COMPLETED)) {
183 torrent->down_count++;
184 completed = 1; /* the event, which may syslog, is issued after unlock */
185 }
186 if (OT_PEERFLAG_D(peer_dest, peer_size) & PEER_FLAG_COMPLETED)
187 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
188 }
189
190 memcpy(peer_dest, peer_src, peer_size);
191#ifdef WANT_SYNC
192 if (proto == FLAG_MCA) {
193 mutex_bucket_unlock_by_hash(*ws->hash, delta_torrentcount);
194 if (completed)
195 stats_issue_event(ws, EVENT_COMPLETED, 0, 0);
196 return 0;
197 }
198#endif
199
200 ws->reply_size = return_peers_for_torrent(ws, torrent, amount, ws->reply, proto);
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);
206 return ws->reply_size;
207}
208
209static size_t return_peers_all(ot_vector *peer_vector, size_t peer_size, size_t peer_count, char *reply) {
210 size_t bucket, num_buckets = 1;
211 ot_vector *bucket_list = peer_vector;
212 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
213 size_t result = compare_size * peer_count;
214 char *r_end = reply + result;
215
216 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
217 num_buckets = bucket_list->size;
218 bucket_list = (ot_vector *)bucket_list->data;
219 }
220
221 for (bucket = 0; bucket < num_buckets; ++bucket) {
222 ot_peer *peers = bucket_list[bucket].data;
223 size_t peer_count = bucket_list[bucket].size;
224 while (peer_count--) {
225 if (OT_PEERFLAG_D(peers, peer_size) & PEER_FLAG_SEEDING) {
226 r_end -= compare_size;
227 memcpy(r_end, peers, compare_size);
228 } else {
229 memcpy(reply, peers, compare_size);
230 reply += compare_size;
231 }
232 peers += peer_size;
233 }
234 }
235 return result;
236}
237
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) {
239 size_t bucket_offset, bucket_index = 0, num_buckets = 1;
240 ot_vector *bucket_list = peer_vector;
241 unsigned int shifted_pc = peer_count;
242 unsigned int shifted_step = 0;
243 unsigned int shift = 0;
244 size_t compare_size = OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(peer_size);
245 size_t result = compare_size * amount;
246 char *r_end = reply + result;
247
248 if (OT_VECTOR_HASBUCKETS(peer_vector)) {
249 num_buckets = bucket_list->size;
250 bucket_list = (ot_vector *)bucket_list->data;
251 }
252
253 /* Make fixpoint arithmetic as exact as possible */
254#define MAXPRECBIT (1 << (8 * sizeof(int) - 3))
255 while (!(shifted_pc & MAXPRECBIT)) {
256 shifted_pc <<= 1;
257 shift++;
258 }
259 shifted_step = shifted_pc / amount;
260#undef MAXPRECBIT
261
262 /* Initialize somewhere in the middle of peers so that
263 fixpoint's aliasing doesn't alway miss the same peers */
264 bucket_offset = nrand48(ws->rand48_state) % peer_count;
265
266 while (amount--) {
267 ot_peer *peer;
268
269 /* This is the aliased, non shifted range, next value may fall into */
270 unsigned int diff = (((amount + 1) * shifted_step) >> shift) - ((amount * shifted_step) >> shift);
271 bucket_offset += 1 + nrand48(ws->rand48_state) % diff;
272
273 while (bucket_offset >= bucket_list[bucket_index].size) {
274 bucket_offset -= bucket_list[bucket_index].size;
275 bucket_index = (bucket_index + 1) % num_buckets;
276 }
277 peer = (ot_peer*)bucket_list[bucket_index].data + peer_size * bucket_offset;
278 if (OT_PEERFLAG_D(peer, peer_size) & PEER_FLAG_SEEDING) {
279 r_end -= compare_size;
280 memcpy(r_end, peer, compare_size);
281 } else {
282 memcpy(reply, peer, compare_size);
283 reply += compare_size;
284 }
285 }
286 return result;
287}
288
289static size_t return_peers_for_torrent_udp(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply) {
290 char *r = reply;
291 size_t peer_size = peer_size_from_peer6(&ws->peer);
292 ot_peerlist *peer_list = torrent->peer_list;
293 ot_vector *family = peer_size == OT_PEER_SIZE6 ? &peer_list->peers6 : &peer_list->peers4;
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);
297
298 if (amount > list_count)
299 amount = list_count;
300
301 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
302 pack_uint32(&r, peer_count - seed_count);
303 pack_uint32(&r, seed_count);
304
305 if (amount) {
306 if (amount == list_count)
307 r += return_peers_all(family, peer_size, list_count, r);
308 else
309 r += return_peers_selection(ws, family, peer_size, amount, list_count, r);
310 }
311 return r - reply;
312}
313
314static size_t return_peers_for_torrent_tcp(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply) {
315 char *r = reply;
316 const char *r_end = ws->outbuf + G_OUTBUF_SIZE;
317 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM;
318 ot_peerlist *peer_list = torrent->peer_list;
319 size_t count6 = vector_peer_count(&peer_list->peers6);
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;
324
325 /* Simple case: amount of peers in both lists is less than requested, here we return all results */
326 size_t amount_v4 = count4;
327 size_t amount_v6 = count6;
328
329 /* Complex case: both lists have more than enough entries and we need to split between v4 and v6 clients */
330 if (amount_v4 + amount_v6 > amount) {
331 size_t amount_left, percent_v6 = 0, percent_v4 = 0, left_v6, left_v4;
332 const size_t SCALE = 1024;
333
334 /* If possible, fill at least a quarter of peer from each family */
335 if (amount / 4 <= amount_v4)
336 amount_v4 = amount / 4;
337 if (amount / 4 <= amount_v6)
338 amount_v6 = amount / 4;
339
340 /* Fill the rest according to which family's pool provides more peers */
341 amount_left = amount - (amount_v4 + amount_v6);
342
343 left_v4 = count4 - amount_v4;
344 left_v6 = count6 - amount_v6;
345
346 if (left_v4 + left_v6) {
347 percent_v4 = (SCALE * left_v4) / (left_v4 + left_v6);
348 percent_v6 = (SCALE * left_v6) / (left_v4 + left_v6);
349 }
350
351 amount_v4 += (amount_left * percent_v4) / SCALE;
352 amount_v6 += (amount_left * percent_v6) / SCALE;
353
354 /* Integer division rounding can leave out a peer */
355 if (amount_v4 + amount_v6 < amount && amount_v6 < count6)
356 ++amount_v6;
357 if (amount_v4 + amount_v6 < amount && amount_v4 < count4)
358 ++amount_v4;
359 }
360
361 fmt_append(&r, r_end, "d8:completei%zde10:downloadedi%zde10:incompletei%zde8:intervali%ie12:min intervali%ie", seed_count, down_count, peer_count, erval,
362 erval / 2);
363
364 if (amount_v4) {
365 fmt_append(&r, r_end, PEERS_BENCODED4 "%zd:", OT_PEER_COMPARE_SIZE4 * amount_v4);
366 if (amount_v4 == count4)
367 r += return_peers_all(&peer_list->peers4, OT_PEER_SIZE4, count4, r);
368 else
369 r += return_peers_selection(ws, &peer_list->peers4, OT_PEER_SIZE4, amount_v4, count4, r);
370 }
371
372 if (amount_v6) {
373 fmt_append(&r, r_end, PEERS_BENCODED6 "%zd:", OT_PEER_COMPARE_SIZE6 * amount_v6);
374 if (amount_v6 == count6)
375 r += return_peers_all(&peer_list->peers6, OT_PEER_SIZE6, count6, r);
376 else
377 r += return_peers_selection(ws, &peer_list->peers6, OT_PEER_SIZE6, amount_v6, count6, r);
378 }
379
380 fmt_append(&r, r_end, "e");
381
382 return r - reply;
383}
384
385/* Compiles a list of random peers for a torrent
386 * Reply must have enough space to hold:
387 * 92 + 6 * amount bytes for TCP/IPv4
388 * 92 + 18 * amount bytes for TCP/IPv6
389 * 12 + 6 * amount bytes for UDP/IPv4
390 * 12 + 18 * amount bytes for UDP/IPv6
391 * Does not yet check not to return self
392 */
393size_t return_peers_for_torrent(struct ot_workstruct *ws, ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto) {
394 return proto == FLAG_TCP ? return_peers_for_torrent_tcp(ws, torrent, amount, reply) : return_peers_for_torrent_udp(ws, torrent, amount, reply);
395}
396
397/* Fetches scrape info for a specific torrent */
398size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply) {
399 int exactmatch, delta_torrentcount = 0;
400 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash);
401 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
402
403 uint32_t seeders = 0, completed = 0, leechers = 0;
404 char *r = reply;
405
406 if (exactmatch) {
407 if (clean_single_torrent(torrent)) {
408 vector_remove_torrent(torrents_list, torrent);
409 delta_torrentcount = -1;
410 } else {
411 seeders = torrent_seed_count(torrent);
412 completed = torrent->down_count;
413 leechers = torrent_peer_count(torrent) - torrent_seed_count(torrent);
414 }
415 }
416 mutex_bucket_unlock_by_hash(hash, delta_torrentcount);
417
418 pack_uint32(&r, seeders);
419 pack_uint32(&r, completed);
420 pack_uint32(&r, leechers);
421 return r - reply;
422}
423
424/* Fetches scrape info for a specific torrent */
425void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char **reply, const char *reply_end) {
426 int exactmatch;
427 size_t i;
428
429 fmt_append(reply, reply_end, "d5:filesd");
430
431 for (i = 0; i < amount; ++i) {
432 int delta_torrentcount = 0;
433 ot_hash const *hash = hash_list + i;
434 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*hash);
435 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
436
437 if (exactmatch) {
438 if (clean_single_torrent(torrent)) {
439 vector_remove_torrent(torrents_list, torrent);
440 delta_torrentcount = -1;
441 } else {
442 fmt_append(reply, reply_end, "20:");
443 fmt_bytes(reply, reply_end, hash, sizeof(ot_hash));
444 size_t seed_count = torrent_seed_count(torrent);
445 size_t peer_count = torrent_peer_count(torrent);
446 fmt_append(reply, reply_end, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee", seed_count, (size_t)torrent->down_count, peer_count - seed_count);
447 }
448 }
449 mutex_bucket_unlock_by_hash(*hash, delta_torrentcount);
450 }
451
452 fmt_append(reply, reply_end, "ee");
453}
454
455size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) {
456 int exactmatch;
457 ot_vector *torrents_list = mutex_bucket_lock_by_hash(*ws->hash);
458 ot_torrent *torrent = vector_binary_search(ws->hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
459 size_t peer_size; /* initialized in next line */
460 ot_peer const *peer_src = peer_from_peer6(&ws->peer, &peer_size);
461 size_t peer_count = 0, seed_count = 0;
462
463#ifdef WANT_SYNC_LIVE
464 if (proto != FLAG_MCA) {
465 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED;
466 livesync_tell(ws);
467 }
468#endif
469
470 if (exactmatch && torrent->peer_list) {
471 ot_vector *family = peer_size == OT_PEER_SIZE6 ? &torrent->peer_list->peers6 : &torrent->peer_list->peers4;
472 if (vector_remove_peer(family, peer_src, peer_size) == 2)
473 torrent->peer_list->seed_count--;
474
475 peer_count = torrent_peer_count(torrent);
476 seed_count = torrent_seed_count(torrent);
477 }
478
479 if (proto == FLAG_TCP) {
480 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM;
481 char *r = ws->reply;
482
483 fmt_append(&r, ws->outbuf + G_OUTBUF_SIZE, "d8:completei%zde10:incompletei%zde8:intervali%ie12:min intervali%ie%s0:e", seed_count, peer_count - seed_count,
484 erval, erval / 2, peer_size == OT_PEER_SIZE6 ? PEERS_BENCODED6 : PEERS_BENCODED4);
485 ws->reply_size = r - ws->reply;
486 }
487
488 /* Handle UDP reply */
489 if (proto == FLAG_UDP) {
490 char *r = ws->reply;
491 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
492 pack_uint32(&r, peer_count - seed_count);
493 pack_uint32(&r, seed_count);
494 ws->reply_size = r - ws->reply;
495 }
496
497 mutex_bucket_unlock_by_hash(*ws->hash, 0);
498 return ws->reply_size;
499}
500
501void iterate_all_torrents(int (*for_each)(ot_torrent *torrent, uintptr_t data), uintptr_t data) {
502 size_t bucket, j;
503
504 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
505 ot_vector *torrents_list = mutex_bucket_lock(bucket);
506 ot_torrent *torrents = (ot_torrent *)(torrents_list->data);
507
508 for (j = 0; j < torrents_list->size; ++j)
509 if (for_each(torrents + j, data))
510 break;
511
512 mutex_bucket_unlock(bucket, 0);
513 if (!g_opentracker_running)
514 return;
515 }
516}
517
518ot_peer *peer_from_peer6(ot_peer6 *peer, size_t *peer_size) {
519 ot_ip6 *ip = (ot_ip6 *)peer;
520 if (!ip_is_v4mapped(ip)) {
521 *peer_size = OT_PEER_SIZE6;
522 return (ot_peer *)peer;
523 }
524 *peer_size = OT_PEER_SIZE4;
525 return (ot_peer *)(((uint8_t *)peer) + 12);
526}
527
528size_t peer_size_from_peer6(ot_peer6 *peer) {
529 ot_ip6 *ip = (ot_ip6 *)peer;
530 if (!ip_is_v4mapped(ip))
531 return OT_PEER_SIZE6;
532 return OT_PEER_SIZE4;
533}
534
535#ifdef _DEBUG_RANDOMTORRENTS
536void trackerlogic_add_random_torrents(size_t amount) {
537 struct ot_workstruct ws;
538 memset(&ws, 0, sizeof(ws));
539
540 ws.inbuf = malloc(G_INBUF_SIZE);
541 ws.outbuf = malloc(G_OUTBUF_SIZE);
542 ws.reply = ws.outbuf;
543 ws.hash = (ot_hash *)ws.inbuf;
544
545 while (amount--) {
546 random_bytes(ws.hash, sizeof(ot_hash));
547 random_bytes(&ws.peer, sizeof(ws.peer));
548
549 OT_PEERFLAG(ws.peer) &= PEER_FLAG_SEEDING | PEER_FLAG_COMPLETED | PEER_FLAG_STOPPED;
550
551 add_peer_to_torrent_and_return_peers(FLAG_TCP, &ws, 1);
552 }
553
554 free(ws.inbuf);
555 free(ws.outbuf);
556}
557#endif
558
559void exerr(const char *message) {
560 fprintf(stderr, "%s\n", message);
561 exit(111);
562}
563
564void trackerlogic_init(void) {
565 g_tracker_id = random_uint32();
566
567 if (!g_stats_path)
568 g_stats_path = "stats";
569 g_stats_path_len = strlen(g_stats_path);
570
571 /* Initialise background worker threads */
572 mutex_init();
573 workqueue_init();
574 clean_init();
575 fullscrape_init();
576 accesslist_init();
577 stats_init();
578}
579
580/* Live sync reads whole packets rather than requests and wants a larger
581 inbuf than the request path does, hence the size. */
582int workstruct_init(struct ot_workstruct *ws, size_t inbuf_size) {
583 memset(ws, 0, sizeof(*ws));
584 ws->inbuf = malloc(inbuf_size);
585 ws->outbuf = malloc(G_OUTBUF_SIZE);
586#ifdef _DEBUG_HTTPERROR
587 ws->debugbuf = malloc(G_DEBUGBUF_SIZE);
588#endif
589 if (!ws->inbuf || !ws->outbuf) {
590 free(ws->inbuf);
591 free(ws->outbuf);
592#ifdef _DEBUG_HTTPERROR
593 free(ws->debugbuf);
594#endif
595 return -1;
596 }
597
598 /* Picking which peers to hand out starts here, so two workers seeded alike
599 would hand out alike */
600 random_bytes(ws->rand48_state, sizeof(ws->rand48_state));
601
602 stats_counters_register(ws);
603 return 0;
604}
605
606void workstruct_deinit(struct ot_workstruct *ws) {
607 /* The tally goes to the global before this struct goes out of scope */
608 stats_counters_retire(ws);
609
610 free(ws->inbuf);
611 free(ws->outbuf);
612#ifdef _DEBUG_HTTPERROR
613 free(ws->debugbuf);
614#endif
615}
616
617void trackerlogic_deinit(void) {
618 size_t bucket, j;
619
620 clean_deinit();
621 stats_deinit();
622 accesslist_deinit();
623 fullscrape_deinit();
624
625 /* Free all torrents... */
626 for (bucket = 0; bucket < OT_BUCKET_COUNT; ++bucket) {
627 ot_vector *torrents_list = mutex_bucket_lock(bucket);
628 int delta_torrentcount = 0;
629 if (torrents_list->size) {
630 for (j = 0; j < torrents_list->size; ++j) {
631 ot_torrent *torrent = ((ot_torrent *)(torrents_list->data)) + j;
632 free_peerlist(torrent->peer_list);
633 delta_torrentcount -= 1;
634 }
635 free(torrents_list->data);
636 }
637 mutex_bucket_unlock(bucket, delta_torrentcount);
638 }
639
640 /* Release mutexes */
641 workqueue_deinit();
642 mutex_deinit();
643}
diff --git a/src/trackerlogic.h b/src/trackerlogic.h
new file mode 100644
index 0000000..a05c790
--- /dev/null
+++ b/src/trackerlogic.h
@@ -0,0 +1,343 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_TRACKERLOGIC_H__
5#define OT_TRACKERLOGIC_H__
6
7#include <arpa/inet.h>
8#include <signal.h>
9#include <stdatomic.h>
10#include <stdint.h>
11#include <stdlib.h>
12#include <string.h>
13#include <sys/time.h>
14#include <sys/types.h>
15#include <time.h>
16
17typedef uint8_t ot_hash[20];
18typedef time_t ot_time;
19typedef char ot_ip6[16];
20typedef struct {
21 ot_ip6 address;
22 int bits;
23} ot_net;
24/* List of peers should fit in a single UDP packet (around 1200 bytes) */
25#define OT_MAX_PEERS_UDP6 66
26#define OT_MAX_PEERS_UDP4 200
27
28#define OT_IP_SIZE6 16
29#define OT_IP_SIZE4 4
30#define OT_PORT_SIZE 2
31#define OT_FLAG_SIZE 1
32#define OT_TIME_SIZE 1
33
34/* Some tracker behaviour tunable */
35#ifndef OT_CLIENT_TIMEOUT
36#define OT_CLIENT_TIMEOUT 30
37#endif
38#ifndef OT_CLIENT_TIMEOUT_CHECKINTERVAL
39#define OT_CLIENT_TIMEOUT_CHECKINTERVAL 10
40#endif
41#define OT_CLIENT_TIMEOUT_SEND (60 * 15)
42#define OT_CLIENT_REQUEST_INTERVAL (60 * 30)
43#define OT_CLIENT_REQUEST_VARIATION (60 * 6)
44#define OT_CLIENT_REJECT_INTERVAL (60 * 120)
45
46#define OT_TORRENT_TIMEOUT_HOURS 24
47#define OT_TORRENT_TIMEOUT (60 * OT_TORRENT_TIMEOUT_HOURS)
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
54#define OT_CLIENT_REQUEST_INTERVAL_RANDOM \
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))
58
59/* If WANT_MODEST_FULLSCRAPES is on, ip addresses may not
60 fullscrape more frequently than this amount in seconds */
61#define OT_MODEST_PEER_TIMEOUT (60 * 5)
62
63/* If peers come back before 10 minutes, don't live sync them */
64#define OT_CLIENT_SYNC_RENEW_BOUNDARY 10
65
66/* Number of tracker admin ip addresses allowed */
67#define OT_ADMINIP_MAX 64
68#define OT_MAX_THREADS 64
69
70/* Number of minutes after announce before peer is removed */
71#define OT_PEER_TIMEOUT 45
72
73/* We maintain a list of 1024 pointers to sorted list of ot_torrent structs
74 Sort key is, of course, its hash.
75 Can be tweked from the Makefile, sensible values are between 8 in 16. More
76 buckets means shorter vectors and a cheaper insert, which only pays for a
77 tracker carrying millions of torrents. Consult the DESIGN document. */
78#ifndef OT_BUCKET_COUNT_BITS
79#define OT_BUCKET_COUNT_BITS 10
80#endif
81
82#define OT_BUCKET_COUNT (1 << OT_BUCKET_COUNT_BITS)
83#define OT_BUCKET_COUNT_SHIFT (32 - OT_BUCKET_COUNT_BITS)
84
85/* if _DEBUG_RANDOMTORRENTS is set, this is the amount of torrents to create
86 on startup */
87#define RANDOMTORRENTS (1024 * 1024 * 1)
88
89#if defined(CLOCK_MONOTONIC_COARSE)
90#define OT_CLOCK_CHEAP CLOCK_MONOTONIC_COARSE /* Linux and FreeBSD */
91#elif defined(CLOCK_MONOTONIC_FAST)
92#define OT_CLOCK_CHEAP CLOCK_MONOTONIC_FAST /* the other BSDs */
93#else
94#define OT_CLOCK_CHEAP CLOCK_MONOTONIC /* macOS and whatever else */
95#endif
96
97static inline ot_time time_now_seconds(void) {
98 struct timespec now;
99 clock_gettime(OT_CLOCK_CHEAP, &now);
100 return (ot_time)now.tv_sec;
101}
102
103static inline ot_time time_now_minutes(void) { return time_now_seconds() / 60; }
104
105/* For the deadlines the tracker sets on itself, which read better as the
106 span they allow than as an addition to the current second */
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
137/* Cleared from the interrupt handler and read by every worker */
138extern _Atomic int g_opentracker_running;
139
140/* Sent to a thread parked in a blocking read */
141#define OT_SIGNAL_WAKE SIGUSR1
142
143
144extern uint32_t g_tracker_id;
145typedef enum { FLAG_TCP, FLAG_UDP, FLAG_MCA, FLAG_SELFPIPE } PROTO_FLAG;
146
147#define OT_PEER_COMPARE_SIZE6 ((OT_IP_SIZE6) + (OT_PORT_SIZE))
148#define OT_PEER_COMPARE_SIZE4 ((OT_IP_SIZE4) + (OT_PORT_SIZE))
149#define OT_PEER_COMPARE_SIZE_FROM_PEER_SIZE(PEER_SIZE) ((PEER_SIZE) - (OT_TIME_SIZE) - (OT_FLAG_SIZE))
150
151#define OT_PEER_SIZE6 ((OT_TIME_SIZE) + (OT_FLAG_SIZE) + (OT_PEER_COMPARE_SIZE6))
152#define OT_PEER_SIZE4 ((OT_TIME_SIZE) + (OT_FLAG_SIZE) + (OT_PEER_COMPARE_SIZE4))
153
154typedef uint8_t ot_peer; /* Generic pointer to a v6 or v4 peer */
155typedef uint8_t ot_peer6[OT_PEER_SIZE6];
156typedef uint8_t ot_peer4[OT_PEER_SIZE4];
157static const uint8_t PEER_FLAG_SEEDING = 0x80;
158static const uint8_t PEER_FLAG_COMPLETED = 0x40;
159static const uint8_t PEER_FLAG_STOPPED = 0x20;
160static const uint8_t PEER_FLAG_FROM_SYNC = 0x10;
161static const uint8_t PEER_FLAG_LEECHING = 0x00;
162
163/* Takes an ot_peer6 and returns the proper pointer to the peer and sets peer_size */
164ot_peer *peer_from_peer6(ot_peer6 *peer, size_t *peer_size);
165size_t peer_size_from_peer6(ot_peer6 *peer);
166
167/* New style */
168#define OT_SETIP(peer, ip) memcpy((uint8_t *)(peer), (ip), OT_IP_SIZE6)
169#define OT_SETPORT(peer, port) memcpy(((uint8_t *)(peer)) + (OT_IP_SIZE6), (port), 2)
170#define OT_PEERFLAG(peer) (((uint8_t *)(peer))[(OT_IP_SIZE6) + 2])
171#define OT_PEERFLAG_D(peer, peersize) (((uint8_t *)(peer))[(peersize) - 2])
172#define OT_PEERTIME(peer, peersize) (((uint8_t *)(peer))[(peersize) - 1])
173
174#define PEERS_BENCODED6 "6:peers6"
175#define PEERS_BENCODED4 "5:peers"
176
177#define OT_HASH_COMPARE_SIZE (sizeof(ot_hash))
178
179struct ot_peerlist;
180typedef struct ot_peerlist ot_peerlist;
181typedef struct {
182 ot_hash hash;
183 ot_peerlist *peer_list; /* NULL until the torrent has a peer in either family */
184 uint32_t base; /* epoch minutes, when the torrent was last cleaned */
185 uint32_t down_count; /* completed events */
186} ot_torrent;
187
188#include "ot_vector.h"
189
190struct ot_peerlist {
191 uint32_t seed_count;
192 /* each family's peers: a normal vector, or a pointer to ot_vector[] buckets
193 when data != NULL and space == 0 (size then holds the bucket count) */
194 ot_vector peers6;
195 ot_vector peers4;
196};
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; }
217
218/* The http replies the tracker counts when it has to refuse a request. */
219enum {
220 CODE_HTTPERROR_302,
221 CODE_HTTPERROR_400,
222 CODE_HTTPERROR_400_PARAM,
223 CODE_HTTPERROR_400_COMPACT,
224 CODE_HTTPERROR_402_NOTMODEST,
225 CODE_HTTPERROR_402_PAYMENT_REQUIRED,
226 CODE_HTTPERROR_403_IP,
227 CODE_HTTPERROR_404,
228 CODE_HTTPERROR_500,
229
230 CODE_HTTPERROR_COUNT
231};
232
233/* One statistic. Used when workers report stats to their workstruct */
234typedef _Atomic unsigned long ot_counter;
235
236/* What each thread counts for itself. The two runs at the end are indexed by
237 the http error code and by the age in minutes of a renewed peer */
238typedef enum {
239 OT_COUNTER_TCP_CONNECTIONS,
240 OT_COUNTER_UDP_CONNECTIONS,
241 OT_COUNTER_TCP_ANNOUNCES,
242 OT_COUNTER_UDP_ANNOUNCES,
243 OT_COUNTER_TCP_SCRAPES,
244 OT_COUNTER_UDP_SCRAPES,
245 OT_COUNTER_TCP_CONNECTS,
246 OT_COUNTER_UDP_CONNECTS,
247 OT_COUNTER_UDP_CONNID_MISSMATCH,
248 OT_COUNTER_COMPLETED,
249 OT_COUNTER_FULLSCRAPES,
250 OT_COUNTER_FULLSCRAPE_REQUESTS,
251 OT_COUNTER_FULLSCRAPE_BYTES,
252 OT_COUNTER_SYNCS,
253 OT_COUNTER_STALLS,
254
255 OT_COUNTER_FAILED, /* CODE_HTTPERROR_COUNT of them */
256 OT_COUNTER_RENEWED = OT_COUNTER_FAILED + CODE_HTTPERROR_COUNT, /* OT_PEER_TIMEOUT of them */
257
258 OT_COUNTER_COUNT = OT_COUNTER_RENEWED + OT_PEER_TIMEOUT
259} ot_counter_index;
260
261struct ot_workstruct {
262 /* Thread specific, static */
263
264 /* This thread's own statistics, and the link ot_stats keeps them on */
265 ot_counter counters[OT_COUNTER_COUNT];
266 struct ot_workstruct *counters_next;
267
268 char *inbuf;
269#define G_INBUF_SIZE 8192
270 char *outbuf;
271#define G_OUTBUF_SIZE 8192
272#ifdef _DEBUG_HTTPERROR
273 char *debugbuf;
274#define G_DEBUGBUF_SIZE 8192
275#endif
276
277 /* The peer currently in the working */
278 ot_peer6 peer; /* Can fit v6 and v4 peers */
279
280 /* Pointers into the request buffer */
281 ot_hash *hash;
282 char *peer_id;
283
284 /* HTTP specific, non static */
285 char *request;
286 ssize_t request_size;
287 ssize_t header_size;
288 char *reply;
289 ssize_t reply_size;
290
291 /* Entropy state for rand48 function so that threads don't need to acquire mutexes for
292 global random() or arc4random() state, which causes heavy load on linuxes */
293 uint16_t rand48_state[3];
294
295 int keep_alive;
296
297 /* Set when a request path gave the connection to a worker thread. */
298 int handed_off;
299};
300
301/* Everything a thread that serves requests needs for itself. Set up and torn
302 down in one place so that a new kind of worker cannot miss a piece.
303 Returns -1 if the buffers could not be had. */
304int workstruct_init(struct ot_workstruct *ws, size_t inbuf_size);
305void workstruct_deinit(struct ot_workstruct *ws);
306
307/*
308 Exported functions
309*/
310
311#ifdef WANT_SYNC_LIVE
312#define WANT_SYNC
313#endif
314
315#ifdef WANT_SYNC
316#define WANT_SYNC_PARAM(param) , param
317#else
318#define WANT_SYNC_PARAM(param)
319#endif
320
321void trackerlogic_init(void);
322void trackerlogic_deinit(void);
323void exerr(const char *message);
324
325/* add_peer_to_torrent does only release the torrent bucket if from_sync is set,
326 otherwise it is released in return_peers_for_torrent */
327size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount);
328size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws);
329void return_tcp_scrape_for_torrent(ot_hash const *hash_list, size_t amount, char **reply, const char *reply_end);
330size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply);
331void add_torrent_from_saved_state(ot_hash const hash, ot_time age, size_t down_count);
332#ifdef _DEBUG_RANDOMTORRENTS
333void trackerlogic_add_random_torrents(size_t amount);
334#endif
335
336/* torrent iterator */
337void iterate_all_torrents(int (*for_each)(ot_torrent *torrent, uintptr_t data), uintptr_t data);
338
339/* Helper, before it moves to its own object */
340void free_peerlist(ot_peerlist *peer_list);
341void free_peer_vector(ot_vector *peer_vector);
342
343#endif
diff --git a/tests/accept_filter_probe.py b/tests/accept_filter_probe.py
new file mode 100644
index 0000000..22f585a
--- /dev/null
+++ b/tests/accept_filter_probe.py
@@ -0,0 +1,110 @@
1"""What a deferred accept does to connections that never send anything.
2
3Those connections never reach opentracker, so its own client timeout cannot
4clean them up: whatever bound exists is the kernel's. This measures it, and
5then asks the question that follows from it -- whether enough of them keep
6the tracker from answering anybody else.
7
8 make opentracker
9 python3 tests/accept_filter_probe.py
10
11On FreeBSD the filter does nothing unless accf_data is loaded, so run it both
12ways to see whether the numbers differ:
13
14 kldload accf_data
15"""
16
17import os
18import socket
19import signal
20import subprocess
21import sys
22import tempfile
23import time
24import urllib.error
25import urllib.request
26
27TRACKER = os.environ.get("OPENTRACKER", "./opentracker")
28IDLE = int(os.environ.get("IDLE", "300"))
29PATIENCE = float(os.environ.get("PATIENCE", "90"))
30HASH = "".join("%%%02x" % b for b in range(1, 21))
31
32
33def start(port):
34 directory = tempfile.mkdtemp(prefix="ot-accf-")
35 with open(os.path.join(directory, "conf"), "w") as handle:
36 handle.write("listen.tcp 127.0.0.1:%d\nlisten.udp 127.0.0.1:%d\n" % (port, port))
37 log = open(os.path.join(directory, "log"), "w+b")
38 tracker = subprocess.Popen([TRACKER, "-f", os.path.join(directory, "conf")], stdout=log, stderr=log)
39 for _ in range(300):
40 try:
41 socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
42 return tracker, log
43 except OSError:
44 time.sleep(0.02)
45 tracker.kill()
46 raise SystemExit("tracker never listened on %d" % port)
47
48
49def announce(port, timeout=5):
50 """One ordinary request, so we can see whether the tracker still serves."""
51 started = time.time()
52 try:
53 urllib.request.urlopen(
54 "http://127.0.0.1:%d/announce?info_hash=%s&peer_id=-OT0001-probe0000001&port=6881&left=0" % (port, HASH),
55 timeout=timeout,
56 ).read()
57 return time.time() - started, None
58 except Exception as problem: # noqa: BLE001 - reported, not swallowed
59 return time.time() - started, problem
60
61
62def main():
63 port = int(os.environ.get("PORT", "28000"))
64 tracker, log = start(port)
65 try:
66 print(" how long a connection that says nothing is held")
67 quiet = socket.create_connection(("127.0.0.1", port), timeout=5)
68 quiet.settimeout(PATIENCE)
69 started = time.time()
70 try:
71 held = "dropped after %.1f s" % (time.time() - started) if quiet.recv(1) == b"" else "sent us something"
72 except socket.timeout:
73 held = "still open after %.0f s" % PATIENCE
74 except OSError as problem:
75 held = "ended after %.1f s: %s" % (time.time() - started, problem)
76 quiet.close()
77 print(" %s" % held)
78
79 print(" and whether %d of them keep anybody else out" % IDLE)
80 before, problem = announce(port)
81 print(" a request before: %.0f ms%s" % (before * 1000, "" if problem is None else " (%s)" % problem))
82
83 idlers = []
84 for _ in range(IDLE):
85 try:
86 idlers.append(socket.create_connection(("127.0.0.1", port), timeout=2))
87 except OSError as problem:
88 print(" could only open %d of them: %s" % (len(idlers), problem))
89 break
90 print(" holding %d connections that have sent nothing" % len(idlers))
91
92 during, problem = announce(port, timeout=10)
93 print(" a request during: %.0f ms%s" % (during * 1000, "" if problem is None else " REFUSED: %s" % problem))
94
95 for idler in idlers:
96 idler.close()
97 after, problem = announce(port)
98 print(" a request after: %.0f ms%s" % (after * 1000, "" if problem is None else " (%s)" % problem))
99 finally:
100 tracker.send_signal(signal.SIGINT)
101 try:
102 tracker.wait(timeout=10)
103 except subprocess.TimeoutExpired:
104 tracker.kill()
105 tracker.wait()
106 log.close()
107
108
109if __name__ == "__main__":
110 main()
diff --git a/tests/http_load.c b/tests/http_load.c
new file mode 100644
index 0000000..d04139b
--- /dev/null
+++ b/tests/http_load.c
@@ -0,0 +1,148 @@
1/* An HTTP load generator speaking the tracker's own protocol.
2
3 Each request is its own connection, which is what a BitTorrent client
4 normally does and what the tracker's hot path is built for: accept, read
5 one request, write a short reply, close. That makes this a measurement of
6 connection cost rather than of request cost, and connection cost is where
7 the tracker's system calls are.
8
9 cc -O2 -pthread -o http_load tests/http_load.c
10 ./http_load 127.0.0.1 6969 8 5 10000
11
12 Arguments: host, port, threads, seconds, and how many distinct torrents to
13 announce. Cycling a fixed set reaches a steady state where almost every
14 announce renews a peer that is already there, rather than measuring how
15 fast the tracker can insert torrents it will never see again. */
16
17#include <arpa/inet.h>
18#include <errno.h>
19#include <netinet/in.h>
20#include <netinet/tcp.h>
21#include <pthread.h>
22#include <stdatomic.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/socket.h>
28#include <sys/time.h>
29#include <unistd.h>
30
31static struct sockaddr_in g_tracker;
32static long g_torrents = 10000;
33static double g_seconds = 5;
34static _Atomic long long g_replies = 0;
35static _Atomic long long g_failed = 0;
36static _Atomic int g_running = 1;
37
38static double now_seconds(void) {
39 struct timeval tv;
40 gettimeofday(&tv, NULL);
41 return tv.tv_sec + tv.tv_usec / 1000000.0;
42}
43
44/* %xx for all twenty bytes, which is what a client sends and what the
45 tracker's urlencode reader has to walk */
46static void hash_of(long which, char *out) {
47 int i;
48
49 for (i = 0; i < 20; ++i) {
50 unsigned byte = (unsigned)((which >> ((i % 4) * 8)) & 0xff) ^ (unsigned)(i * 37);
51 sprintf(out + i * 3, "%%%02x", byte & 0xff);
52 }
53}
54
55static void *worker(void *args) {
56 long index = (long)(intptr_t)args;
57 long which = index * 7919;
58 char request[512], hash[61], reply[2048];
59
60 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
61 int sock = socket(AF_INET, SOCK_STREAM, 0);
62 int one = 1;
63 ssize_t got, sent;
64 size_t length;
65
66 if (sock < 0) {
67 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
68 continue;
69 }
70 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
71
72 if (connect(sock, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) < 0) {
73 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
74 close(sock);
75 continue;
76 }
77
78 hash_of(which, hash);
79 which = (which + 1) % g_torrents;
80 length = (size_t)snprintf(request, sizeof(request),
81 "GET /announce?info_hash=%s&peer_id=-OT0001-%06ld%06ld&port=%u&left=0 HTTP/1.0\r\n\r\n",
82 hash, index, which, (unsigned)(6881 + index));
83
84 for (sent = 0; (size_t)sent < length;) {
85 ssize_t wrote = write(sock, request + sent, length - (size_t)sent);
86 if (wrote <= 0)
87 break;
88 sent += wrote;
89 }
90
91 /* Read to end of reply, which the tracker marks by closing */
92 got = 0;
93 for (;;) {
94 ssize_t piece = read(sock, reply, sizeof(reply));
95 if (piece <= 0)
96 break;
97 got += piece;
98 }
99 close(sock);
100
101 if (got > 0)
102 atomic_fetch_add_explicit(&g_replies, 1, memory_order_relaxed);
103 else
104 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
105 }
106 return NULL;
107}
108
109int main(int argc, char **argv) {
110 const char *host = argc > 1 ? argv[1] : "127.0.0.1";
111 int port = argc > 2 ? atoi(argv[2]) : 6969;
112 long threads = argc > 3 ? atol(argv[3]) : 4;
113 pthread_t *pool;
114 double started, elapsed;
115 long i;
116
117 g_seconds = argc > 4 ? atof(argv[4]) : 5;
118 g_torrents = argc > 5 ? atol(argv[5]) : 10000;
119 if (g_torrents < 1)
120 g_torrents = 1;
121
122 memset(&g_tracker, 0, sizeof(g_tracker));
123 g_tracker.sin_family = AF_INET;
124 g_tracker.sin_port = htons((uint16_t)port);
125 if (inet_pton(AF_INET, host, &g_tracker.sin_addr) != 1) {
126 fprintf(stderr, "cannot parse address %s\n", host);
127 return 1;
128 }
129
130 pool = calloc((size_t)threads, sizeof(pthread_t));
131 started = now_seconds();
132 for (i = 0; i < threads; ++i)
133 pthread_create(pool + i, NULL, worker, (void *)(intptr_t)i);
134
135 while (now_seconds() - started < g_seconds)
136 usleep(20000);
137 atomic_store(&g_running, 0);
138
139 for (i = 0; i < threads; ++i)
140 pthread_join(pool[i], NULL);
141 elapsed = now_seconds() - started;
142
143 printf("%.0f replies/s (%lld replies, %lld failed, %ld threads, %.1f s)\n",
144 (double)atomic_load(&g_replies) / elapsed, (long long)atomic_load(&g_replies),
145 (long long)atomic_load(&g_failed), threads, elapsed);
146 free(pool);
147 return 0;
148}
diff --git a/tests/integration/.gitignore b/tests/integration/.gitignore
new file mode 100644
index 0000000..7a60b85
--- /dev/null
+++ b/tests/integration/.gitignore
@@ -0,0 +1,2 @@
1__pycache__/
2*.pyc
diff --git a/tests/integration/harness.py b/tests/integration/harness.py
new file mode 100644
index 0000000..f3cd0fa
--- /dev/null
+++ b/tests/integration/harness.py
@@ -0,0 +1,366 @@
1"""Starts a real opentracker and talks to it over the wire.
2
3Everything here drives the binary rather than the code, so these tests cover
4what the unit suite cannot reach: the event loop, the HTTP parser and the
5torrent store working together. Run against a sanitizer build and the tracker
6reports its own memory errors, which the teardown turns into test failures.
7"""
8
9import os
10import shutil
11import signal
12import socket
13import struct
14import subprocess
15import sys
16import tempfile
17import time
18import unittest
19import urllib.error
20import urllib.parse
21import urllib.request
22
23# groupip_1 in src/ot_livesync.c
24LIVESYNC_GROUP = "224.0.23.5"
25
26TRACKER = os.environ.get("OPENTRACKER", os.path.join(os.path.dirname(__file__), "..", "..", "opentracker.debug"))
27
28
29def bdecode(data):
30 """Enough bencode for what a tracker answers."""
31
32 def value(i):
33 if data[i : i + 1] == b"d":
34 i, out = i + 1, {}
35 while data[i : i + 1] != b"e":
36 i, key = value(i)
37 i, out[key] = value(i)
38 return i + 1, out
39 if data[i : i + 1] == b"l":
40 i, out = i + 1, []
41 while data[i : i + 1] != b"e":
42 i, item = value(i)
43 out.append(item)
44 return i + 1, out
45 if data[i : i + 1] == b"i":
46 end = data.index(b"e", i)
47 return end + 1, int(data[i + 1 : end])
48 colon = data.index(b":", i)
49 length = int(data[i:colon])
50 return colon + 1 + length, data[colon + 1 : colon + 1 + length]
51
52 return value(0)[1]
53
54
55def free_port(attempts=50):
56 """A port free for both protocols, because the tracker binds both.
57
58 Asking the kernel for a free tcp port says nothing about the udp port of
59 the same number, and anything on the machine holding that one makes the
60 tracker exit at once with "Address already in use".
61 """
62 for _ in range(attempts):
63 tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
64 udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
65 try:
66 tcp.bind(("127.0.0.1", 0))
67 udp.bind(("127.0.0.1", tcp.getsockname()[1]))
68 return tcp.getsockname()[1]
69 except OSError:
70 continue
71 finally:
72 tcp.close()
73 udp.close()
74 raise AssertionError("no port free for both tcp and udp after %d tries" % attempts)
75
76
77class Tracker:
78 """One tracker process, listening on loopback."""
79
80 def __init__(self, extra_config="", files=None, extra_args=()):
81 self.port = free_port()
82 # Only used by a config that asks for live sync, but allocated either
83 # way so {livesync_port} always resolves.
84 self.livesync_port = free_port()
85 self.dir = tempfile.mkdtemp(prefix="ot-integration-")
86 self.log = None
87 self.process = None
88 try:
89 for name, content in (files or {}).items():
90 with open(os.path.join(self.dir, name), "wb") as handle:
91 handle.write(content)
92 self.config = os.path.join(self.dir, "opentracker.conf")
93 with open(self.config, "w") as handle:
94 handle.write("listen.tcp 127.0.0.1:%d\n" % self.port)
95 handle.write("listen.udp 127.0.0.1:%d\n" % self.port)
96 handle.write(extra_config.replace("{dir}", self.dir).replace("{livesync_port}", str(self.livesync_port)))
97 self.log = open(os.path.join(self.dir, "tracker.log"), "w+b")
98 # Leak detection is left at the sanitizer's own default, which is on
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.
101 environment = dict(os.environ, ASAN_OPTIONS="abort_on_error=0")
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)
104 self._wait_for_port()
105 except BaseException:
106 self._cleanup()
107 raise
108
109 def _cleanup(self):
110 """Close what we opened and take the scratch directory with it."""
111 if self.process is not None and self.process.poll() is None:
112 self.process.kill()
113 self.process.wait()
114 if self.log is not None:
115 self.log.close()
116 self.log = None
117 shutil.rmtree(self.dir, ignore_errors=True)
118
119 def _wait_for_port(self):
120 for _ in range(200):
121 if self.process.poll() is not None:
122 raise AssertionError("tracker exited at once:\n" + self.output())
123 try:
124 probe = socket.create_connection(("127.0.0.1", self.port), timeout=0.2)
125 probe.close()
126 return
127 except OSError:
128 time.sleep(0.05)
129 raise AssertionError("tracker never listened on %d:\n%s" % (self.port, self.output()))
130
131 def output(self):
132 if self.log is None:
133 return ""
134 self.log.flush()
135 self.log.seek(0)
136 return self.log.read().decode("utf-8", "replace")
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
143 def stop(self):
144 """Returns anything the tracker complained about on the way out.
145
146 The interrupt rather than a kill is what makes the leak check work at
147 all: LeakSanitizer reports from an exit handler, so a killed tracker
148 reports nothing and the suite passes over leaks it never looked for.
149 """
150 refused_to_exit = False
151 if self.process is not None and self.process.poll() is None:
152 self.process.send_signal(signal.SIGINT)
153 try:
154 self.process.wait(timeout=5)
155 except subprocess.TimeoutExpired:
156 self.process.kill()
157 self.process.wait()
158 refused_to_exit = True
159 complaints = [
160 line
161 for line in self.output().splitlines()
162 if "Sanitizer" in line or "runtime error" in line or line.startswith("ERROR")
163 ]
164 if refused_to_exit:
165 # Killing it throws away whatever the sanitizer had to say on the
166 # way out, so a test that ends this way has checked nothing.
167 complaints.append("the tracker did not exit within 5 s of SIGINT and had to be killed")
168 self._cleanup()
169 return complaints
170
171 # ----------------------------------------------------------- over http
172
173 def get(self, path, timeout=10):
174 return urllib.request.urlopen("http://127.0.0.1:%d%s" % (self.port, path), timeout=timeout).read()
175
176 def announce(self, info_hash, peer_id=b"-OT0001-aaaaaaaaaaaa", port=6881, left=0, **extra):
177 query = {
178 "info_hash": urllib.parse.quote_from_bytes(info_hash, safe=""),
179 "peer_id": urllib.parse.quote_from_bytes(peer_id, safe=""),
180 "port": port,
181 "left": left,
182 }
183 query.update(extra)
184 return bdecode(self.get("/announce?" + "&".join("%s=%s" % item for item in query.items())))
185
186 def scrape(self, info_hash):
187 return bdecode(self.get("/scrape?info_hash=" + urllib.parse.quote_from_bytes(info_hash, safe="")))
188
189 def stats(self, mode):
190 return self.get("/stats?mode=" + mode)
191
192 def get_with_headers(self, path, headers=None, timeout=10):
193 """The body and the response headers, for the compressed answers."""
194 request = urllib.request.Request("http://127.0.0.1:%d%s" % (self.port, path), headers=headers or {})
195 with urllib.request.urlopen(request, timeout=timeout) as response:
196 return response.read(), dict(response.headers)
197
198 def torrent_count(self):
199 return int(self.stats("torr").split()[0])
200
201 def livesync_send(self, payload, group=LIVESYNC_GROUP):
202 """Put a packet on the live sync group.
203
204 It has to go to the group rather than straight at the port: the
205 tracker binds two sockets there, the reader on the wildcard address
206 and the writer on the configured one, and the kernel gives a unicast
207 datagram to the more specific of the two, which nobody reads."""
208 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
209 try:
210 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton("127.0.0.1"))
211 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
212 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
213 sock.sendto(payload, (group, self.livesync_port))
214 finally:
215 sock.close()
216
217 def wait_until(self, predicate, timeout=5):
218 """A live sync packet is handled by another thread, so an effect of
219 one arrives some time after the send."""
220 deadline = time.time() + timeout
221 while time.time() < deadline:
222 if predicate():
223 return True
224 time.sleep(0.02)
225 return predicate()
226
227 # ------------------------------------------------------------ over udp
228
229 def udp_connect(self):
230 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
231 sock.settimeout(5)
232 sock.sendto(struct.pack(">QII", 0x41727101980, 0, 1), ("127.0.0.1", self.port))
233 answer = sock.recv(2048)
234 action, _, connection_id = struct.unpack(">IIQ", answer[:16])
235 assert action == 0, "udp connect answered action %d" % action
236 return sock, connection_id
237
238 def udp_announce(self, sock, connection_id, info_hash, left=0, event=0, port=6881, numwant=-1):
239 sock.sendto(
240 struct.pack(
241 ">QII20s20sQQQIIIiH", connection_id, 1, 2, info_hash, b"p" * 20, 0, left, 0, event, 0, 0, numwant, port
242 ),
243 ("127.0.0.1", self.port),
244 )
245 answer = sock.recv(2048)
246 action, _, interval, leechers, seeders = struct.unpack(">IIIII", answer[:20])
247 assert action == 1, "udp announce answered action %d" % action
248 return {"interval": interval, "leechers": leechers, "seeders": seeders, "peers": answer[20:]}
249
250 def udp_scrape(self, sock, connection_id, hashes):
251 """One (seeders, completed, leechers) triple per hash, in order."""
252 sock.sendto(struct.pack(">QII", connection_id, 2, 3) + b"".join(hashes), ("127.0.0.1", self.port))
253 answer = sock.recv(2048)
254 action, _ = struct.unpack(">II", answer[:8])
255 assert action == 2, "udp scrape answered action %d" % action
256 return [struct.unpack(">III", answer[8 + 12 * i : 20 + 12 * i]) for i in range(len(hashes))]
257
258 def connect(self):
259 """A connection the caller drives and closes."""
260 return Connection(self.port)
261
262 def udp_raw(self, payload, timeout=1.0):
263 """Sends a packet exactly as given. Returns the answer, or None if the
264 tracker chose to say nothing, which is how it treats a broken one."""
265 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
266 sock.settimeout(timeout)
267 try:
268 sock.sendto(payload, ("127.0.0.1", self.port))
269 try:
270 return sock.recv(2048)
271 except socket.timeout:
272 return None
273 finally:
274 sock.close()
275
276
277class Connection:
278 """One HTTP connection the caller keeps open, which urllib will not do.
279
280 Reads exactly one reply at a time, so a test can tell "the tracker
281 answered and kept the socket" from "the tracker answered and hung up"."""
282
283 def __init__(self, port, timeout=5):
284 self.sock = socket.create_connection(("127.0.0.1", port), timeout=timeout)
285 self.sock.settimeout(timeout)
286 self.buffer = b""
287
288 def send(self, path, connection="Keep-Alive", version="1.1"):
289 request = "GET %s HTTP/%s\r\nHost: tracker\r\n" % (path, version)
290 if connection is not None:
291 request += "Connection: %s\r\n" % connection
292 self.sock.sendall((request + "\r\n").encode())
293
294 def _fill(self):
295 chunk = self.sock.recv(65536)
296 if not chunk:
297 raise EOFError("the tracker closed the connection")
298 self.buffer += chunk
299
300 def reply(self):
301 """The one complete reply at the front of the stream, headers and body."""
302 while b"\r\n\r\n" not in self.buffer:
303 self._fill()
304 head, rest = self.buffer.split(b"\r\n\r\n", 1)
305 headers = {}
306 for line in head.split(b"\r\n")[1:]:
307 name, _, value = line.partition(b":")
308 headers[name.strip().lower()] = value.strip()
309
310 if headers.get(b"transfer-encoding") == b"chunked":
311 while not rest.endswith(b"0\r\n\r\n"):
312 self.buffer = head + b"\r\n\r\n" + rest
313 self._fill()
314 rest = self.buffer.split(b"\r\n\r\n", 1)[1]
315 body, self.buffer = rest, b""
316 else:
317 length = int(headers.get(b"content-length", b"0"))
318 while len(rest) < length:
319 self.buffer = head + b"\r\n\r\n" + rest
320 self._fill()
321 rest = self.buffer.split(b"\r\n\r\n", 1)[1]
322 body, self.buffer = rest[:length], rest[length:]
323 return head.split(b"\r\n")[0], headers, body
324
325 def is_open(self):
326 """True if the tracker is still holding the connection."""
327 try:
328 self.sock.settimeout(0.4)
329 return self.sock.recv(1) != b""
330 except socket.timeout:
331 return True
332 except OSError:
333 return False
334 finally:
335 try:
336 self.sock.settimeout(5)
337 except OSError:
338 pass
339
340 def close(self):
341 self.sock.close()
342
343
344class TrackerTestCase(unittest.TestCase):
345 """Gives every test its own tracker and fails it on any sanitizer output."""
346
347 config = ""
348 files = None
349
350 def setUp(self):
351 self.tracker = Tracker(self.config, self.files)
352
353 def tearDown(self):
354 # A connection the test closed is only reaped when the event loop gets
355 # round to it, and a cookie still held at exit reads as a leak. One
356 # more request puts us behind that work in the loop's queue.
357 try:
358 self.tracker.torrent_count()
359 except Exception:
360 pass
361 complaints = self.tracker.stop()
362 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
363
364 def hash_for(self, name):
365 """A distinct info hash per test, so tests cannot leak into each other."""
366 return (name.encode() + b"\0" * 20)[:20]
diff --git a/tests/integration/test_accesslist.py b/tests/integration/test_accesslist.py
new file mode 100644
index 0000000..3ed8ddf
--- /dev/null
+++ b/tests/integration/test_accesslist.py
@@ -0,0 +1,128 @@
1"""The blacklist, loaded from a file at startup.
2
3A blacklisted info hash must be refused at both the announce and the scrape
4entry, 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.
6"""
7
8import os
9import struct
10import time
11import unittest
12
13from harness import Tracker, TrackerTestCase
14
15BLOCKED = b"\xb1" * 20
16ALLOWED = b"\xa1" * 20
17
18
19def listing(*hashes):
20 return b"".join(h.hex().upper().encode() + b"\n" for h in hashes)
21
22
23class Blacklist(TrackerTestCase):
24 config = "access.blacklist {dir}/blacklist\n"
25 files = {"blacklist": listing(BLOCKED)}
26
27 def test_a_blacklisted_hash_is_refused(self):
28 answer = self.tracker.announce(BLOCKED, port=6881, left=0)
29 self.assertIn(b"failure reason", answer)
30 self.assertIn(b"not authorized", answer[b"failure reason"])
31
32 def test_a_blacklisted_hash_never_becomes_a_torrent(self):
33 before = self.tracker.torrent_count()
34 self.tracker.announce(BLOCKED, port=6881, left=0)
35 self.assertEqual(self.tracker.torrent_count(), before, "the refused hash was stored anyway")
36
37 def test_any_other_hash_is_served(self):
38 answer = self.tracker.announce(ALLOWED, port=6881, left=0)
39 self.assertNotIn(b"failure reason", answer)
40 self.assertEqual(answer[b"complete"], 1)
41
42 def test_the_block_is_an_empty_announce_over_udp(self):
43 """An empty swarm with a long interval, not an error. BEP 15 binds a
44 client to the interval and says nothing about what to do with an
45 error, so an error puts the client on its own retry schedule, which
46 starts in the tens of seconds."""
47 sock, connection_id = self.tracker.udp_connect()
48 sock.close()
49 request = struct.pack(
50 ">QII20s20sQQQIIIiH", connection_id, 1, 7, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881
51 )
52 answer = self.tracker.udp_raw(request)
53 self.assertIsNotNone(answer)
54 self.assertEqual(len(answer), 20, "header and counts, no peers behind them")
55 action, transaction, interval, leechers, seeders = struct.unpack(">IIIII", answer)
56 self.assertEqual(action, 1, "action 1 is the announce packet")
57 self.assertEqual(transaction, 7)
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")
61
62 def test_a_blocked_hash_is_not_stored_when_it_arrives_over_udp(self):
63 sock, connection_id = self.tracker.udp_connect()
64 sock.close()
65 self.tracker.udp_raw(
66 struct.pack(">QII20s20sQQQIIIiH", connection_id, 1, 8, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881)
67 )
68 self.assertEqual(self.tracker.torrent_count(), 0)
69
70
71class BlacklistWithoutTrailingNewline(TrackerTestCase):
72 """A single hash with no newline after it used to size the list at zero
73 and then write into it, which took the tracker down before it listened."""
74
75 config = "access.blacklist {dir}/blacklist\n"
76 files = {"blacklist": BLOCKED.hex().upper().encode()}
77
78 def test_the_last_line_counts_even_without_its_newline(self):
79 answer = self.tracker.announce(BLOCKED, port=6881, left=0)
80 self.assertIn(b"failure reason", answer)
81
82 def test_and_the_tracker_still_serves_everything_else(self):
83 self.assertEqual(self.tracker.announce(ALLOWED, port=6881, left=0)[b"complete"], 1)
84
85
86class EmptyBlacklist(TrackerTestCase):
87 config = "access.blacklist {dir}/blacklist\n"
88 files = {"blacklist": b""}
89
90 def test_an_empty_file_blocks_nothing_and_starts_cleanly(self):
91 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1)
92 self.assertEqual(self.tracker.announce(ALLOWED, port=6882, left=0)[b"complete"], 1)
93
94
95class MissingBlacklist(TrackerTestCase):
96 """The file is named but absent: the tracker warns and serves everything,
97 because it may be created later."""
98
99 config = "access.blacklist {dir}/absent\n"
100
101 def test_a_missing_file_blocks_nothing(self):
102 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1)
103
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
127if __name__ == "__main__":
128 unittest.main()
diff --git a/tests/integration/test_announce.py b/tests/integration/test_announce.py
new file mode 100644
index 0000000..2d21417
--- /dev/null
+++ b/tests/integration/test_announce.py
@@ -0,0 +1,144 @@
1"""What a peer's announce does to the swarm it joins."""
2
3import os
4import socket
5import sys
6import unittest
7
8sys.path.insert(0, os.path.dirname(__file__))
9from harness import TrackerTestCase
10
11
12def peers_of(answer, key=b"peers"):
13 """Compact peer list as a list of (address, port)."""
14 blob, out = answer.get(key, b""), []
15 size = 6 if key == b"peers" else 18
16 for offset in range(0, len(blob), size):
17 entry = blob[offset : offset + size]
18 address = socket.inet_ntop(socket.AF_INET if size == 6 else socket.AF_INET6, entry[:-2])
19 out.append((address, entry[-2] << 8 | entry[-1]))
20 return out
21
22
23class AnnounceLifetime(TrackerTestCase):
24 config = ""
25
26 def test_a_leecher_is_counted_as_incomplete(self):
27 info_hash = self.hash_for("leecher")
28 answer = self.tracker.announce(info_hash, left=100)
29 self.assertEqual(answer[b"complete"], 0)
30 self.assertEqual(answer[b"incomplete"], 1)
31
32 def test_no_bytes_left_means_seeding(self):
33 info_hash = self.hash_for("seeder")
34 answer = self.tracker.announce(info_hash, left=0)
35 self.assertEqual(answer[b"complete"], 1)
36 self.assertEqual(answer[b"incomplete"], 0)
37
38 def test_a_peer_that_finishes_moves_from_one_column_to_the_other(self):
39 info_hash = self.hash_for("finishes")
40 peer_id = b"-OT0001-finisher0001"
41 self.tracker.announce(info_hash, peer_id=peer_id, left=100)
42 self.assertEqual(self.tracker.announce(info_hash, peer_id=peer_id, left=100)[b"incomplete"], 1)
43
44 answer = self.tracker.announce(info_hash, peer_id=peer_id, left=0, event="completed")
45 self.assertEqual(answer[b"complete"], 1, "the peer should now count as a seeder")
46 self.assertEqual(answer[b"incomplete"], 0, "and no longer as a leecher")
47
48 def test_stopped_removes_the_peer(self):
49 info_hash = self.hash_for("stopped")
50 peer_id = b"-OT0001-leaves000001"
51 self.tracker.announce(info_hash, peer_id=peer_id, left=100)
52 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"incomplete"], 1)
53
54 self.tracker.announce(info_hash, peer_id=peer_id, left=100, event="stopped")
55 self.assertEqual(
56 self.tracker.scrape(info_hash)[b"files"][info_hash][b"incomplete"], 0, "the peer should be gone"
57 )
58
59 def test_the_same_peer_announcing_twice_is_still_one_peer(self):
60 info_hash = self.hash_for("twice")
61 peer_id = b"-OT0001-repeats00001"
62 for _ in range(5):
63 answer = self.tracker.announce(info_hash, peer_id=peer_id, left=100)
64 self.assertEqual(answer[b"incomplete"], 1, "re-announcing must not duplicate the peer")
65
66 def test_a_peer_is_its_address_and_port_not_its_peer_id(self):
67 """Two announces from one address and port are one peer, whatever
68 peer_id they carry, because that pair is the whole identity."""
69 info_hash = self.hash_for("identity")
70 self.tracker.announce(info_hash, peer_id=b"-OT0001-a00000000001", port=6881, left=100)
71 answer = self.tracker.announce(info_hash, peer_id=b"-OT0001-b00000000002", port=6881, left=100)
72 self.assertEqual(answer[b"incomplete"], 1, "same address and port, so still one peer")
73
74 answer = self.tracker.announce(info_hash, peer_id=b"-OT0001-c00000000003", port=6882, left=100)
75 self.assertEqual(answer[b"incomplete"], 2, "a different port makes a different peer")
76
77 def test_a_downloaded_count_is_kept(self):
78 info_hash = self.hash_for("downloaded")
79 self.tracker.announce(info_hash, port=7001, left=0, event="completed")
80 self.tracker.announce(info_hash, port=7002, left=0, event="completed")
81 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"downloaded"], 2)
82
83 def test_a_peer_is_given_the_whole_swarm_including_itself(self):
84 """opentracker does not filter the announcing peer out of its own
85 answer. Clients are expected to ignore themselves."""
86 info_hash = self.hash_for("sees")
87 self.tracker.announce(info_hash, port=1111, left=100)
88 answer = self.tracker.announce(info_hash, port=2222, left=100)
89
90 ports = sorted(port for _, port in peers_of(answer))
91 self.assertEqual(ports, [1111, 2222])
92
93 def test_an_unknown_torrent_scrapes_as_empty(self):
94 answer = self.tracker.scrape(self.hash_for("never-seen"))
95 self.assertEqual(answer[b"files"], {}, "a torrent nobody announced has no entry")
96
97
98class AnnounceRejects(TrackerTestCase):
99 def assert_rejected(self, query):
100 import urllib.error
101
102 with self.assertRaises(urllib.error.HTTPError) as caught:
103 self.tracker.get("/announce?" + query)
104 self.assertEqual(caught.exception.code, 400)
105
106 def test_a_short_info_hash_is_rejected(self):
107 self.assert_rejected("info_hash=tooshort&peer_id=" + "b" * 20 + "&port=6881&left=0")
108
109 def test_a_missing_info_hash_answers_a_failure_reason(self):
110 """Not a 400: the tracker answers 200 with a bencoded complaint, so
111 that a client shows the message to its user."""
112 from harness import bdecode
113
114 answer = bdecode(self.tracker.get("/announce?peer_id=" + "b" * 20 + "&port=6881&left=0"))
115 self.assertIn(b"failure reason", answer)
116 self.assertIn(b"info_hash", answer[b"failure reason"])
117
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")
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
124 def test_a_port_that_is_not_a_number_is_rejected(self):
125 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0")
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
139 def test_two_info_hashes_are_rejected(self):
140 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0")
141
142
143if __name__ == "__main__":
144 unittest.main()
diff --git a/tests/integration/test_concurrency.py b/tests/integration/test_concurrency.py
new file mode 100644
index 0000000..528992d
--- /dev/null
+++ b/tests/integration/test_concurrency.py
@@ -0,0 +1,209 @@
1"""Several clients at once.
2
3The rest of the suite talks to the tracker one request at a time, which
4leaves the worker threads and the bucket locks almost untouched. These reach
5them.
6
7What they assert is weak on purpose. A lost update needs two threads inside
8the same few instructions, which is rare enough that these tests pass
9against code that has the race: measured, eight runs in a row. Their worth
10is that they make the racing code run at all, so that "make check-tsan"
11has something to report. Reaching the code and judging it are two jobs, and
12these only do the first.
13"""
14
15import struct
16import threading
17import unittest
18
19from harness import TrackerTestCase, bdecode
20
21THREADS = 8
22PER_THREAD = 40
23
24
25def run_threads(target, count=THREADS):
26 errors = []
27
28 def guarded(index):
29 try:
30 target(index)
31 except Exception as exception: # noqa: BLE001 - reported, not swallowed
32 errors.append("thread %d: %r" % (index, exception))
33
34 threads = [threading.Thread(target=guarded, args=(i,)) for i in range(count)]
35 for thread in threads:
36 thread.start()
37 for thread in threads:
38 thread.join()
39 return errors
40
41
42class ConcurrentAnnounce(TrackerTestCase):
43 def test_every_peer_of_one_swarm_arrives(self):
44 """One torrent, one bucket, every thread contending for its lock."""
45 info_hash = self.hash_for("concurrent-one")
46
47 def announce(index):
48 for i in range(PER_THREAD):
49 self.tracker.announce(info_hash, port=10000 + index * PER_THREAD + i, left=0)
50
51 self.assertEqual(run_threads(announce), [])
52 answer = self.tracker.scrape(info_hash)
53 self.assertEqual(answer[b"files"][info_hash][b"complete"], THREADS * PER_THREAD)
54
55 def test_inserts_spread_over_buckets(self):
56 """Every thread inserts into a different bucket, so the bucket locks
57 serialise nothing between them, and the counter they all adjust is
58 the one global the locks do not cover. Under check-tsan this is what
59 names mutex_bucket_unlock if that counter stops being atomic."""
60
61 def announce(index):
62 for i in range(PER_THREAD):
63 self.tracker.announce(struct.pack(">HH", index, i) + b"\0" * 16, port=11000 + i, left=0)
64
65 self.assertEqual(run_threads(announce), [])
66 self.assertEqual(self.tracker.torrent_count(), THREADS * PER_THREAD)
67
68 def test_a_swarm_that_fills_and_empties_at_once(self):
69 """Inserts and removals racing in the same buckets."""
70 info_hash = self.hash_for("concurrent-churn")
71 for port in range(12000, 12000 + THREADS * PER_THREAD):
72 self.tracker.announce(info_hash, port=port, left=0)
73
74 def churn(index):
75 base = 12000 + index * PER_THREAD
76 for i in range(PER_THREAD):
77 self.tracker.announce(info_hash, port=base + i, left=0, event="stopped")
78 self.tracker.announce(info_hash, port=base + i, left=100)
79
80 self.assertEqual(run_threads(churn), [])
81 answer = self.tracker.scrape(info_hash)
82 self.assertEqual(answer[b"files"][info_hash][b"incomplete"], THREADS * PER_THREAD)
83 self.assertEqual(answer[b"files"][info_hash][b"complete"], 0)
84
85
86class ConcurrentMixedBearers(TrackerTestCase):
87 def test_tcp_and_udp_reach_the_same_swarm(self):
88 info_hash = self.hash_for("concurrent-mixed")
89
90 def over_tcp(index):
91 for i in range(PER_THREAD):
92 self.tracker.announce(info_hash, port=13000 + index * PER_THREAD + i, left=0)
93
94 def over_udp(index):
95 sock, connection_id = self.tracker.udp_connect()
96 try:
97 for i in range(PER_THREAD):
98 self.tracker.udp_announce(
99 sock, connection_id, info_hash, left=0, port=14000 + index * PER_THREAD + i
100 )
101 finally:
102 sock.close()
103
104 errors = []
105 threads = [threading.Thread(target=lambda i=i: over_tcp(i)) for i in range(THREADS // 2)]
106 threads += [threading.Thread(target=lambda i=i: over_udp(i)) for i in range(THREADS // 2)]
107 for thread in threads:
108 thread.start()
109 for thread in threads:
110 thread.join()
111
112 self.assertEqual(errors, [])
113 answer = self.tracker.scrape(info_hash)
114 self.assertEqual(answer[b"files"][info_hash][b"complete"], THREADS * PER_THREAD)
115
116
117class ConcurrentWorkerTasks(TrackerTestCase):
118 def test_full_scrapes_while_the_swarm_moves(self):
119 """The full scrape runs on a worker thread, walking the same buckets
120 the announces are changing."""
121 for i in range(200):
122 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=15000 + i, left=0)
123
124 def announce(index):
125 for i in range(PER_THREAD):
126 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=16000 + index * PER_THREAD + i, left=0)
127
128 def scrape(index):
129 for _ in range(6):
130 answer = bdecode(self.tracker.get("/scrape"))
131 for counts in answer[b"files"].values():
132 if counts[b"complete"] < 0 or counts[b"incomplete"] < 0:
133 raise AssertionError("negative count in a full scrape: %r" % counts)
134
135 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)]
136 threads += [threading.Thread(target=scrape, args=(i,)) for i in range(2)]
137 for thread in threads:
138 thread.start()
139 for thread in threads:
140 thread.join()
141
142 self.assertEqual(self.tracker.torrent_count(), 200)
143
144 def test_stats_while_the_swarm_moves(self):
145 def announce(index):
146 for i in range(PER_THREAD):
147 self.tracker.announce(struct.pack(">HH", index, i) + b"\0" * 16, port=17000 + i, left=i % 2)
148
149 def poll(index):
150 for _ in range(10):
151 for mode in ("everything", "top100", "peer", "torr"):
152 self.tracker.stats(mode)
153
154 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)]
155 threads += [threading.Thread(target=poll, args=(i,)) for i in range(2)]
156 for thread in threads:
157 thread.start()
158 for thread in threads:
159 thread.join()
160
161 self.assertEqual(self.tracker.torrent_count(), (THREADS // 2) * PER_THREAD)
162
163
164class CountersAcrossContexts(TrackerTestCase):
165 """With udp workers configured, every one of them counts into a block of
166 its own, and the figure reported is those blocks added up. A registry
167 that lost a block, or a worker that wrote into somebody else's, would
168 show here and nowhere else in the suite: without this directive udp is
169 served by the main loop, which is a single context."""
170
171 config = "listen.udp.workers 4\n"
172
173 def test_the_udp_count_is_the_sum_of_every_worker(self):
174 before = int(self.tracker.stats("udp4").splitlines()[0])
175
176 packets = 0
177 for round_ in range(6):
178 sock, connection_id = self.tracker.udp_connect() # one packet
179 packets += 1
180 try:
181 for i in range(10):
182 self.tracker.udp_announce(sock, connection_id, self.hash_for("ctx%d" % i), left=0)
183 packets += 1
184 finally:
185 sock.close()
186
187 after = int(self.tracker.stats("udp4").splitlines()[0])
188 self.assertEqual(after - before, packets, "every packet counted exactly once")
189
190 def test_announces_from_several_workers_reach_one_swarm(self):
191 info_hash = self.hash_for("ctx-swarm")
192
193 def announce(index):
194 sock, connection_id = self.tracker.udp_connect()
195 try:
196 for i in range(PER_THREAD):
197 self.tracker.udp_announce(
198 sock, connection_id, info_hash, left=0, port=18000 + index * PER_THREAD + i
199 )
200 finally:
201 sock.close()
202
203 self.assertEqual(run_threads(announce, 4), [])
204 answer = self.tracker.scrape(info_hash)
205 self.assertEqual(answer[b"files"][info_hash][b"complete"], 4 * PER_THREAD)
206
207
208if __name__ == "__main__":
209 unittest.main()
diff --git a/tests/integration/test_config.py b/tests/integration/test_config.py
new file mode 100644
index 0000000..fe5cf9d
--- /dev/null
+++ b/tests/integration/test_config.py
@@ -0,0 +1,72 @@
1"""Settings the tracker has to accept, and still work with.
2
3An unrecognised key only warns, so coming up proves nothing on its own and a
4test that cares has to look at what the tracker said. A key that is
5recognised but cannot be parsed is another matter, and for the listen
6statements it stops the tracker.
7"""
8
9import unittest
10
11from harness import Tracker, TrackerTestCase, free_port
12
13
14class TcpWorkers(TrackerTestCase):
15 config = "listen.tcp.workers 2\n"
16
17 def test_the_tracker_serves_with_tcp_workers_asked_for(self):
18 self.assertEqual(self.tracker.announce(self.hash_for("tcpworkers"))[b"complete"], 1)
19 self.assertNotIn("Unhandled line", self.tracker.output())
20
21
22class WorkersOnAListenStatement(unittest.TestCase):
23 def test_a_listen_statement_may_carry_a_worker_count(self):
24 """The option is read off the statement rather than inherited."""
25 second = free_port()
26 tracker = Tracker("listen.tcp 127.0.0.1:%d workers=2\n" % second)
27 try:
28 self.assertEqual(tracker.announce(b"listenopts\0\0\0\0\0\0\0\0\0\0")[b"complete"], 1)
29 complaints = tracker.stop()
30 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
31 finally:
32 tracker._cleanup()
33
34
35class AListenLineThatDoesNotParse(unittest.TestCase):
36 """Warning and carrying on left a tracker that had been told where to
37 listen coming up on its default instead, which is every interface."""
38
39 def refuses(self, line):
40 with self.assertRaises(AssertionError) as caught:
41 Tracker(line)
42 return str(caught.exception)
43
44 def test_an_address_that_is_not_one_stops_the_tracker(self):
45 self.assertIn("want an address", self.refuses("listen.tcp 10.0.0.300:7999\n"))
46
47 def test_so_does_a_port_out_of_range(self):
48 self.assertIn("want an address", self.refuses("listen.udp 127.0.0.1:99999\n"))
49
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"))
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_dualstack.py b/tests/integration/test_dualstack.py
new file mode 100644
index 0000000..cd5ba7d
--- /dev/null
+++ b/tests/integration/test_dualstack.py
@@ -0,0 +1,89 @@
1"""A tracker serving both families from one socket.
2
3These need WANT_IP_FROM_QUERY_STRING so a peer's address can be dictated
4rather than being whatever loopback the test happened to come from.
5"""
6
7import os
8import socket
9import sys
10import unittest
11
12sys.path.insert(0, os.path.dirname(__file__))
13from harness import TrackerTestCase
14
15
16def addresses(answer, key):
17 blob, out = answer.get(key, b""), []
18 size = 6 if key == b"peers" else 18
19 for offset in range(0, len(blob), size):
20 entry = blob[offset : offset + size]
21 out.append(socket.inet_ntop(socket.AF_INET if size == 6 else socket.AF_INET6, entry[:-2]))
22 return out
23
24
25class DualStack(TrackerTestCase):
26 def test_an_ipv4_peer_lands_in_the_v4_list(self):
27 info_hash = self.hash_for("v4only")
28 self.tracker.announce(info_hash, ip="10.1.2.3", port=5001, left=100)
29 answer = self.tracker.announce(info_hash, ip="10.1.2.4", port=5002, left=100)
30
31 self.assertEqual(sorted(addresses(answer, b"peers")), ["10.1.2.3", "10.1.2.4"])
32 self.assertEqual(addresses(answer, b"peers6"), [], "no v6 peer was announced")
33
34 def test_an_ipv6_peer_lands_in_the_v6_list(self):
35 info_hash = self.hash_for("v6only")
36 self.tracker.announce(info_hash, ip="2001:db8::1", port=5001, left=100)
37 answer = self.tracker.announce(info_hash, ip="2001:db8::2", port=5002, left=100)
38
39 self.assertEqual(sorted(addresses(answer, b"peers6")), ["2001:db8::1", "2001:db8::2"])
40 self.assertEqual(addresses(answer, b"peers"), [], "no v4 peer was announced")
41
42 def test_the_two_families_are_kept_apart_but_both_returned(self):
43 info_hash = self.hash_for("both")
44 self.tracker.announce(info_hash, ip="10.9.9.9", port=6001, left=100)
45 answer = self.tracker.announce(info_hash, ip="2001:db8::9", port=6002, left=100)
46
47 self.assertEqual(addresses(answer, b"peers"), ["10.9.9.9"])
48 self.assertEqual(addresses(answer, b"peers6"), ["2001:db8::9"])
49
50 def test_a_v4_mapped_address_is_the_same_peer_as_the_plain_one(self):
51 info_hash = self.hash_for("v4mapped")
52 self.tracker.announce(info_hash, ip="10.5.5.5", port=7001, left=100)
53 answer = self.tracker.announce(info_hash, ip="::ffff:10.5.5.5", port=7001, left=100)
54
55 self.assertEqual(answer[b"incomplete"], 1, "the same address written two ways is one peer")
56 self.assertEqual(addresses(answer, b"peers"), ["10.5.5.5"], "and it is held as v4")
57
58 def test_the_two_families_count_into_one_swarm(self):
59 info_hash = self.hash_for("counts")
60 self.tracker.announce(info_hash, ip="10.4.4.4", port=8001, left=0)
61 answer = self.tracker.announce(info_hash, ip="2001:db8::4", port=8002, left=100)
62
63 self.assertEqual(answer[b"complete"], 1)
64 self.assertEqual(answer[b"incomplete"], 1)
65 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"complete"], 1)
66
67 def test_stopped_removes_only_the_family_it_came_from(self):
68 info_hash = self.hash_for("stopfamily")
69 self.tracker.announce(info_hash, ip="10.3.3.3", port=9001, left=100)
70 self.tracker.announce(info_hash, ip="2001:db8::3", port=9002, left=100)
71 self.tracker.announce(info_hash, ip="10.3.3.3", port=9001, left=100, event="stopped")
72
73 answer = self.tracker.announce(info_hash, ip="2001:db8::33", port=9003, left=100)
74 self.assertEqual(addresses(answer, b"peers"), [], "the v4 peer left")
75 self.assertIn("2001:db8::3", addresses(answer, b"peers6"), "the v6 one stayed")
76
77 def test_a_malformed_address_is_rejected(self):
78 import urllib.error
79
80 # The whole field has to be the address: a prefix that happens to
81 # parse would quietly record the peer somewhere else
82 for bad in ("999.1.2.3", "nonsense", "2001:db8:::1", "10.1.2.3.4", "10.1.2.3junk", "2001:db8::1%eth0"):
83 with self.assertRaises(urllib.error.HTTPError, msg="ip=%s should be refused" % bad) as caught:
84 self.tracker.announce(self.hash_for("badip"), ip=bad, port=6881, left=0)
85 self.assertEqual(caught.exception.code, 400)
86
87
88if __name__ == "__main__":
89 unittest.main()
diff --git a/tests/integration/test_dynamic_accesslist.py b/tests/integration/test_dynamic_accesslist.py
new file mode 100644
index 0000000..2072f5e
--- /dev/null
+++ b/tests/integration/test_dynamic_accesslist.py
@@ -0,0 +1,68 @@
1"""Hashes added to and removed from the blacklist while the tracker runs.
2
3The two FIFOs are read by threads of their own, which is also what makes
4this the test that drives those threads through a shutdown.
5"""
6
7import os
8import time
9import unittest
10
11from harness import TrackerTestCase
12
13BLOCKED = bytes(range(1, 21))
14
15
16def as_hex(info_hash):
17 return "".join("%02x" % b for b in info_hash)
18
19
20class DynamicAccesslist(TrackerTestCase):
21 config = ("access.blacklist {dir}/blacklist\n"
22 "access.fifo_add {dir}/add.fifo\n"
23 "access.fifo_delete {dir}/delete.fifo\n")
24 files = {"blacklist": b""}
25
26 def feed(self, name, info_hash):
27 """Writing to the FIFO blocks until the reader has it, so this also
28 tells us the thread is alive."""
29 with open(os.path.join(self.tracker.dir, name), "w") as fifo:
30 fifo.write("%s added by a test\n" % as_hex(info_hash))
31
32 def wait_for(self, info_hash, blocked, patience=5.0):
33 """The reader thread picks the hash up on its own schedule, so this
34 waits for the answer to change rather than assuming it already has."""
35 deadline = time.time() + patience
36 while time.time() < deadline:
37 answer = self.tracker.announce(info_hash)
38 if (b"failure reason" in answer) == blocked:
39 return True
40 time.sleep(0.05)
41 return False
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
61 def test_a_hash_can_be_blocked_and_released_while_running(self):
62 self.assertNotIn(b"failure reason", self.tracker.announce(BLOCKED))
63
64 self.feed("add.fifo", BLOCKED)
65 self.assertTrue(self.wait_for(BLOCKED, blocked=True), "the hash was never blocked")
66
67 self.feed("delete.fifo", BLOCKED)
68 self.assertTrue(self.wait_for(BLOCKED, blocked=False), "the hash was never released")
diff --git a/tests/integration/test_expiry.py b/tests/integration/test_expiry.py
new file mode 100644
index 0000000..5e6dc0a
--- /dev/null
+++ b/tests/integration/test_expiry.py
@@ -0,0 +1,44 @@
1"""What the expiry sweep finds, and what it must not find.
2
3A plain request is answered and the connection closed by http_close, not by
4the sweep. If that path left the descriptor's slot behind, the sweep would
5walk into it once the client timeout had passed and free a cookie that is
6already gone; the sanitizer build reports that and teardown turns it into a
7failure.
8
9Both halves share one tracker and one wait, because the wait is the whole
10cost of the test.
11
12The two numbers below mirror OT_CLIENT_TIMEOUT and
13OT_CLIENT_TIMEOUT_CHECKINTERVAL in FEATURES_integration.
14"""
15
16import socket
17import time
18import unittest
19
20from harness import TrackerTestCase
21
22CLIENT_TIMEOUT = 5
23CHECK_INTERVAL = 1
24
25
26class ExpirySweep(TrackerTestCase):
27 def test_the_sweep_takes_the_idle_and_leaves_the_answered(self):
28 idle = socket.create_connection(("127.0.0.1", self.tracker.port), timeout=5)
29 try:
30 # Enough for a kernel that holds a connection back until data
31 # arrives to hand it over, and far too little to be answered, so
32 # the tracker has accepted it and is waiting for the rest
33 idle.sendall(b"GET /ann")
34
35 self.assertEqual(self.tracker.announce(self.hash_for("expiry-sweep"))[b"complete"], 1)
36
37 time.sleep(CLIENT_TIMEOUT + 3 * CHECK_INTERVAL)
38
39 self.assertEqual(self.tracker.torrent_count(), 1, "the tracker stopped serving while sweeping")
40
41 idle.settimeout(5)
42 self.assertEqual(idle.recv(64), b"", "a connection that went quiet mid-request was not swept")
43 finally:
44 idle.close()
diff --git a/tests/integration/test_fullscrape.py b/tests/integration/test_fullscrape.py
new file mode 100644
index 0000000..45b3ffb
--- /dev/null
+++ b/tests/integration/test_fullscrape.py
@@ -0,0 +1,148 @@
1"""The full scrape, in every format the tracker offers.
2
3Each format is a separate writer, and they differ in more than cosmetics:
4one is binary, one is bencoded, three are line based and one dumps the
5tracker's own state for a restart. A worker thread produces them in chunks,
6so these also exercise the chunked transfer the ordinary replies never take.
7"""
8
9import gzip
10import struct
11import time
12import unittest
13
14from harness import TrackerTestCase, bdecode
15
16HEX = b"0123456789ABCDEF"
17
18
19class FullScrape(TrackerTestCase):
20 def setUp(self):
21 TrackerTestCase.setUp(self)
22 self.seeding = self.hash_for("fsA")
23 self.leeching = self.hash_for("fsB")
24 self.tracker.announce(self.seeding, port=6001, left=0)
25 self.tracker.announce(self.leeching, port=6002, left=4096)
26
27 def scrape_all(self, query, headers=None):
28 body, head = self.tracker.get_with_headers(query, headers)
29 if head.get("Content-Encoding") == "gzip":
30 body = gzip.decompress(body)
31 return body
32
33 # --------------------------------------------------------- bencoded
34
35 def test_a_bare_scrape_returns_every_torrent(self):
36 answer = bdecode(self.scrape_all("/scrape"))
37 self.assertIn(self.seeding, answer[b"files"])
38 self.assertIn(self.leeching, answer[b"files"])
39 self.assertEqual(answer[b"files"][self.seeding][b"complete"], 1)
40 self.assertEqual(answer[b"files"][self.leeching][b"incomplete"], 1)
41
42 def test_the_bencoded_format_matches_the_bare_scrape(self):
43 self.assertEqual(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben")), bdecode(self.scrape_all("/scrape")))
44
45 def test_a_full_scrape_can_be_gzipped(self):
46 plain = self.scrape_all("/scrape")
47 body, head = self.tracker.get_with_headers("/scrape", {"Accept-Encoding": "gzip"})
48 self.assertEqual(head.get("Content-Encoding"), "gzip")
49 self.assertEqual(gzip.decompress(body), plain)
50
51 # ----------------------------------------------------------- binary
52
53 def test_the_binary_format_is_a_hash_and_two_counts(self):
54 body = self.scrape_all("/stats?mode=tpbs&format=bin")
55 self.assertEqual(len(body) % 28, 0, "twenty byte hash plus two counts")
56 entries = {body[i : i + 20]: struct.unpack(">II", body[i + 20 : i + 28]) for i in range(0, len(body), 28)}
57 self.assertEqual(entries[self.seeding], (1, 0), "one seeder, no leechers")
58 self.assertEqual(entries[self.leeching], (0, 1), "no seeders, one leecher")
59
60 # ------------------------------------------------------- line based
61
62 def entries_from_lines(self, body):
63 return {line.split(b":")[0]: line.split(b":")[1:] for line in body.splitlines() if line}
64
65 def test_the_text_format_is_hex_colon_seeders_colon_leechers(self):
66 entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt"))
67 self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0"])
68 self.assertEqual(entries[self.leeching.hex().upper().encode()], [b"0", b"1"])
69
70 def test_the_text_plus_format_adds_the_completed_count(self):
71 entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp"))
72 self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0", b"0"])
73
74 def test_the_urlencoded_format_escapes_the_hash(self):
75 body = self.scrape_all("/stats?mode=tpbs&format=url")
76 lines = [line for line in body.splitlines() if line]
77 self.assertEqual(len(lines), 2)
78 for line in lines:
79 escaped = line.rsplit(b":", 2)[0]
80 self.assertIn(b"%", escaped, "these hashes are mostly unprintable bytes")
81
82 def test_the_state_dump_carries_a_stamp_rather_than_a_peer_count(self):
83 """What a restart reads back. The second column is the minute the
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."""
86 entries = self.entries_from_lines(self.scrape_all("/stats?mode=statedump"))
87 self.assertIn(self.seeding.hex().upper().encode(), entries)
88 stamp, completed = entries[self.seeding.hex().upper().encode()]
89 self.assertAlmostEqual(int(stamp), int(time.time()) // 60, delta=1, msg="announced a moment ago")
90 self.assertEqual(int(completed), 0)
91
92 # ------------------------------------------------------------ shape
93
94 def test_every_format_sees_the_same_torrents(self):
95 counts = {
96 "ben": len(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben"))[b"files"]),
97 "bin": len(self.scrape_all("/stats?mode=tpbs&format=bin")) // 28,
98 "txt": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt"))),
99 "txtp": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp"))),
100 "url": len([l for l in self.scrape_all("/stats?mode=tpbs&format=url").splitlines() if l]),
101 }
102 self.assertEqual(set(counts.values()), {2}, "all formats, two torrents: %r" % counts)
103
104
105class FullScrapeChunking(TrackerTestCase):
106 def test_a_scrape_larger_than_one_chunk_arrives_whole(self):
107 """The writer hands the socket a chunk at a time, so a scrape that
108 spans several is the case where the seams show."""
109 for i in range(400):
110 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=7000 + i, left=0)
111 answer = bdecode(self.tracker.get("/scrape"))
112 self.assertEqual(len(answer[b"files"]), 400)
113
114
115if __name__ == "__main__":
116 unittest.main()
117
118
119class PartialScrapeOrder(TrackerTestCase):
120 """A bencoded dictionary names its keys in order, once each. The full
121 scrape got that from walking the buckets; the partial scrape used to
122 echo whatever order the client asked in."""
123
124 def setUp(self):
125 TrackerTestCase.setUp(self)
126 self.hashes = [bytes([i]) + b"\0" * 19 for i in (9, 1, 5, 3, 7)]
127 for i, h in enumerate(self.hashes):
128 self.tracker.announce(h, port=6001 + i, left=0)
129
130 def scrape_many(self, hashes):
131 import urllib.parse
132
133 query = "&".join("info_hash=" + urllib.parse.quote_from_bytes(h, safe="") for h in hashes)
134 return bdecode(self.tracker.get("/scrape?" + query))
135
136 def test_the_keys_come_back_in_order(self):
137 answer = self.scrape_many(self.hashes)
138 self.assertEqual(list(answer[b"files"]), sorted(self.hashes))
139
140 def test_reversing_the_question_does_not_reverse_the_answer(self):
141 self.assertEqual(
142 list(self.scrape_many(self.hashes[::-1])[b"files"]), list(self.scrape_many(self.hashes)[b"files"])
143 )
144
145 def test_a_hash_asked_for_twice_is_named_once(self):
146 asked = [self.hashes[0], self.hashes[1], self.hashes[0]]
147 answer = self.scrape_many(asked)
148 self.assertEqual(list(answer[b"files"]), sorted({self.hashes[0], self.hashes[1]}))
diff --git a/tests/integration/test_keepalive.py b/tests/integration/test_keepalive.py
new file mode 100644
index 0000000..f9aa468
--- /dev/null
+++ b/tests/integration/test_keepalive.py
@@ -0,0 +1,146 @@
1"""Holding a connection open across several requests.
2
3The reply path has two shapes. A small answer goes out in one write and the
4connection is done with immediately. A large one is queued and finishes on a
5later pass through the event loop, by which time the workstruct that served
6the request has moved on, so whether to keep the connection has to be
7remembered on the connection itself.
8"""
9
10import time
11import unittest
12import urllib.parse
13
14from harness import TrackerTestCase, bdecode
15
16
17class KeepAlive(TrackerTestCase):
18 def announce_path(self, name, port=6881):
19 return "/announce?info_hash=%s&peer_id=%s&port=%d&left=0" % (
20 urllib.parse.quote_from_bytes(self.hash_for(name), safe=""),
21 "x" * 20,
22 port,
23 )
24
25 def test_two_requests_over_one_connection(self):
26 c = self.tracker.connect()
27 try:
28 c.send(self.announce_path("kaA"))
29 status, _, first = c.reply()
30 self.assertIn(b"200", status)
31 c.send(self.announce_path("kaB"))
32 status, _, second = c.reply()
33 self.assertIn(b"200", status)
34 self.assertIn(b"complete", bdecode(second))
35 finally:
36 c.close()
37
38 def test_close_ends_the_connection(self):
39 c = self.tracker.connect()
40 try:
41 c.send(self.announce_path("kaclose"), connection="close")
42 c.reply()
43 self.assertFalse(c.is_open(), "the tracker was asked to hang up")
44 finally:
45 c.close()
46
47 def test_a_connection_survives_a_reply_too_large_for_one_write(self):
48 """The case that was broken: a queued reply finished draining and the
49 connection was closed regardless of what the client had asked for."""
50 for i in range(400):
51 self.tracker.announce(bytes([i // 256, i % 256]) + b"\0" * 18, port=7000 + i, left=0)
52
53 c = self.tracker.connect()
54 try:
55 c.send("/scrape")
56 status, headers, body = c.reply()
57 self.assertIn(b"200", status)
58 self.assertGreater(len(body), 16384, "this reply has to outgrow one write")
59
60 c.send(self.announce_path("kaafter"))
61 status, _, after = c.reply()
62 self.assertIn(b"200", status)
63 self.assertIn(b"complete", bdecode(after))
64 finally:
65 c.close()
66
67 def test_several_requests_in_a_row(self):
68 c = self.tracker.connect()
69 try:
70 for i in range(20):
71 c.send(self.announce_path("karow%d" % i))
72 status, _, body = c.reply()
73 self.assertIn(b"200", status)
74 self.assertEqual(self.tracker.torrent_count(), 20)
75 finally:
76 c.close()
77
78 def test_without_the_header_the_connection_is_not_held(self):
79 """HTTP/1.1 calls a connection persistent unless told otherwise; this
80 tracker holds one only when asked by name. Pinned as it is."""
81 c = self.tracker.connect()
82 try:
83 c.send(self.announce_path("kanone"), connection=None)
84 c.reply()
85 self.assertFalse(c.is_open())
86 finally:
87 c.close()
88
89 def test_the_error_path_does_not_hold_the_connection(self):
90 c = self.tracker.connect()
91 try:
92 c.send("/announce?info_hash=short")
93 status, _, _ = c.reply()
94 self.assertIn(b"400", status)
95 finally:
96 c.close()
97
98 def test_an_error_after_a_kept_connection_is_still_an_error(self):
99 """The keep-alive decision used to be taken after the handler had run,
100 so an error reply inherited whatever the previous request wanted."""
101 c = self.tracker.connect()
102 try:
103 c.send(self.announce_path("kabefore"))
104 self.assertIn(b"200", c.reply()[0])
105 c.send("/announce?info_hash=short")
106 self.assertIn(b"400", c.reply()[0])
107 finally:
108 c.close()
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
144
145if __name__ == "__main__":
146 unittest.main()
diff --git a/tests/integration/test_livesync.py b/tests/integration/test_livesync.py
new file mode 100644
index 0000000..e146d93
--- /dev/null
+++ b/tests/integration/test_livesync.py
@@ -0,0 +1,240 @@
1"""Live sync, driven over the multicast group a cluster would use.
2
3Live sync sits behind WANT_SYNC_LIVE, so these only run against a binary
4built with it: make check-livesync. Against any other build they skip, which
5is what the feature list in -v is for.
6"""
7
8import socket
9import struct
10import subprocess
11import unittest
12
13from harness import TRACKER, Tracker, TrackerTestCase
14
15# enum { OT_SYNC_PEER4, OT_SYNC_PEER6 } in src/ot_livesync.c
16SYNC_PEER4 = 0
17SYNC_PEER6 = 1
18
19# src/trackerlogic.h
20FLAG_SEEDING = 0x80
21FLAG_COMPLETED = 0x40
22FLAG_STOPPED = 0x20
23
24
25def has_livesync():
26 done = subprocess.run([TRACKER, "-v"], capture_output=True, timeout=30)
27 return b"WANT_SYNC_LIVE" in done.stderr
28
29
30def peer4(address, port, flags):
31 """Four bytes of address, two of port, one of flags, one the tracker
32 overwrites with its own idea of the time."""
33 return socket.inet_aton(address) + struct.pack("!H", port) + bytes([flags, 0])
34
35
36def peer6(address, port, flags):
37 return socket.inet_pton(socket.AF_INET6, address) + struct.pack("!H", port) + bytes([flags, 0])
38
39
40def packet(kind, entries, tracker_id=0xDEADBEEF):
41 body = b"".join(info_hash + peer for info_hash, peer in entries)
42 return struct.pack("!I", tracker_id) + struct.pack("!I", kind) + body
43
44
45@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
46class LiveSyncIn(TrackerTestCase):
47 config = "livesync.cluster.listen 127.0.0.1:{livesync_port}\nlivesync.cluster.node_ip 127.0.0.1\n"
48
49 def counts(self, info_hash):
50 """Seeders and leechers a scrape reports for one torrent."""
51 files = self.tracker.scrape(info_hash)[b"files"]
52 if info_hash not in files:
53 return None
54 entry = files[info_hash]
55 return entry[b"complete"], entry[b"incomplete"]
56
57 def test_a_synced_seeder_arrives(self):
58 info_hash = self.hash_for("sync-seed")
59 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.3", 6881, FLAG_SEEDING))]))
60 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)),
61 "scrape says %r" % (self.counts(info_hash),))
62
63 def test_a_synced_leecher_arrives(self):
64 info_hash = self.hash_for("sync-leech")
65 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.4", 6881, 0))]))
66 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (0, 1)),
67 "scrape says %r" % (self.counts(info_hash),))
68
69 def test_a_v6_peer_arrives(self):
70 info_hash = self.hash_for("sync-v6")
71 self.tracker.livesync_send(packet(SYNC_PEER6, [(info_hash, peer6("2001:db8::1", 6881, FLAG_SEEDING))]))
72 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)),
73 "scrape says %r" % (self.counts(info_hash),))
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
88 def test_one_packet_carries_several_torrents(self):
89 hashes = [self.hash_for("sync-many-%d" % i) for i in range(4)]
90 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (5 + i), 6881, FLAG_SEEDING))
91 for i, h in enumerate(hashes)]))
92 self.assertTrue(self.tracker.wait_until(lambda: all(self.counts(h) == (1, 0) for h in hashes)))
93
94 def test_a_stopped_peer_is_taken_away_again(self):
95 info_hash = self.hash_for("sync-stop")
96 peer = peer4("10.1.2.9", 6881, FLAG_SEEDING)
97 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer)]))
98 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)))
99
100 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.9", 6881, FLAG_STOPPED))]))
101 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) in (None, (0, 0))),
102 "scrape still says %r" % (self.counts(info_hash),))
103
104 def test_a_truncated_entry_is_dropped(self):
105 """The loop takes whole hash and peer pairs and leaves a short tail
106 where it is, so the complete entry before it still lands."""
107 good, short = self.hash_for("sync-good"), self.hash_for("sync-short")
108 payload = packet(SYNC_PEER4, [(good, peer4("10.1.2.10", 6881, FLAG_SEEDING))]) + short + b"\x0a\x01"
109 self.tracker.livesync_send(payload)
110 self.assertTrue(self.tracker.wait_until(lambda: self.counts(good) == (1, 0)))
111 self.assertIsNone(self.counts(short))
112
113 def test_an_unknown_packet_type_is_ignored(self):
114 info_hash = self.hash_for("sync-unknown")
115 self.tracker.livesync_send(packet(99, [(info_hash, peer4("10.1.2.11", 6881, FLAG_SEEDING))]))
116 self.assertFalse(self.tracker.wait_until(lambda: self.counts(info_hash) is not None, timeout=1))
117
118 def test_synced_peers_are_counted(self):
119 """The live sync worker keeps its own tally like every other worker,
120 and ?mode=syncs is the sum of them."""
121 before = int(self.tracker.stats("syncs").split()[0])
122 hashes = [self.hash_for("sync-count-%d" % i) for i in range(3)]
123 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (20 + i), 6881, FLAG_SEEDING))
124 for i, h in enumerate(hashes)]))
125 self.assertTrue(self.tracker.wait_until(
126 lambda: int(self.tracker.stats("syncs").split()[0]) == before + 3),
127 "syncs says %s" % self.tracker.stats("syncs").split()[0])
128
129 def test_a_packet_with_nothing_but_a_header_is_ignored(self):
130 before = self.tracker.torrent_count()
131 self.tracker.livesync_send(struct.pack("!I", 0xDEADBEEF) + struct.pack("!I", SYNC_PEER4))
132 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != before, timeout=1))
133
134
135@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
136class LiveSyncAccess(TrackerTestCase):
137 """Nothing blesses 127.0.0.1 here, so the tracker should take nothing
138 from it. Source address checking is all live sync has."""
139
140 config = "livesync.cluster.listen 127.0.0.1:{livesync_port}\nlivesync.cluster.node_ip 10.0.0.1\n"
141
142 def test_an_unblessed_sender_is_ignored(self):
143 info_hash = self.hash_for("sync-unblessed")
144 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.12", 6881, FLAG_SEEDING))]))
145 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != 0, timeout=1))
146
147
148@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
149class LiveSyncUnconfigured(TrackerTestCase):
150 """A binary that has the feature but no cluster to join. Somebody whose
151 packager turned WANT_SYNC_LIVE on did not ask for live sync and should
152 not be able to tell that it is there."""
153
154 config = ""
155
156 def test_the_tracker_runs_anyway(self):
157 info_hash = self.hash_for("no-cluster")
158 self.tracker.announce(info_hash, port=6881, left=0)
159 self.assertEqual(self.tracker.torrent_count(), 1)
160
161 def test_nothing_is_said_about_the_missing_cluster(self):
162 self.assertNotIn("sync", self.tracker.output().lower())
163
164 def test_no_socket_is_bound_for_it(self):
165 """A configured tracker holds the wildcard address on that port, so
166 taking it here proves nothing was started."""
167 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
168 try:
169 sock.bind(("0.0.0.0", self.tracker.livesync_port))
170 finally:
171 sock.close()
172
173 def test_announcing_stays_clean(self):
174 """Enough announces to pass the watermark that would flush an
175 outgoing buffer, if there were one to flush. The sanitizers in this
176 build turn anything the attempt touched into a failure."""
177 for i in range(200):
178 self.tracker.announce(self.hash_for("no-cluster-%d" % i), port=6881 + i, left=0)
179 self.assertEqual(self.tracker.torrent_count(), 200)
180
181
182# RFC 2365 sets 239.192.0.0/14 aside for exactly this kind of use
183OWN_GROUP = "239.192.0.7"
184# A group nothing in this suite ever joins. Deliberately not the default one:
185# other trackers here do join that, on ports the harness picks at random, and
186# a socket bound to the wildcard address shares a port's multicast traffic
187# with anything else on the host that has joined the group it is addressed
188# to. Two clusters sharing a host and a port is pathological in the field but
189# routine in a test suite.
190UNJOINED_GROUP = "239.192.0.99"
191
192
193@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
194class LiveSyncGroup(TrackerTestCase):
195 config = ("livesync.cluster.group %s\n"
196 "livesync.cluster.listen 127.0.0.1:{livesync_port}\n"
197 "livesync.cluster.node_ip 127.0.0.1\n" % OWN_GROUP)
198
199 def test_the_configured_group_is_joined(self):
200 info_hash = self.hash_for("own-group")
201 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.3.1", 6881, FLAG_SEEDING))]),
202 group=OWN_GROUP)
203 self.assertTrue(self.tracker.wait_until(lambda: self.tracker.torrent_count() == 1))
204
205 def test_another_group_is_left_alone(self):
206 """A cluster that picked its own group hears nothing from the others."""
207 info_hash = self.hash_for("not-our-group")
208 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.3.2", 6881, FLAG_SEEDING))]),
209 group=UNJOINED_GROUP)
210 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != 0, timeout=1))
211
212
213@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
214class LiveSyncGroupRefused(unittest.TestCase):
215 """A cluster that asked for a group of its own must not quietly end up on
216 the one every other opentracker is on, so a line that does not name a
217 group stops the tracker rather than falling back."""
218
219 def start_with(self, group):
220 return Tracker("livesync.cluster.group %s\n"
221 "livesync.cluster.listen 127.0.0.1:{livesync_port}\n"
222 "livesync.cluster.node_ip 127.0.0.1\n" % group)
223
224 def test_a_unicast_address_stops_the_tracker(self):
225 with self.assertRaises(AssertionError) as caught:
226 self.start_with("10.0.0.1")
227 self.assertIn("multicast address", str(caught.exception))
228
229 def test_so_does_something_that_is_not_an_address(self):
230 with self.assertRaises(AssertionError) as caught:
231 self.start_with("not-an-address")
232 self.assertIn("multicast address", str(caught.exception))
233
234 def test_a_group_at_either_end_of_the_range_is_taken(self):
235 for group in ("224.0.0.1", "239.255.255.255"):
236 tracker = self.start_with(group)
237 try:
238 self.assertEqual(tracker.torrent_count(), 0)
239 finally:
240 tracker.stop()
diff --git a/tests/integration/test_shutdown.py b/tests/integration/test_shutdown.py
new file mode 100644
index 0000000..063d779
--- /dev/null
+++ b/tests/integration/test_shutdown.py
@@ -0,0 +1,58 @@
1"""That every thread the tracker starts also ends when it is asked to stop.
2
3The rest of the suite stops a tracker too, so a thread left behind already
4shows up in teardown as the complaint that the tracker had to be killed.
5These ask for the arrangements that park a thread in a blocking read in the
6first place, and they time the exit, because a reader woken only by its own
7receive timeout passes a correctness check while taking a second over it.
8"""
9
10import time
11import unittest
12
13from harness import Tracker, TrackerTestCase
14
15# Generous enough for a platform where shutting the socket down does not wake
16# the reader and the receive timeout has to expire, tight enough that a reader
17# which is never woken at all fails instead of hanging the suite
18PATIENCE = 3.0
19
20
21def time_the_exit(extra_config):
22 tracker = Tracker(extra_config)
23 try:
24 # Serve one request of each kind first, so the threads that are about
25 # to be joined have actually run
26 tracker.announce(b"shutdown-probe\0\0\0\0\0\0")
27 sock, connection_id = tracker.udp_connect()
28 tracker.udp_announce(sock, connection_id, b"shutdown-probe\0\0\0\0\0\0")
29 sock.close()
30 started = time.time()
31 complaints = tracker.stop()
32 return time.time() - started, complaints
33 finally:
34 tracker._cleanup()
35
36
37class UdpWorkers(TrackerTestCase):
38 config = "listen.udp.workers 8\n"
39
40 def test_announce_reaches_one_of_eight_workers(self):
41 """Keeps the workers from being merely started and never used."""
42 sock, connection_id = self.tracker.udp_connect()
43 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("eight-workers"))
44 sock.close()
45 self.assertEqual(answer["seeders"], 1)
46
47
48class ShutdownEndsEveryThread(unittest.TestCase):
49 def test_eight_udp_workers_are_joined(self):
50 took, complaints = time_the_exit("listen.udp.workers 8\n")
51 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
52 self.assertLess(took, PATIENCE, "stopping eight udp workers took %.1f s" % took)
53
54 def test_udp_in_the_event_loop_still_stops(self):
55 """Worker count zero leaves no thread to join, which must also work."""
56 took, complaints = time_the_exit("listen.udp.workers 0\n")
57 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
58 self.assertLess(took, PATIENCE, "stopping without workers took %.1f s" % took)
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
new file mode 100644
index 0000000..46ca39b
--- /dev/null
+++ b/tests/integration/test_stats.py
@@ -0,0 +1,146 @@
1"""The /stats endpoint.
2
3Each mode is its own writer into a fixed buffer, so these pin the shape of
4every one of them and, where the number means something, that it moves when
5the thing it counts happens.
6"""
7
8import re
9import unittest
10import urllib.error
11import xml.etree.ElementTree
12
13from harness import TrackerTestCase
14
15# The modes a default build answers. "tpbs" and "statedump" are full scrapes
16# and belong to test_fullscrape; "woodpeckers" sits behind a
17# feature flag this build does not set.
18MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"]
19TEXT_MODES = ["herr", "top10", "top100", "renew"]
20
21
22class StatsShape(TrackerTestCase):
23 def test_every_mode_answers_something(self):
24 for mode in MRTG_MODES + TEXT_MODES + ["everything"]:
25 self.assertTrue(self.tracker.stats(mode), "mode %s answered empty" % mode)
26
27 def test_an_mrtg_mode_opens_with_two_numbers(self):
28 """MRTG reads the first two lines as counters and the rest as labels,
29 so the order matters to something outside this project."""
30 for mode in MRTG_MODES:
31 lines = self.tracker.stats(mode).splitlines()
32 self.assertGreaterEqual(len(lines), 2, "mode %s" % mode)
33 for line in lines[:2]:
34 self.assertRegex(line, rb"^\d+$", "mode %s line %r" % (mode, line))
35
36 def test_the_busy_mode_is_gone(self):
37 """It was listed in the mode table and implemented nowhere, so it only
38 ever answered 500. Removed rather than written: picking poisoning
39 networks out stopped being meaningful once consumer lines became bot
40 hosts and v6 made the address space too large to watch."""
41 with self.assertRaises(urllib.error.HTTPError) as caught:
42 self.tracker.stats("busy")
43 self.assertEqual(caught.exception.code, 400, "an unknown mode, like any other")
44
45 def test_an_unknown_mode_is_refused(self):
46 with self.assertRaises(urllib.error.HTTPError) as caught:
47 self.tracker.stats("nosuchmode")
48 self.assertEqual(caught.exception.code, 400)
49
50 def test_everything_is_well_formed_xml(self):
51 root = xml.etree.ElementTree.fromstring(self.tracker.stats("everything").decode())
52 self.assertEqual(root.tag, "stats")
53 self.assertIsNotNone(root.find("torrents/count_mutex"))
54 self.assertIsNotNone(root.find("connections/tcp/announce"))
55
56 def test_the_version_mode_is_gone(self):
57 """Which build a tracker is and what went into it is of use to whoever
58 attacks it and to nobody else on the far end of a socket. It is
59 reported by -v, to whoever already has the binary."""
60 with self.assertRaises(urllib.error.HTTPError) as caught:
61 self.tracker.stats("version")
62 self.assertEqual(caught.exception.code, 400, "an unknown mode, like any other")
63
64 def test_everything_does_not_name_the_build(self):
65 self.assertNotIn(b"opentracker 1", self.tracker.stats("everything"))
66
67 def test_everything_does_not_name_the_tracker_id(self):
68 """The id a tracker recognises its own live sync packets by. Knowing
69 it is of no use to a client and of some use to whoever would like a
70 tracker to discard what it is told."""
71 self.assertNotIn(b"tracker_id", self.tracker.stats("everything"))
72
73
74class StatsCount(TrackerTestCase):
75 def test_the_torrent_count_follows_the_torrents(self):
76 before = self.tracker.torrent_count()
77 self.tracker.announce(self.hash_for("statA"), port=6001, left=0)
78 self.assertEqual(self.tracker.torrent_count(), before + 1)
79 self.tracker.announce(self.hash_for("statB"), port=6002, left=0)
80 self.assertEqual(self.tracker.torrent_count(), before + 2)
81
82 def test_the_peer_count_separates_seeders_from_the_rest(self):
83 self.tracker.announce(self.hash_for("statpeers"), port=6001, left=0)
84 self.tracker.announce(self.hash_for("statpeers"), port=6002, left=4096)
85 peers, seeds = self.tracker.stats("peer").splitlines()[:2]
86 self.assertEqual(int(peers), 2)
87 self.assertEqual(int(seeds), 1)
88
89 def test_the_completed_count_follows_the_completed_event(self):
90 before = int(self.tracker.stats("completed").splitlines()[0])
91 self.tracker.announce(self.hash_for("statdone"), port=6001, left=0, event="completed")
92 self.assertEqual(int(self.tracker.stats("completed").splitlines()[0]), before + 1)
93
94 def test_a_bad_request_is_counted_as_an_http_error(self):
95 before = self.tracker.stats("herr")
96 try:
97 self.tracker.stats("nosuchmode")
98 except urllib.error.HTTPError:
99 pass
100 after = self.tracker.stats("herr")
101 self.assertNotEqual(before, after, "no error counter moved")
102
103 def test_the_tcp_counter_follows_tcp_requests(self):
104 before = int(self.tracker.stats("tcp4").splitlines()[0])
105 for _ in range(3):
106 self.tracker.announce(self.hash_for("stattcp"), port=6001, left=0)
107 self.assertGreaterEqual(int(self.tracker.stats("tcp4").splitlines()[0]), before + 3)
108
109 def test_the_udp_counter_follows_udp_requests(self):
110 before = int(self.tracker.stats("udp4").splitlines()[0])
111 sock, connection_id = self.tracker.udp_connect()
112 try:
113 self.tracker.udp_announce(sock, connection_id, self.hash_for("statudp"), left=0)
114 finally:
115 sock.close()
116 self.assertGreater(int(self.tracker.stats("udp4").splitlines()[0]), before)
117
118 def test_the_scrape_counter_follows_scrapes(self):
119 before = int(self.tracker.stats("scrp").splitlines()[0])
120 self.tracker.scrape(self.hash_for("statscrape"))
121 self.assertEqual(int(self.tracker.stats("scrp").splitlines()[0]), before + 1)
122
123
124class StatsTop(TrackerTestCase):
125 def test_the_top_list_ranks_by_peer_count(self):
126 busy = self.hash_for("topbusy")
127 quiet = self.hash_for("topquiet")
128 for port in range(6001, 6006):
129 self.tracker.announce(busy, port=port, left=0)
130 self.tracker.announce(quiet, port=6100, left=0)
131
132 body = self.tracker.stats("top10")
133 self.assertIn(b"Top 10 torrents by peers", body)
134 ranked = re.findall(rb"\t(\d+)\t([0-9A-F]{40})", body.split(b"by seeds")[0])
135 self.assertEqual(ranked[0][1], busy.hex().upper().encode(), "the busy torrent ranks first")
136 self.assertEqual(int(ranked[0][0]), 5)
137
138 def test_the_top_list_has_three_sections(self):
139 self.tracker.announce(self.hash_for("topsections"), port=6001, left=0)
140 body = self.tracker.stats("top100")
141 for heading in (b"by peers", b"by seeds", b"by leechers"):
142 self.assertIn(heading, body)
143
144
145if __name__ == "__main__":
146 unittest.main()
diff --git a/tests/integration/test_tcpworkers.py b/tests/integration/test_tcpworkers.py
new file mode 100644
index 0000000..e43612a
--- /dev/null
+++ b/tests/integration/test_tcpworkers.py
@@ -0,0 +1,67 @@
1"""The tracker with its tcp side handed to worker threads.
2
3With workers configured, a connection is accepted and answered on a worker's
4own stack. Anything it cannot finish there is copied to the heap and handed
5to the event loop, which is the one place where a worker and the main thread
6touch the same structures, so these drive all three outcomes: answered
7inline, held open, and parked waiting for another thread entirely.
8"""
9
10import threading
11import unittest
12import urllib.parse
13
14from harness import TrackerTestCase, bdecode
15
16WORKERS = 4
17
18
19class TcpWorkers(TrackerTestCase):
20 config = "listen.tcp.workers %d\n" % WORKERS
21
22 def announce_path(self, name, port=6881):
23 return "/announce?info_hash=%s&peer_id=%s&port=%d&left=0" % (
24 urllib.parse.quote_from_bytes(self.hash_for(name), safe=""),
25 "x" * 20,
26 port,
27 )
28
29 def test_many_at_once_are_all_answered(self):
30 """Every worker gets something to do, and the swarm adds up."""
31 info_hash = self.hash_for("workers-swarm")
32 errors = []
33
34 def announce(index):
35 try:
36 self.tracker.announce(info_hash, peer_id=b"-OT0001-%012d" % index, port=7000 + index, left=0)
37 except Exception as problem: # noqa: BLE001 - reported, not swallowed
38 errors.append("%d: %r" % (index, problem))
39
40 threads = [threading.Thread(target=announce, args=(i,)) for i in range(32)]
41 for thread in threads:
42 thread.start()
43 for thread in threads:
44 thread.join()
45
46 self.assertEqual(errors, [], "\n".join(errors))
47 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"complete"], 32)
48
49 def test_a_kept_connection_outlives_the_worker_that_took_it(self):
50 """Keep-alive is the plain case of a connection a worker hands on."""
51 connection = self.tracker.connect()
52 try:
53 for i in range(4):
54 connection.send(self.announce_path("workers-kept"))
55 status, _, body = connection.reply()
56 self.assertIn(b"200", status)
57 self.assertIn(b"complete", bdecode(body))
58 finally:
59 connection.close()
60
61 def test_a_full_scrape_asked_for_by_a_worker_still_arrives(self):
62 """The reply is built by another thread, so the worker parks the
63 connection waiting for nothing at all before handing it over."""
64 for i in range(20):
65 self.tracker.announce(bytes([i]) + b"\0" * 19, port=7100 + i, left=0)
66 body = self.tracker.get("/scrape")
67 self.assertEqual(len(bdecode(body)[b"files"]), 20)
diff --git a/tests/integration/test_udp.py b/tests/integration/test_udp.py
new file mode 100644
index 0000000..8a255ec
--- /dev/null
+++ b/tests/integration/test_udp.py
@@ -0,0 +1,218 @@
1"""The UDP tracker protocol, BEP 15.
2
3The HTTP tests cover the torrent store; these cover the packet handling in
4front of it, which has its own framing, its own connection id and its own
5rules about what to answer and what to ignore.
6"""
7
8import socket
9import struct
10import unittest
11
12from harness import Tracker, TrackerTestCase
13
14MAGIC = 0x41727101980
15
16
17class UdpProtocol(TrackerTestCase):
18 def test_connect_echoes_the_transaction_id(self):
19 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20 sock.settimeout(5)
21 try:
22 sock.sendto(struct.pack(">QII", MAGIC, 0, 0xDEADBEEF), ("127.0.0.1", self.tracker.port))
23 action, transaction, connection_id = struct.unpack(">IIQ", sock.recv(2048)[:16])
24 self.assertEqual(action, 0)
25 self.assertEqual(transaction, 0xDEADBEEF)
26 self.assertNotEqual(connection_id, 0)
27 finally:
28 sock.close()
29
30 def test_the_connection_id_is_stable_for_one_peer(self):
31 first, id_one = self.tracker.udp_connect()
32 second, id_two = self.tracker.udp_connect()
33 try:
34 self.assertEqual(id_one, id_two)
35 finally:
36 first.close()
37 second.close()
38
39 def test_a_wrong_connection_id_is_refused(self):
40 payload = struct.pack(">QII20s20sQQQIIIiH", 0, 1, 2, self.hash_for("udpbad"), b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881)
41 answer = self.tracker.udp_raw(payload)
42 self.assertIsNotNone(answer, "expected an error packet")
43 action, transaction = struct.unpack(">II", answer[:8])
44 self.assertEqual(action, 3, "action 3 is the error packet")
45 self.assertIn(b"Connection ID missmatch", answer[8:])
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
58 def test_a_packet_shorter_than_the_header_is_ignored(self):
59 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15))
60
61 def test_an_unknown_action_is_ignored(self):
62 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC, 9, 1)))
63
64 def test_connect_requires_the_protocol_magic(self):
65 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC + 1, 0, 1)))
66
67 def test_an_announce_cut_short_is_ignored(self):
68 sock, connection_id = self.tracker.udp_connect()
69 try:
70 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", connection_id, 1, 1) + b"\0" * 40))
71 finally:
72 sock.close()
73
74
75class UdpAnnounce(TrackerTestCase):
76 def test_a_seeder_is_counted_as_a_seeder(self):
77 sock, connection_id = self.tracker.udp_connect()
78 try:
79 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpseed"), left=0)
80 self.assertEqual(answer["seeders"], 1)
81 self.assertEqual(answer["leechers"], 0)
82 self.assertGreater(answer["interval"], 0)
83 finally:
84 sock.close()
85
86 def test_a_leecher_is_counted_as_a_leecher(self):
87 sock, connection_id = self.tracker.udp_connect()
88 try:
89 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpleech"), left=1024)
90 self.assertEqual(answer["seeders"], 0)
91 self.assertEqual(answer["leechers"], 1)
92 finally:
93 sock.close()
94
95 def test_stopped_removes_the_peer(self):
96 info_hash = self.hash_for("udpstop")
97 sock, connection_id = self.tracker.udp_connect()
98 try:
99 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
100 self.tracker.udp_announce(sock, connection_id, info_hash, left=0, event=3)
101 answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=1024)
102 self.assertEqual(answer["seeders"], 0, "the seeder announced stopped")
103 finally:
104 sock.close()
105
106 def test_an_announce_over_udp_is_visible_over_http(self):
107 """One torrent store behind both bearers, not two."""
108 info_hash = self.hash_for("udpcross")
109 sock, connection_id = self.tracker.udp_connect()
110 try:
111 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
112 finally:
113 sock.close()
114 scrape = self.tracker.scrape(info_hash)
115 self.assertEqual(scrape[b"files"][info_hash][b"complete"], 1)
116
117 def test_the_peer_list_carries_the_announcing_peer(self):
118 info_hash = self.hash_for("udppeers")
119 sock, connection_id = self.tracker.udp_connect()
120 try:
121 answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=0, port=6881)
122 self.assertEqual(len(answer["peers"]) % 6, 0, "v4 peers are six bytes each")
123 self.assertGreaterEqual(len(answer["peers"]), 6)
124 self.assertEqual(struct.unpack(">H", answer["peers"][4:6])[0], 6881)
125 finally:
126 sock.close()
127
128
129class UdpScrape(TrackerTestCase):
130 def test_scrape_reports_the_swarm(self):
131 info_hash = self.hash_for("udpscrape")
132 sock, connection_id = self.tracker.udp_connect()
133 try:
134 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
135 seeders, completed, leechers = self.tracker.udp_scrape(sock, connection_id, [info_hash])[0]
136 self.assertEqual(seeders, 1)
137 self.assertEqual(leechers, 0)
138 self.assertEqual(completed, 0)
139 finally:
140 sock.close()
141
142 def test_an_unknown_hash_scrapes_as_empty(self):
143 sock, connection_id = self.tracker.udp_connect()
144 try:
145 self.assertEqual(self.tracker.udp_scrape(sock, connection_id, [self.hash_for("udpnone")])[0], (0, 0, 0))
146 finally:
147 sock.close()
148
149 def test_several_hashes_answer_in_order(self):
150 seeding = self.hash_for("udpmultiA")
151 leeching = self.hash_for("udpmultiB")
152 sock, connection_id = self.tracker.udp_connect()
153 try:
154 self.tracker.udp_announce(sock, connection_id, seeding, left=0)
155 self.tracker.udp_announce(sock, connection_id, leeching, left=1024)
156 answers = self.tracker.udp_scrape(sock, connection_id, [seeding, leeching])
157 self.assertEqual(answers[0][0], 1, "first hash is the seeded one")
158 self.assertEqual(answers[1][2], 1, "second hash is the leeched one")
159 finally:
160 sock.close()
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
184
185class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
186 """The harness writes its listen lines first, so this directive lands
187 below them: the position a config file should not care about."""
188
189 config = "listen.udp.workers 4\n"
190
191 def test_the_tracker_starts_and_still_answers_udp(self):
192 sock, connection_id = self.tracker.udp_connect()
193 try:
194 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpworkers"), left=0)
195 self.assertEqual(answer["seeders"], 1)
196 finally:
197 sock.close()
198
199
200if __name__ == "__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/integration/test_version.py b/tests/integration/test_version.py
new file mode 100644
index 0000000..66f570d
--- /dev/null
+++ b/tests/integration/test_version.py
@@ -0,0 +1,36 @@
1"""The -v report, which is where a build says what went into it.
2
3Driving the binary is the only way to see this: the feature list is a table
4of #ifdefs, so it is only true for the flags the binary itself was built with.
5"""
6
7import subprocess
8import unittest
9
10from harness import TRACKER
11
12
13class VersionFlag(unittest.TestCase):
14 def report(self):
15 # -v writes to stderr and exits before it binds anything
16 done = subprocess.run([TRACKER, "-v"], capture_output=True, timeout=30)
17 self.assertEqual(done.returncode, 0, done.stderr)
18 return done.stderr.decode()
19
20 def test_first_line_names_the_release(self):
21 # The commit in brackets is there in a checkout and in a release
22 # tarball, and absent in a build that had neither to ask.
23 first = self.report().splitlines()[0]
24 self.assertRegex(first, r"^opentracker \d+\.\d+\.\d+( \(\S+\))?$")
25
26 def test_names_the_event_mechanism(self):
27 self.assertRegex(self.report(), r"(?m)^events: (epoll|kqueue|poll)$")
28
29 def test_lists_the_features_this_build_has(self):
30 # The Makefile builds this binary with these and not with those, so a
31 # feature table that stops following the build fails here.
32 report = self.report()
33 for want in ("WANT_KEEPALIVE", "WANT_ACCESSLIST_BLACK", "WANT_DYNAMIC_ACCESSLIST"):
34 self.assertIn(want, report)
35 for unwanted in ("WANT_SPOT_WOODPECKER", "WANT_V4_ONLY", "WANT_RESTRICT_STATS"):
36 self.assertNotIn(unwanted, report)
diff --git a/tests/runner.c b/tests/runner.c
new file mode 100644
index 0000000..2398991
--- /dev/null
+++ b/tests/runner.c
@@ -0,0 +1,115 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <sys/wait.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "test.h"
13
14struct module {
15 const char *name;
16 void (*run)(void);
17};
18
19static const struct module modules[] = {{"ot_urlencoded", test_urlencoded},
20 {"ot_iovec", test_iovec},
21 {"ot_vector", test_vector},
22 {"ot_random", test_random},
23 {"ot_hex", test_hex},
24 {"ot_scan", test_scan},
25 {"ot_buf", test_buf},
26 {"ot_ip", test_ip},
27 {"ot_socket", test_socket},
28 {"ot_mutex", test_mutex},
29 {"trackerlogic", test_trackerlogic},
30 {"clean", test_clean},
31 {"ot_workqueue", test_workqueue},
32 {"ot_batch", test_batch},
33 {"ot_fdstate", test_fdstate},
34 {"ot_event", test_event},
35 {"ot_fmt", test_fmt},
36 {"ot_accesslist", test_accesslist},
37 {NULL, NULL}};
38
39struct tally {
40 unsigned long checks;
41 unsigned long failures;
42};
43
44/* Each module runs in a child of its own, so that a crash or a sanitizer
45 abort costs that module's results rather than every module after it. The
46 child reports its tally through a pipe; one that dies without reporting is
47 counted as a failure under its own name. */
48static void run_forked(const struct module *m) {
49 struct tally tally = {0, 0};
50 int pipefd[2], status = 0;
51 pid_t child;
52 ssize_t got;
53
54 if (pipe(pipefd)) {
55 test_failf(__FILE__, __LINE__, "pipe failed, cannot isolate %s", m->name);
56 return;
57 }
58
59 fflush(stdout); /* or the child inherits a copy and prints it again */
60 child = fork();
61 if (child < 0) {
62 close(pipefd[0]);
63 close(pipefd[1]);
64 test_failf(__FILE__, __LINE__, "fork failed, cannot isolate %s", m->name);
65 return;
66 }
67
68 if (!child) {
69 close(pipefd[0]);
70 test_checks = test_failures = 0;
71 m->run();
72 tally.checks = test_checks;
73 tally.failures = test_failures;
74 if (write(pipefd[1], &tally, sizeof(tally)) != (ssize_t)sizeof(tally))
75 _exit(1);
76 fflush(stdout);
77 _exit(0);
78 }
79
80 close(pipefd[1]);
81 got = read(pipefd[0], &tally, sizeof(tally));
82 close(pipefd[0]);
83 while (waitpid(child, &status, 0) < 0)
84 ;
85
86 if (got == (ssize_t)sizeof(tally)) {
87 test_checks += tally.checks;
88 test_failures += tally.failures;
89 }
90 if (got != (ssize_t)sizeof(tally) || !WIFEXITED(status) || WEXITSTATUS(status))
91 test_failf(__FILE__, __LINE__, "%s did not run to the end", m->name);
92}
93
94/* Run every module, or only those whose name contains argv[1].
95 OT_TEST_FORK=0 keeps everything in one process, which is what a debugger
96 wants. */
97int main(int argc, char **argv) {
98 const char *fork_setting = getenv("OT_TEST_FORK");
99 int isolate = !fork_setting || strcmp(fork_setting, "0");
100 const struct module *m;
101
102 for (m = modules; m->name; ++m) {
103 if (argc > 1 && !strstr(m->name, argv[1]))
104 continue;
105 test_module(m->name);
106 if (!isolate) {
107 m->run();
108 continue;
109 }
110 test_case("the module runs to the end");
111 run_forked(m);
112 }
113
114 return test_summary();
115}
diff --git a/tests/stubs.c b/tests/stubs.c
new file mode 100644
index 0000000..b8ab174
--- /dev/null
+++ b/tests/stubs.c
@@ -0,0 +1,48 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* Stubs for symbols the modules under test reference but never reach along
5 the paths the tests exercise. If a test ever does reach one, the missing
6 behaviour should be supplied here rather than the test weakened. */
7
8/* Opentracker */
9#include "ot_stats.h"
10#include "trackerlogic.h"
11
12/* ot_accesslist.c is built with WANT_ACCESSLIST_BLACK so that the hash parser
13 is reachable. These two belong to accesslist_readfile and the reload worker,
14 neither of which any test drives. */
15_Atomic int g_opentracker_running;
16
17/* ot_mutex.c wakes the main loop through the self pipe when a result is
18 ready. The queue tests never get that far. */
19int g_self_pipe[2] = {-1, -1};
20long io_trywrite(long d, const char *buf, long len) {
21 (void)d;
22 (void)buf;
23 return len;
24}
25
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
28 rather than linked in and left to run threads of their own. */
29/* ot_clean.c is in the unit build for t_clean, so its thread control is the
30 real thing and only the stats hook it calls is stubbed here. */
31void fullscrape_init(void) {}
32void fullscrape_deinit(void) {}
33void stats_cleanup(void) {}
34void livesync_tell(struct ot_workstruct *ws) { (void)ws; }
35void stats_init(void) {}
36void stats_deinit(void) {}
37void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FLAG proto, uintptr_t event_data) {
38 (void)ws;
39 (void)event;
40 (void)proto;
41 (void)event_data;
42}
43void stats_counters_register(struct ot_workstruct *ws) { (void)ws; }
44void stats_counters_retire(struct ot_workstruct *ws) { (void)ws; }
45
46const char *g_stats_path;
47ssize_t g_stats_path_len;
48uint32_t g_tracker_id;
diff --git a/sync_daemon.pl b/tests/sync_daemon.pl
index 9e4bdb9..9e4bdb9 100644
--- a/sync_daemon.pl
+++ b/tests/sync_daemon.pl
diff --git a/tests/syscount.c b/tests/syscount.c
new file mode 100644
index 0000000..ec45c15
--- /dev/null
+++ b/tests/syscount.c
@@ -0,0 +1,144 @@
1/* Counts the system calls a run makes, by standing in front of libc.
2
3 cc -O2 -shared -fPIC -o syscount.so tests/syscount.c -ldl
4 LD_PRELOAD=./syscount.so ./opentracker -f conf (DYLD_INSERT_LIBRARIES on macOS)
5
6 The tally goes to stderr when the process exits. Reading the source tells
7 you which calls a path should make; this tells you which it does make,
8 which is not always the same thing. */
9
10#define _GNU_SOURCE
11#include <dlfcn.h>
12#include <stdarg.h>
13#include <stdatomic.h>
14#include <stdio.h>
15#include <sys/socket.h>
16#include <sys/types.h>
17#include <unistd.h>
18
19#ifdef __linux__
20#include <sys/epoll.h>
21#endif
22
23#define COUNTER(name) static _Atomic long g_##name
24#define BUMP(name) atomic_fetch_add_explicit(&g_##name, 1, memory_order_relaxed)
25#define REPORT(name) fprintf(stderr, " %-14s %10ld\n", #name, atomic_load(&g_##name))
26
27COUNTER(accept);
28COUNTER(accept4);
29COUNTER(read);
30COUNTER(write);
31COUNTER(close);
32COUNTER(fcntl);
33COUNTER(recvfrom);
34COUNTER(sendto);
35COUNTER(epoll_ctl);
36COUNTER(epoll_wait);
37
38typedef int (*fn_accept)(int, struct sockaddr *, socklen_t *);
39typedef int (*fn_accept4)(int, struct sockaddr *, socklen_t *, int);
40typedef ssize_t (*fn_read)(int, void *, size_t);
41typedef ssize_t (*fn_write)(int, const void *, size_t);
42typedef int (*fn_close)(int);
43typedef int (*fn_fcntl)(int, int, ...);
44typedef ssize_t (*fn_recvfrom)(int, void *, size_t, int, struct sockaddr *, socklen_t *);
45typedef ssize_t (*fn_sendto)(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
46
47static fn_accept real_accept;
48static fn_accept4 real_accept4;
49static fn_read real_read;
50static fn_write real_write;
51static fn_close real_close;
52static fn_fcntl real_fcntl;
53static fn_recvfrom real_recvfrom;
54static fn_sendto real_sendto;
55
56/* Resolving lazily keeps the library out of the way until something is
57 actually called, which matters because dlsym itself allocates */
58#define WRAP(name) \
59 if (!real_##name) \
60 real_##name = (fn_##name)dlsym(RTLD_NEXT, #name); \
61 BUMP(name)
62
63int accept(int s, struct sockaddr *addr, socklen_t *len) {
64 WRAP(accept);
65 return real_accept(s, addr, len);
66}
67
68#ifdef SOCK_NONBLOCK
69int accept4(int s, struct sockaddr *addr, socklen_t *len, int flags) {
70 WRAP(accept4);
71 return real_accept4(s, addr, len, flags);
72}
73#endif
74
75ssize_t read(int fd, void *buf, size_t count) {
76 WRAP(read);
77 return real_read(fd, buf, count);
78}
79
80ssize_t write(int fd, const void *buf, size_t count) {
81 WRAP(write);
82 return real_write(fd, buf, count);
83}
84
85int close(int fd) {
86 WRAP(close);
87 return real_close(fd);
88}
89
90int fcntl(int fd, int cmd, ...) {
91 va_list args;
92 long arg;
93
94 va_start(args, cmd);
95 arg = va_arg(args, long);
96 va_end(args);
97 WRAP(fcntl);
98 return real_fcntl(fd, cmd, arg);
99}
100
101ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) {
102 WRAP(recvfrom);
103 return real_recvfrom(s, buf, len, flags, from, fromlen);
104}
105
106ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) {
107 WRAP(sendto);
108 return real_sendto(s, buf, len, flags, to, tolen);
109}
110
111#ifdef __linux__
112typedef int (*fn_epoll_ctl)(int, int, int, struct epoll_event *);
113typedef int (*fn_epoll_wait)(int, struct epoll_event *, int, int);
114static fn_epoll_ctl real_epoll_ctl;
115static fn_epoll_wait real_epoll_wait;
116
117int epoll_ctl(int ep, int op, int fd, struct epoll_event *ev) {
118 WRAP(epoll_ctl);
119 return real_epoll_ctl(ep, op, fd, ev);
120}
121
122int epoll_wait(int ep, struct epoll_event *events, int max, int timeout) {
123 WRAP(epoll_wait);
124 return real_epoll_wait(ep, events, max, timeout);
125}
126#endif
127
128__attribute__((destructor)) static void report(void) {
129 fprintf(stderr, "\n system calls this run\n");
130 REPORT(accept);
131#ifdef SOCK_NONBLOCK
132 REPORT(accept4);
133#endif
134 REPORT(read);
135 REPORT(write);
136 REPORT(close);
137 REPORT(fcntl);
138 REPORT(recvfrom);
139 REPORT(sendto);
140#ifdef __linux__
141 REPORT(epoll_ctl);
142 REPORT(epoll_wait);
143#endif
144}
diff --git a/tests/t_accesslist.c b/tests/t_accesslist.c
new file mode 100644
index 0000000..14321f4
--- /dev/null
+++ b/tests/t_accesslist.c
@@ -0,0 +1,120 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_accesslist.h"
10#include "test.h"
11
12#define A "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
13#define B "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
14#define C "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
15
16static ot_hash dest[8];
17
18/* The parser is handed a mapped file, so it must never look at a byte beyond
19 the length it was given. These cases place a hex digit immediately after
20 that length: a parser that reads one byte too far sees it, decides the hash
21 runs on, and silently drops the last entry. */
22
23static void case_empty(void) {
24 test_case("an empty buffer yields nothing");
25 CHECK_INT(accesslist_parse_hashes(dest, 8, "", 0), 0);
26}
27
28static void case_single_with_newline(void) {
29 const char buf[] = A "\n";
30
31 test_case("one hash followed by a newline");
32 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 41), 1);
33}
34
35static void case_single_without_newline(void) {
36 const char buf[] = A "A";
37
38 test_case("one hash ending the buffer, with a hex digit just past the end");
39 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 40), 1);
40}
41
42static void case_several_last_without_newline(void) {
43 const char buf[] = A "\n" B "\n" C "C";
44
45 test_case("a final hash without a trailing newline still counts");
46 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 3 * 40 + 2), 3);
47}
48
49static void case_run_on_hash_is_rejected(void) {
50 const char buf[] = A "A\n";
51
52 test_case("forty one hex digits are not a hash");
53 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 42), 0);
54}
55
56static void case_junk_lines_skipped(void) {
57 const char buf[] = "# a comment\n" A "\nnot a hash\n" B "\n";
58
59 test_case("lines that are not hashes are ignored");
60 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, sizeof(buf) - 1), 2);
61}
62
63static void case_trailing_junk_on_line(void) {
64 const char buf[] = A " some comment\n" B "\n";
65
66 test_case("a hash followed by other text on the same line still counts");
67 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, sizeof(buf) - 1), 2);
68}
69
70static void case_capacity_is_respected(void) {
71 const char buf[] = A "\n" B "\n" C "\n";
72
73 test_case("no more than capacity hashes are written");
74 CHECK_INT(accesslist_parse_hashes(dest, 2, buf, sizeof(buf) - 1), 2);
75}
76
77static void case_zero_capacity_never_writes(void) {
78 const char buf[] = A "\n";
79
80 test_case("a zero capacity tolerates a null destination");
81 CHECK_INT(accesslist_parse_hashes(NULL, 0, buf, 41), 0);
82}
83
84static void case_decoded_value(void) {
85 const char buf[] = "000102030405060708090A0B0C0D0E0F10111213\n";
86 const uint8_t want[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
87
88 test_case("the hash is decoded, not merely counted");
89 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 41), 1);
90 CHECK_MEM(dest[0], want, sizeof(want));
91}
92
93static void case_capacity_bound_holds(void) {
94 /* (len + 1) / 41 is what accesslist_readfile allocates. Pack a buffer as
95 densely as the parser allows and check the bound is not exceeded. */
96 char buf[41 * 4];
97 size_t len, capacity, found;
98
99 test_case("the capacity formula bounds what the parser can produce");
100 memcpy(buf, A "\n" B "\n" C "\n" A, 4 * 40 + 3);
101 len = 4 * 40 + 3;
102 capacity = (len + 1) / 41;
103 found = accesslist_parse_hashes(dest, 8, buf, len);
104 CHECK_INT(found, 4);
105 CHECK(found <= capacity);
106}
107
108void test_accesslist(void) {
109 case_empty();
110 case_single_with_newline();
111 case_single_without_newline();
112 case_several_last_without_newline();
113 case_run_on_hash_is_rejected();
114 case_junk_lines_skipped();
115 case_trailing_junk_on_line();
116 case_capacity_is_respected();
117 case_zero_capacity_never_writes();
118 case_decoded_value();
119 case_capacity_bound_holds();
120}
diff --git a/tests/t_batch.c b/tests/t_batch.c
new file mode 100644
index 0000000..5a7ac1e
--- /dev/null
+++ b/tests/t_batch.c
@@ -0,0 +1,346 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <fcntl.h>
6#include <poll.h>
7#include <stdlib.h>
8#include <string.h>
9#include <sys/socket.h>
10#include <unistd.h>
11
12/* Opentracker */
13#include "ot_batch.h"
14#include "test.h"
15
16/* The batch writes to a real socket pair, because what is worth pinning down
17 is what it does when the kernel takes only part of what it was offered. */
18
19static char *dup_of(const char *text) {
20 size_t len = strlen(text);
21 char *copy = malloc(len);
22
23 memcpy(copy, text, len);
24 return copy;
25}
26
27static void drain(int s, char *into, size_t len) {
28 size_t got = 0;
29
30 while (got < len) {
31 ssize_t r = read(s, into + got, len - got);
32
33 if (r <= 0)
34 break;
35 got += (size_t)r;
36 }
37 into[got] = 0;
38}
39
40static void case_queue_accounting(void) {
41 ot_batch batch;
42
43 memset(&batch, 0, sizeof(batch));
44
45 test_case("a zeroed batch is empty and sends nothing");
46 CHECK_INT(batch_pending(&batch), 0);
47 CHECK_INT(batch_send(-1, &batch), BATCH_DONE);
48
49 test_case("anything queued makes it pending");
50 CHECK_INT(batch_add(&batch, dup_of("hello "), 6), 0);
51 CHECK_INT(batch_add_copy(&batch, "world", 5), 0);
52 CHECK_INT(batch_pending(&batch), 1);
53 CHECK_INT(batch.count, 2);
54
55 batch_reset(&batch);
56 test_case("and a reset empties it");
57 CHECK_INT(batch_pending(&batch), 0);
58 CHECK_PTR(batch.entries, NULL);
59}
60
61static void case_send_in_one_go(void) {
62 ot_batch batch;
63 int sv[2];
64 char got[32];
65
66 memset(&batch, 0, sizeof(batch));
67 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
68
69 test_case("several buffers arrive as one stream, in order");
70 CHECK_INT(batch_add(&batch, dup_of("opentracker"), 11), 0);
71 CHECK_INT(batch_add_copy(&batch, " says ", 6), 0);
72 CHECK_INT(batch_add(&batch, dup_of("hello"), 5), 0);
73 CHECK_INT(batch_send(sv[0], &batch), 22);
74 CHECK_INT(batch_pending(&batch), 0);
75
76 drain(sv[1], got, 22);
77 CHECK_STR(got, "opentracker says hello");
78
79 test_case("and an empty batch reports it has nothing left");
80 CHECK_INT(batch_send(sv[0], &batch), BATCH_DONE);
81
82 batch_reset(&batch);
83 close(sv[0]);
84 close(sv[1]);
85}
86
87/* Send everything the batch holds, reading the other end as we go so the
88 socket never stays full, and return what arrived. */
89static size_t pump(int writer, int reader, ot_batch *batch, char *into, size_t room) {
90 size_t got = 0;
91
92 while (batch_pending(batch) || got < room) {
93 ssize_t r;
94
95 if (batch_pending(batch)) {
96 ssize_t res = batch_send(writer, batch);
97
98 if (res == BATCH_FAILED)
99 break;
100 if (res > 0)
101 continue;
102 }
103
104 r = read(reader, into + got, room - got);
105 if (r <= 0)
106 break;
107 got += (size_t)r;
108 }
109 return got;
110}
111
112static void case_partial_write_resumes(void) {
113 const size_t size = 200000;
114 ot_batch batch;
115 int sv[2], sndbuf = 4096;
116 char *sent, *got;
117 size_t i, arrived;
118
119 memset(&batch, 0, sizeof(batch));
120 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
121 setsockopt(sv[0], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
122 fcntl(sv[0], F_SETFL, fcntl(sv[0], F_GETFL, 0) | O_NONBLOCK);
123
124 sent = malloc(size);
125 got = malloc(size);
126 for (i = 0; i < size; ++i)
127 sent[i] = (char)(i % 251);
128
129 test_case("a buffer the kernel takes in pieces arrives whole and in order");
130 CHECK_INT(batch_add(&batch, memcpy(malloc(size), sent, size), size), 0);
131 arrived = pump(sv[0], sv[1], &batch, got, size);
132 CHECK_INT(arrived, size);
133 CHECK_INT(batch_pending(&batch), 0);
134 CHECK_MEM(got, sent, size);
135
136 free(sent);
137 free(got);
138 batch_reset(&batch);
139 close(sv[0]);
140 close(sv[1]);
141}
142
143/* writev refuses more than IOV_MAX entries at once, so a long batch has to be
144 sent across several calls. */
145static void case_more_entries_than_one_writev(void) {
146 const size_t entries = 3000, each = 4;
147 ot_batch batch;
148 int sv[2], sndbuf = 4096;
149 char *sent, *got;
150 size_t i, arrived, refused = 0;
151
152 memset(&batch, 0, sizeof(batch));
153 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
154 setsockopt(sv[0], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
155 fcntl(sv[0], F_SETFL, fcntl(sv[0], F_GETFL, 0) | O_NONBLOCK);
156
157 sent = malloc(entries * each);
158 got = malloc(entries * each);
159
160 test_case("a batch of more entries than writev accepts still arrives whole");
161 for (i = 0; i < entries; ++i) {
162 char piece[4];
163
164 piece[0] = (char)(i), piece[1] = (char)(i >> 8), piece[2] = 'x', piece[3] = 'y';
165 memcpy(sent + i * each, piece, each);
166 if (batch_add(&batch, memcpy(malloc(each), piece, each), each))
167 ++refused;
168 }
169 CHECK_INT(refused, 0);
170 CHECK_INT(batch.count, entries);
171
172 arrived = pump(sv[0], sv[1], &batch, got, entries * each);
173 CHECK_INT(arrived, entries * each);
174 CHECK_MEM(got, sent, entries * each);
175
176 free(sent);
177 free(got);
178 batch_reset(&batch);
179 close(sv[0]);
180 close(sv[1]);
181}
182
183static void case_reset_frees_the_unsent(void) {
184 ot_batch batch;
185 int sv[2];
186
187 memset(&batch, 0, sizeof(batch));
188 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
189
190 test_case("a batch torn down mid flight keeps no bytes outstanding");
191 CHECK_INT(batch_add(&batch, dup_of("first"), 5), 0);
192 CHECK_INT(batch_add(&batch, dup_of("second"), 6), 0);
193 CHECK_INT(batch_send(sv[0], &batch), 11);
194 CHECK_INT(batch_add(&batch, dup_of("never sent"), 10), 0);
195 CHECK_INT(batch_pending(&batch), 1);
196
197 /* Whether the unsent buffer is freed is for the sanitizer to say */
198 batch_reset(&batch);
199 CHECK_INT(batch_pending(&batch), 0);
200 CHECK_INT(batch.count, 0);
201
202 close(sv[0]);
203 close(sv[1]);
204}
205
206static void case_closed_socket_is_fatal(void) {
207 ot_batch batch;
208 int sv[2];
209
210 memset(&batch, 0, sizeof(batch));
211 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
212 close(sv[1]);
213
214 test_case("writing to a socket whose peer is gone reports a dead connection");
215 CHECK_INT(batch_add(&batch, dup_of("nobody is listening"), 19), 0);
216 CHECK_INT(batch_send(sv[0], &batch), BATCH_FAILED);
217
218 batch_reset(&batch);
219 close(sv[0]);
220}
221
222static void case_vector_is_taken_whole(void) {
223 ot_batch batch;
224 struct iovec *vector = malloc(3 * sizeof(struct iovec));
225 int sv[2];
226 char got[32];
227
228 memset(&batch, 0, sizeof(batch));
229 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
230
231 test_case("a whole vector is queued in one go, in order");
232 vector[0].iov_base = dup_of("one "), vector[0].iov_len = 4;
233 vector[1].iov_base = dup_of("two "), vector[1].iov_len = 4;
234 vector[2].iov_base = dup_of("three"), vector[2].iov_len = 5;
235 CHECK_INT(batch_add_vector(&batch, vector, 3), 0);
236 free(vector);
237 CHECK_INT(batch.count, 3);
238 CHECK_INT(batch_send(sv[0], &batch), 13);
239
240 drain(sv[1], got, 13);
241 CHECK_STR(got, "one two three");
242
243 batch_reset(&batch);
244 close(sv[0]);
245 close(sv[1]);
246}
247
248/* The entry array starts small and doubles, so crossing that boundary one
249 buffer at a time is worth its own case. */
250static void case_growing_one_entry_at_a_time(void) {
251 const size_t entries = 100;
252 ot_batch batch;
253 int sv[2];
254 char sent[400], got[401];
255 size_t i, refused = 0;
256
257 memset(&batch, 0, sizeof(batch));
258 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
259
260 test_case("a batch grown one buffer at a time keeps them all, in order");
261 for (i = 0; i < entries; ++i) {
262 char piece[4];
263
264 piece[0] = (char)('a' + i % 26), piece[1] = (char)('0' + i % 10);
265 piece[2] = (char)('A' + i % 26), piece[3] = '.';
266 memcpy(sent + i * 4, piece, 4);
267 if (batch_add(&batch, memcpy(malloc(4), piece, 4), 4))
268 ++refused;
269 }
270 CHECK_INT(refused, 0);
271 CHECK_INT(batch.count, entries);
272 CHECK_INT(batch_send(sv[0], &batch), (ssize_t)(entries * 4));
273
274 drain(sv[1], got, entries * 4);
275 CHECK_MEM(got, sent, entries * 4);
276
277 batch_reset(&batch);
278 close(sv[0]);
279 close(sv[1]);
280}
281
282/* Appending while earlier entries are still on their way is what a chunked
283 transfer does. Rather than depend on when a kernel decides to block, this
284 takes entries off the front the way a completed send would and checks that
285 the array reuses the space instead of growing. */
286static void case_append_while_sending(void) {
287 const size_t per_round = 12, each = 8;
288 ot_batch batch;
289 int sv[2];
290 char expected[16], got[17];
291 size_t i, round, refused = 0, space_after_first = 0;
292
293 memset(&batch, 0, sizeof(batch));
294 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
295
296 test_case("an array whose front has gone out is reused, not grown");
297 for (round = 0; round < 8; ++round) {
298 for (i = 0; i < per_round; ++i) {
299 /* Distinct per entry, so a move from the wrong index shows up */
300 char *piece = malloc(each);
301
302 memset(piece, (int)('a' + (round * per_round + i) % 26), each);
303 piece[0] = (char)('0' + i);
304 piece[1] = (char)('0' + round);
305 if (batch_add(&batch, piece, each))
306 ++refused;
307 }
308
309 /* All but the last entry have left and been freed */
310 while (batch.count - batch.first > 1)
311 free(batch.entries[batch.first++].iov_base);
312
313 if (!round)
314 space_after_first = batch.space;
315 }
316 CHECK_INT(refused, 0);
317 CHECK_INT(batch.space, space_after_first);
318
319 test_case("and what is still queued survives the move, in order");
320 CHECK_INT(batch.count - batch.first, 1);
321 CHECK_INT(batch_add(&batch, memset(malloc(each), 'Z', each), each), 0);
322 CHECK_INT(batch_send(sv[0], &batch), (ssize_t)(2 * each));
323
324 memset(expected, (int)('a' + (7 * per_round + per_round - 1) % 26), each);
325 expected[0] = (char)('0' + per_round - 1);
326 expected[1] = '7';
327 memset(expected + each, 'Z', each);
328 drain(sv[1], got, 2 * each);
329 CHECK_MEM(got, expected, 2 * each);
330
331 batch_reset(&batch);
332 close(sv[0]);
333 close(sv[1]);
334}
335
336void test_batch(void) {
337 case_queue_accounting();
338 case_send_in_one_go();
339 case_vector_is_taken_whole();
340 case_growing_one_entry_at_a_time();
341 case_append_while_sending();
342 case_partial_write_resumes();
343 case_more_entries_than_one_writev();
344 case_reset_frees_the_unsent();
345 case_closed_socket_is_fatal();
346}
diff --git a/tests/t_buf.c b/tests/t_buf.c
new file mode 100644
index 0000000..39c44f1
--- /dev/null
+++ b/tests/t_buf.c
@@ -0,0 +1,203 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_buf.h"
10#include "test.h"
11
12static void case_starts_empty(void) {
13 ot_buf buf = {NULL, 0};
14
15 test_case("a fresh buffer holds nothing and has no data pointer");
16 CHECK_PTR(buf.data, NULL);
17 CHECK_INT(buf.size, 0);
18}
19
20static void case_cat_appends(void) {
21 ot_buf buf = {NULL, 0};
22
23 test_case("appends concatenate in order and report success");
24 CHECK_INT(buf_cat(&buf, "GET /ann", 8), 0);
25 CHECK(buf.data != NULL);
26 CHECK_INT(buf.size, 8);
27 CHECK_INT(buf_cat(&buf, "ounce", 5), 0);
28 CHECK_INT(buf.size, 13);
29 CHECK_MEM(buf.data, "GET /announce", 13);
30 buf_reset(&buf);
31}
32
33static void case_cat_of_nothing_allocates_nothing(void) {
34 ot_buf buf = {NULL, 0};
35
36 /* handle_read tells an untouched buffer from a partial request by the data
37 pointer, so a zero length append must not quietly allocate one */
38 test_case("appending zero bytes leaves the buffer untouched");
39 CHECK_INT(buf_cat(&buf, "ignored", 0), 0);
40 CHECK_PTR(buf.data, NULL);
41 CHECK_INT(buf.size, 0);
42 buf_reset(&buf);
43}
44
45static void case_grows_across_many_appends(void) {
46 ot_buf buf = {NULL, 0};
47 char chunk[100];
48 size_t i;
49
50 test_case("content survives growing one packet at a time");
51 memset(chunk, 'x', sizeof(chunk));
52 for (i = 0; i < 100; ++i)
53 if (buf_cat(&buf, chunk, sizeof(chunk))) {
54 test_failf(__FILE__, __LINE__, "append %zu was refused", i);
55 buf_reset(&buf);
56 return;
57 }
58 ++test_checks;
59 CHECK_INT(buf.size, 10000);
60 for (i = 0; i < 10000; ++i)
61 if (buf.data[i] != 'x') {
62 test_failf(__FILE__, __LINE__, "byte %zu was not preserved across growth", i);
63 buf_reset(&buf);
64 return;
65 }
66 ++test_checks;
67 buf_reset(&buf);
68}
69
70static void case_grows_one_byte_at_a_time(void) {
71 ot_buf buf = {NULL, 0};
72 size_t i;
73
74 /* The shape a trickling client produces. Nothing here is optimised for it,
75 so the point is only that it stays correct. */
76 test_case("a byte at a time accumulates correctly");
77 for (i = 0; i < 2048; ++i) {
78 char c = (char)('a' + (i % 26));
79 if (buf_cat(&buf, &c, 1)) {
80 test_failf(__FILE__, __LINE__, "append %zu was refused", i);
81 buf_reset(&buf);
82 return;
83 }
84 }
85 ++test_checks;
86 CHECK_INT(buf.size, 2048);
87 for (i = 0; i < 2048; ++i)
88 if (buf.data[i] != (char)('a' + (i % 26))) {
89 test_failf(__FILE__, __LINE__, "byte %zu differs", i);
90 buf_reset(&buf);
91 return;
92 }
93 ++test_checks;
94 buf_reset(&buf);
95}
96
97static void case_truncate_shrinks_only(void) {
98 ot_buf buf = {NULL, 0};
99
100 test_case("truncate drops the tail but never grows");
101 buf_cat(&buf, "0123456789", 10);
102 buf_truncate(&buf, 4);
103 CHECK_INT(buf.size, 4);
104 CHECK_MEM(buf.data, "0123", 4);
105
106 buf_truncate(&buf, 9);
107 CHECK_INT(buf.size, 4);
108 buf_truncate(&buf, 4);
109 CHECK_INT(buf.size, 4);
110
111 buf_truncate(&buf, 0);
112 CHECK_INT(buf.size, 0);
113 buf_reset(&buf);
114}
115
116static void case_append_after_truncate(void) {
117 ot_buf buf = {NULL, 0};
118
119 test_case("appending after a truncate overwrites the dropped tail");
120 buf_cat(&buf, "keepdrop", 8);
121 buf_truncate(&buf, 4);
122 CHECK_INT(buf_cat(&buf, "MORE", 4), 0);
123 CHECK_INT(buf.size, 8);
124 CHECK_MEM(buf.data, "keepMORE", 8);
125 buf_reset(&buf);
126}
127
128static void case_reset_clears_everything(void) {
129 ot_buf buf = {NULL, 0};
130
131 test_case("reset releases the buffer and restores the initial state");
132 buf_cat(&buf, "something", 9);
133 buf_reset(&buf);
134 CHECK_PTR(buf.data, NULL);
135 CHECK_INT(buf.size, 0);
136}
137
138static void case_reset_of_empty_is_safe(void) {
139 ot_buf buf = {NULL, 0};
140
141 test_case("resetting a buffer that was never used is harmless");
142 buf_reset(&buf);
143 buf_reset(&buf);
144 CHECK_PTR(buf.data, NULL);
145 CHECK_INT(buf.size, 0);
146}
147
148static void case_refused_append_is_harmless(void) {
149 ot_buf buf = {NULL, 0};
150
151 /* A length that would wrap the size is rejected before src is read and
152 before anything is allocated, so a short string is safe to pass here.
153 A refused append must not destroy the partial request already collected:
154 the caller answers and closes rather than losing both. */
155 test_case("a length that would wrap the size is refused");
156 CHECK_INT(buf_cat(&buf, "already here", 12), 0);
157 CHECK_INT(buf_cat(&buf, "x", (size_t)-1), -1);
158
159 test_case("and earlier content survives it");
160 CHECK_INT(buf.size, 12);
161 CHECK_MEM(buf.data, "already here", 12);
162
163 test_case("and the buffer still works afterwards");
164 CHECK_INT(buf_cat(&buf, "!", 1), 0);
165 CHECK_INT(buf.size, 13);
166 CHECK_MEM(buf.data, "already here!", 13);
167 buf_reset(&buf);
168}
169
170static void case_accumulates_a_split_request(void) {
171 /* What handle_read actually does: collect a request that arrived in
172 pieces, then hand over the whole of it */
173 ot_buf buf = {NULL, 0};
174 const char *pieces[] = {"GET /announce?info_hash=", "0123456789abcdefghij", " HTTP/1.0\r\n\r\n"};
175 size_t i;
176
177 test_case("a request split over several reads is reassembled");
178 for (i = 0; i < 3; ++i)
179 if (buf_cat(&buf, pieces[i], strlen(pieces[i]))) {
180 test_failf(__FILE__, __LINE__, "piece %zu was refused", i);
181 buf_reset(&buf);
182 return;
183 }
184 ++test_checks;
185
186 CHECK_INT(buf.size, 24 + 20 + 13);
187 CHECK_MEM(buf.data, "GET /announce?info_hash=0123456789abcdefghij HTTP/1.0\r\n\r\n", 57);
188 buf_reset(&buf);
189}
190
191void test_buf(void) {
192 case_starts_empty();
193 case_cat_appends();
194 case_cat_of_nothing_allocates_nothing();
195 case_grows_across_many_appends();
196 case_grows_one_byte_at_a_time();
197 case_truncate_shrinks_only();
198 case_append_after_truncate();
199 case_reset_clears_everything();
200 case_reset_of_empty_is_safe();
201 case_refused_append_is_harmless();
202 case_accumulates_a_split_request();
203}
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_event.c b/tests/t_event.c
new file mode 100644
index 0000000..5c45089
--- /dev/null
+++ b/tests/t_event.c
@@ -0,0 +1,289 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <fcntl.h>
6#include <string.h>
7#include <sys/socket.h>
8#include <sys/time.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "ot_event.h"
13#include "test.h"
14
15/* Against real socket pairs: only the kernel can say whether a descriptor is
16 ready, so there is nothing useful to mock here. */
17
18#define EVENTS 16
19
20static int sv[2];
21static ot_event ready[EVENTS];
22
23static void pair_open(void) {
24 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
25 sv[0] = sv[1] = -1;
26}
27
28static void pair_close(void) {
29 if (sv[0] != -1)
30 close(sv[0]);
31 if (sv[1] != -1)
32 close(sv[1]);
33 sv[0] = sv[1] = -1;
34}
35
36static int wait_for(int fd, int what, int timeout_ms, uint32_t *generation) {
37 int count = event_wait(ready, EVENTS, timeout_ms), i;
38
39 for (i = 0; i < count; ++i)
40 if (ready[i].fd == fd && (ready[i].what & what)) {
41 if (generation)
42 *generation = ready[i].generation;
43 return 1;
44 }
45 return 0;
46}
47
48static unsigned long elapsed_ms(struct timeval *since) {
49 struct timeval now;
50
51 gettimeofday(&now, NULL);
52 return (unsigned long)((now.tv_sec - since->tv_sec) * 1000 + (now.tv_usec - since->tv_usec) / 1000);
53}
54
55static void case_readable(void) {
56 uint32_t generation = 0;
57
58 test_case("a descriptor with something to read is reported, with its generation");
59 pair_open();
60 CHECK(sv[0] != -1);
61 CHECK_INT(event_add(sv[0], EVENT_IN, 4711), 0);
62 CHECK_INT(write(sv[1], "x", 1), 1);
63 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
64 CHECK_INT(generation, 4711);
65
66 test_case("and keeps being reported until it is read");
67 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
68 {
69 char scratch[4];
70 CHECK_INT(read(sv[0], scratch, sizeof(scratch)), 1);
71 }
72 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
73
74 CHECK_INT(event_del(sv[0]), 0);
75 pair_close();
76}
77
78static void case_writable(void) {
79 test_case("a descriptor with room to write is reported");
80 pair_open();
81 CHECK(sv[0] != -1);
82 CHECK_INT(event_add(sv[0], EVENT_OUT, 1), 0);
83 CHECK_INT(wait_for(sv[0], EVENT_OUT, 1000, NULL), 1);
84
85 test_case("and is not, once we say we no longer care");
86 CHECK_INT(event_modify(sv[0], EVENT_IN, 1), 0);
87 CHECK_INT(wait_for(sv[0], EVENT_OUT, 50, NULL), 0);
88
89 CHECK_INT(event_del(sv[0]), 0);
90 pair_close();
91}
92
93static void case_interest_is_separate(void) {
94 test_case("asking only about writing does not report reading");
95 pair_open();
96 CHECK(sv[0] != -1);
97 CHECK_INT(event_add(sv[0], EVENT_OUT, 1), 0);
98 CHECK_INT(write(sv[1], "x", 1), 1);
99 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
100
101 test_case("until we ask about it");
102 CHECK_INT(event_modify(sv[0], EVENT_IN | EVENT_OUT, 1), 0);
103 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
104
105 CHECK_INT(event_del(sv[0]), 0);
106 pair_close();
107}
108
109static void case_removed_is_silent(void) {
110 test_case("a removed descriptor is not reported again");
111 pair_open();
112 CHECK(sv[0] != -1);
113 CHECK_INT(event_add(sv[0], EVENT_IN, 1), 0);
114 CHECK_INT(write(sv[1], "x", 1), 1);
115 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
116 CHECK_INT(event_del(sv[0]), 0);
117 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
118 pair_close();
119}
120
121static void case_generations_do_not_mix(void) {
122 int other[2];
123 uint32_t generation = 0;
124
125 test_case("two descriptors carry their own generations");
126 pair_open();
127 CHECK(sv[0] != -1);
128 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, other), 0);
129 CHECK_INT(event_add(sv[0], EVENT_IN, 100), 0);
130 CHECK_INT(event_add(other[0], EVENT_IN, 200), 0);
131 CHECK_INT(write(sv[1], "x", 1), 1);
132 CHECK_INT(write(other[1], "y", 1), 1);
133
134 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
135 CHECK_INT(generation, 100);
136 CHECK_INT(wait_for(other[0], EVENT_IN, 1000, &generation), 1);
137 CHECK_INT(generation, 200);
138
139 test_case("and re-registering one changes only its own");
140 CHECK_INT(event_modify(sv[0], EVENT_IN, 101), 0);
141 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
142 CHECK_INT(generation, 101);
143 CHECK_INT(wait_for(other[0], EVENT_IN, 1000, &generation), 1);
144 CHECK_INT(generation, 200);
145
146 event_del(sv[0]);
147 event_del(other[0]);
148 close(other[0]);
149 close(other[1]);
150 pair_close();
151}
152
153/* Removing one of several has to leave the rest addressable: a backend that
154 keeps its descriptors packed moves the last one into the gap, and has to
155 remember where it went. */
156static void case_delete_from_the_middle(void) {
157 int pair[3][2];
158 uint32_t generation = 0;
159 int i;
160
161 test_case("deleting one of three leaves the others reported correctly");
162 for (i = 0; i < 3; ++i) {
163 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, pair[i]), 0);
164 CHECK_INT(event_add(pair[i][0], EVENT_IN, (uint32_t)(10 + i)), 0);
165 }
166 CHECK_INT(event_del(pair[1][0]), 0);
167
168 for (i = 0; i < 3; i += 2) {
169 CHECK_INT(write(pair[i][1], "x", 1), 1);
170 CHECK_INT(wait_for(pair[i][0], EVENT_IN, 1000, &generation), 1);
171 CHECK_INT(generation, 10 + i);
172 }
173
174 test_case("and the survivors can still be changed and removed");
175 CHECK_INT(event_modify(pair[2][0], EVENT_IN, 99), 0);
176 CHECK_INT(wait_for(pair[2][0], EVENT_IN, 1000, &generation), 1);
177 CHECK_INT(generation, 99);
178 CHECK_INT(event_del(pair[0][0]), 0);
179 CHECK_INT(event_del(pair[2][0]), 0);
180 CHECK_INT(wait_for(pair[2][0], EVENT_IN, 50, NULL), 0);
181
182 for (i = 0; i < 3; ++i)
183 close(pair[i][0]), close(pair[i][1]);
184}
185
186static void case_timeout(void) {
187 struct timeval started;
188
189 test_case("waiting on nothing comes back empty when the time is up");
190 gettimeofday(&started, NULL);
191 CHECK_INT(event_wait(ready, EVENTS, 200), 0);
192 {
193 unsigned long took = elapsed_ms(&started);
194 /* Scheduling makes the upper bound generous. The point is that it waited
195 rather than returning at once, and that it came back at all */
196 CHECK(took >= 150);
197 CHECK(took < 5000);
198 }
199}
200
201static void case_unknown_descriptor(void) {
202 test_case("changing or removing one that was never added is refused");
203 CHECK_INT(event_modify(4096, EVENT_IN, 1), -1);
204 CHECK_INT(event_del(4096), -1);
205}
206
207/* event_close exists so that the mechanisms which drop a closed descriptor
208 by themselves are not asked to do it twice. The one that keeps its own
209 list has to be told, and forgetting would leave the entry there to be
210 reported for ever, so what is checked here is the silence afterwards. */
211static void case_close_takes_it_out(void) {
212 int other[2], closed, count, i, strays = 0;
213
214 test_case("a closed descriptor is gone from the set and really closed");
215 pair_open();
216 CHECK(sv[0] != -1);
217 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, other), 0);
218 CHECK_INT(event_add(sv[0], EVENT_IN, 1), 0);
219 CHECK_INT(event_add(other[0], EVENT_IN, 2), 0);
220
221 closed = sv[0];
222 CHECK_INT(event_close(closed), 0);
223 sv[0] = -1;
224 CHECK_INT(fcntl(closed, F_GETFD), -1);
225
226 /* The survivor is made ready so the wait has something to come back with,
227 and anything left over from the closed one shows up beside it */
228 CHECK_INT((int)write(other[1], "x", 1), 1);
229 count = event_wait(ready, EVENTS, 200);
230 CHECK(count >= 1);
231 for (i = 0; i < count; ++i)
232 if (ready[i].fd != other[0])
233 ++strays;
234 CHECK_INT(strays, 0);
235
236 event_del(other[0]);
237 close(other[0]);
238 close(other[1]);
239 pair_close();
240}
241
242/* A descriptor can be taken on before anybody waits for anything on it: the
243 full scrape parks a connection while a worker thread builds the reply. The
244 mechanisms disagree about what registering nothing means, so what is
245 checked is that asking for a filter afterwards still works. */
246static void case_add_nothing_then_ask(void) {
247 test_case("a descriptor added with no interest can be given some later");
248 pair_open();
249 CHECK(sv[0] != -1);
250 CHECK_INT(event_add(sv[0], 0, 7), 0);
251 CHECK_INT((int)write(sv[1], "x", 1), 1);
252 CHECK_INT(wait_for(sv[0], EVENT_IN, 200, NULL), 0);
253
254 CHECK_INT(event_modify(sv[0], EVENT_IN, 7), 0);
255 {
256 uint32_t generation = 0;
257 CHECK_INT(wait_for(sv[0], EVENT_IN, 500, &generation), 1);
258 CHECK_INT((int)generation, 7);
259 }
260 event_del(sv[0]);
261 pair_close();
262}
263
264/* Whether a worker thread may register a descriptor while this one waits
265 depends on who keeps the set. Tying the answer to the mechanism's name
266 here means a backend added later cannot quietly forget to say. */
267static void case_sharing_matches_the_mechanism(void) {
268 test_case("only a set the kernel keeps may be changed from another thread");
269 CHECK_INT(event_can_share(), strcmp(event_mechanism(), "poll") ? 1 : 0);
270}
271
272void test_event(void) {
273 CHECK_INT(event_init(), 0);
274 CHECK(event_mechanism() != NULL);
275 case_sharing_matches_the_mechanism();
276
277 case_readable();
278 case_writable();
279 case_interest_is_separate();
280 case_removed_is_silent();
281 case_generations_do_not_mix();
282 case_delete_from_the_middle();
283 case_timeout();
284 case_unknown_descriptor();
285 case_close_takes_it_out();
286 case_add_nothing_then_ask();
287
288 event_deinit();
289}
diff --git a/tests/t_fdstate.c b/tests/t_fdstate.c
new file mode 100644
index 0000000..c806dbe
--- /dev/null
+++ b/tests/t_fdstate.c
@@ -0,0 +1,230 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <stdint.h>
8#include <stdlib.h>
9#include <string.h>
10
11/* Opentracker */
12#include "ot_fdstate.h"
13#include "test.h"
14
15/* ------------------------------------------------------- one thread first */
16
17static void case_open_claim_release(void) {
18 char cookie[4];
19 uint32_t generation;
20
21 test_case("a descriptor taken into the table can be claimed and gives back its cookie");
22 generation = fdstate_open(7, cookie, 0);
23 CHECK_INT(fdstate_claim(7, generation), 1);
24 CHECK_PTR(fdstate_cookie(7), cookie);
25 fdstate_release(7);
26
27 test_case("and can be claimed again once released");
28 CHECK_INT(fdstate_claim(7, generation), 1);
29 fdstate_release(7);
30 fdstate_close(7);
31}
32
33static void case_one_holder_at_a_time(void) {
34 uint32_t generation = fdstate_open(8, NULL, 0);
35
36 test_case("a descriptor somebody holds cannot be claimed again");
37 CHECK_INT(fdstate_claim(8, generation), 1);
38 CHECK_INT(fdstate_claim(8, generation), 0);
39 fdstate_release(8);
40 CHECK_INT(fdstate_claim(8, generation), 1);
41 fdstate_release(8);
42 fdstate_close(8);
43}
44
45static void case_stale_generation_is_refused(void) {
46 char first[4], second[4];
47 uint32_t old, new;
48
49 test_case("a caller quoting the generation of a closed descriptor is turned away");
50 old = fdstate_open(9, first, 0);
51 fdstate_close(9);
52 new = fdstate_open(9, second, 0);
53 CHECK(old != new);
54 CHECK_INT(fdstate_claim(9, old), 0);
55
56 test_case("while the one quoting the new generation gets the new cookie");
57 CHECK_INT(fdstate_claim(9, new), 1);
58 CHECK_PTR(fdstate_cookie(9), second);
59 fdstate_release(9);
60 fdstate_close(9);
61}
62
63static void case_expiry(void) {
64 uint32_t generation = fdstate_open(10, NULL, 100);
65
66 test_case("a descriptor past its expiry is collected");
67 CHECK_INT(fdstate_claim_expired(10, 99), 0);
68 CHECK_INT(fdstate_claim_expired(10, 100), 1);
69 fdstate_close(10);
70
71 test_case("one that never expires is never collected");
72 generation = fdstate_open(10, NULL, 0);
73 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 0);
74
75 test_case("and one somebody is working on is left alone");
76 fdstate_set_expiry(10, 1);
77 CHECK_INT(fdstate_claim(10, generation), 1);
78 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 0);
79 fdstate_release(10);
80 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 1);
81 fdstate_close(10);
82}
83
84static void case_out_of_range(void) {
85 test_case("a descriptor outside the table is refused rather than trusted");
86 CHECK_INT(fdstate_claim(-1, 0), 0);
87 CHECK_INT(fdstate_claim((int)fdstate_slots(), 0), 0);
88 CHECK_INT(fdstate_claim_expired(-1, 0), 0);
89 CHECK_PTR(fdstate_cookie(-1), NULL);
90}
91
92/* --------------------------------------------------------- then in anger */
93
94/* The race this is about only exists while a descriptor is being recycled,
95 so recycling is driven by work done rather than by a clock: every slot is
96 given up after RECYCLE_AFTER claims, whatever the machine's speed. */
97
98#define STRESS_SLOTS 64
99#define RECYCLE_AFTER 32
100#define STRESS_CLAIMS 200000
101#define STRESS_GIVEUP (STRESS_CLAIMS * 100)
102/* What the run has to reach for its result to mean anything */
103#define STRESS_CYCLES (STRESS_CLAIMS / (RECYCLE_AFTER * 4))
104
105static _Atomic long stress_claims, stress_recycles, stress_violations, stress_attempts;
106static _Atomic int stress_lives[STRESS_SLOTS];
107static _Atomic int stress_live[STRESS_SLOTS];
108
109/* Generation and cookie are published in one word so a worker can never read
110 a cookie that belongs to a different generation than the one it claimed
111 with. Each connection gets a cookie nobody else ever gets. */
112static _Atomic uint64_t stress_conn[STRESS_SLOTS];
113static _Atomic uint64_t stress_next_cookie;
114
115#define STRESS_CONN(cookie, gen) (((uint64_t)(cookie) << 32) | (uint32_t)(gen))
116#define STRESS_CONN_COOKIE(w) ((void *)(uintptr_t)((w) >> 32))
117#define STRESS_CONN_GEN(w) ((uint32_t)(w))
118
119/* The workers reach their claim target on their own, but the recycles that
120 make the run worth anything are the keeper's, and on a loaded machine the
121 keeper is the thread that loses. So the run goes on until both targets are
122 met rather than until the faster of the two is. */
123static int stress_running(void) {
124 if (atomic_load(&stress_attempts) >= STRESS_GIVEUP)
125 return 0;
126 return atomic_load(&stress_claims) < STRESS_CLAIMS || atomic_load(&stress_recycles) <= STRESS_CYCLES;
127}
128
129static void *stress_worker(void *arg) {
130 unsigned seed = (unsigned)(uintptr_t)arg;
131
132 while (stress_running()) {
133 int fd = (int)(rand_r(&seed) % STRESS_SLOTS);
134 uint64_t conn = atomic_load(&stress_conn[fd]);
135
136 atomic_fetch_add(&stress_attempts, 1);
137 if (!fdstate_claim(fd, STRESS_CONN_GEN(conn)))
138 continue;
139
140 if (fdstate_cookie(fd) != STRESS_CONN_COOKIE(conn))
141 atomic_fetch_add(&stress_violations, 1);
142 if (atomic_fetch_sub(&stress_lives[fd], 1) <= 1)
143 fdstate_set_expiry(fd, 1); /* retired by its holder, as a handler would */
144 if (fdstate_cookie(fd) != STRESS_CONN_COOKIE(conn))
145 atomic_fetch_add(&stress_violations, 1);
146
147 fdstate_release(fd);
148 atomic_fetch_add(&stress_claims, 1);
149 }
150 return NULL;
151}
152
153static void *stress_keeper(void *arg) {
154 (void)arg;
155 while (stress_running()) {
156 int fd;
157
158 for (fd = 0; fd < STRESS_SLOTS; ++fd) {
159 if (atomic_load(&stress_live[fd])) {
160 if (!fdstate_claim_expired(fd, 1))
161 continue; /* a worker has it, come back */
162 fdstate_close(fd);
163 atomic_store(&stress_live[fd], 0);
164 atomic_fetch_add(&stress_recycles, 1);
165 }
166 {
167 void *cookie = (void *)(uintptr_t)(atomic_fetch_add(&stress_next_cookie, 1) + 1);
168 uint32_t gen = fdstate_open(fd, cookie, 0);
169
170 atomic_store(&stress_lives[fd], RECYCLE_AFTER);
171 atomic_store(&stress_conn[fd], STRESS_CONN((uintptr_t)cookie, gen));
172 atomic_store(&stress_live[fd], 1);
173 }
174 }
175 }
176 return NULL;
177}
178
179static void case_recycling_under_load(void) {
180 pthread_t worker[4], keeper;
181 size_t i;
182
183 test_case("no worker is ever handed a connection from another generation");
184 atomic_store(&stress_claims, 0);
185 atomic_store(&stress_recycles, 0);
186 atomic_store(&stress_violations, 0);
187 atomic_store(&stress_attempts, 0);
188 atomic_store(&stress_next_cookie, 0);
189 /* Every slot is opened and published before any worker runs: a worker only
190 ever learns of a descriptor from whoever registered it, and never
191 invents a generation of its own. */
192 for (i = 0; i < STRESS_SLOTS; ++i) {
193 void *cookie = (void *)(uintptr_t)(atomic_fetch_add(&stress_next_cookie, 1) + 1);
194 uint32_t gen = fdstate_open((int)i, cookie, 0);
195
196 atomic_store(&stress_lives[i], RECYCLE_AFTER);
197 atomic_store(&stress_conn[i], STRESS_CONN((uintptr_t)cookie, gen));
198 atomic_store(&stress_live[i], 1);
199 }
200
201 pthread_create(&keeper, NULL, stress_keeper, NULL);
202 for (i = 0; i < sizeof(worker) / sizeof(worker[0]); ++i)
203 pthread_create(&worker[i], NULL, stress_worker, (void *)(uintptr_t)(i + 1));
204 for (i = 0; i < sizeof(worker) / sizeof(worker[0]); ++i)
205 pthread_join(worker[i], NULL);
206 pthread_join(keeper, NULL);
207
208 CHECK_INT(atomic_load(&stress_violations), 0);
209
210 test_case("and the run actually recycled descriptors, or it proved nothing");
211 CHECK(atomic_load(&stress_claims) >= STRESS_CLAIMS);
212 CHECK(atomic_load(&stress_recycles) > STRESS_CYCLES);
213
214 for (i = 0; i < STRESS_SLOTS; ++i)
215 fdstate_close((int)i);
216}
217
218void test_fdstate(void) {
219 CHECK_INT(fdstate_init(), 0);
220 CHECK(fdstate_slots() > STRESS_SLOTS);
221
222 case_open_claim_release();
223 case_one_holder_at_a_time();
224 case_stale_generation_is_refused();
225 case_expiry();
226 case_out_of_range();
227 case_recycling_under_load();
228
229 fdstate_deinit();
230}
diff --git a/tests/t_fmt.c b/tests/t_fmt.c
new file mode 100644
index 0000000..f94102d
--- /dev/null
+++ b/tests/t_fmt.c
@@ -0,0 +1,106 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <string.h>
6
7/* Opentracker */
8#include "ot_fmt.h"
9#include "test.h"
10
11static void case_appends_in_sequence(void) {
12 char buffer[64];
13 char *r = buffer, *re = buffer + sizeof(buffer);
14
15 test_case("appends follow each other and advance the cursor");
16 fmt_append(&r, re, "d8:completei%zde", (size_t)7);
17 fmt_append(&r, re, "ee");
18 *r = 0;
19 CHECK_STR(buffer, "d8:completei7eee");
20 CHECK_INT(r - buffer, 16);
21}
22
23static void case_truncation_stops_at_the_end(void) {
24 char buffer[16];
25 char *r = buffer, *re = buffer + 8; /* pretend the buffer ends early */
26
27 memset(buffer, '#', sizeof(buffer));
28 test_case("a value too long for the room left stops at the end");
29 fmt_append(&r, re, "%s", "0123456789");
30 CHECK_PTR(r, re);
31
32 test_case("and writes nothing past it");
33 CHECK_INT(buffer[8], '#');
34 CHECK_INT(buffer[15], '#');
35}
36
37static void case_a_full_buffer_takes_nothing_more(void) {
38 char buffer[16];
39 char *r = buffer + 8, *re = buffer + 8;
40
41 memset(buffer, '#', sizeof(buffer));
42 test_case("appending to a cursor already at the end changes nothing");
43 fmt_append(&r, re, "more");
44 CHECK_PTR(r, re);
45 CHECK_INT(buffer[8], '#');
46}
47
48static void case_an_append_that_just_fits(void) {
49 char buffer[8];
50 char *r = buffer, *re = buffer + 3;
51
52 memset(buffer, '#', sizeof(buffer));
53 test_case("three characters into three bytes of room still truncate");
54 fmt_append(&r, re, "abc");
55 CHECK_PTR(r, re);
56 CHECK_INT(buffer[0], 'a');
57 CHECK_INT(buffer[1], 'b');
58
59 test_case("because snprintf spends the last byte on its terminator");
60 CHECK_INT(buffer[2], 0);
61 CHECK_INT(buffer[3], '#');
62}
63
64static void case_bytes_are_all_or_nothing(void) {
65 char buffer[16];
66 char *r = buffer, *re = buffer + 8;
67
68 memset(buffer, '#', sizeof(buffer));
69 test_case("a run of bytes is written when it fits");
70 fmt_bytes(&r, re, "\0\1\2\3", 4);
71 CHECK_PTR(r, buffer + 4);
72 CHECK_MEM(buffer, "\0\1\2\3", 4);
73
74 test_case("a run that would not fit is refused whole");
75 fmt_bytes(&r, re, "abcde", 5);
76 CHECK_PTR(r, re);
77 CHECK_INT(buffer[4], '#');
78
79 test_case("a run of exactly the room left is written");
80 r = buffer + 4;
81 fmt_bytes(&r, re, "wxyz", 4);
82 CHECK_PTR(r, re);
83 CHECK_MEM(buffer + 4, "wxyz", 4);
84 CHECK_INT(buffer[8], '#');
85}
86
87static void case_bytes_do_not_terminate(void) {
88 char buffer[8];
89 char *r = buffer, *re = buffer + 4;
90
91 memset(buffer, '#', sizeof(buffer));
92 test_case("unlike an append, a run of bytes may fill the room exactly");
93 fmt_bytes(&r, re, "abcd", 4);
94 CHECK_PTR(r, re);
95 CHECK_MEM(buffer, "abcd", 4);
96 CHECK_INT(buffer[4], '#');
97}
98
99void test_fmt(void) {
100 case_appends_in_sequence();
101 case_truncation_stops_at_the_end();
102 case_a_full_buffer_takes_nothing_more();
103 case_an_append_that_just_fits();
104 case_bytes_are_all_or_nothing();
105 case_bytes_do_not_terminate();
106}
diff --git a/tests/t_hex.c b/tests/t_hex.c
new file mode 100644
index 0000000..84aeba2
--- /dev/null
+++ b/tests/t_hex.c
@@ -0,0 +1,126 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_hex.h"
10#include "test.h"
11
12static const uint8_t sample[20] = {0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0};
13
14static void case_encode(void) {
15 char dest[64];
16
17 test_case("a hash encodes to forty upper case digits and a terminator");
18 memset(dest, 0x7f, sizeof(dest));
19 CHECK_PTR(hex_from_hash(dest, sample), dest);
20 CHECK_STR(dest, "000123456789ABCDEFFF10203040506070809" "0A0");
21 CHECK_INT(strlen(dest), 40);
22 CHECK_INT((unsigned char)dest[41], 0x7f);
23}
24
25static void case_decode(void) {
26 ot_hash hash;
27
28 test_case("forty digits decode back to the hash");
29 CHECK(hex_to_hash(hash, "000123456789ABCDEFFF10203040506070809" "0A0"));
30 CHECK_MEM(hash, sample, sizeof(sample));
31}
32
33static void case_round_trip(void) {
34 ot_hash hash;
35 char text[64];
36 size_t i;
37
38 test_case("encode and decode are inverses over every byte value");
39 for (i = 0; i < 256; ++i) {
40 uint8_t probe[20];
41 memset(probe, (uint8_t)i, sizeof(probe));
42 hex_from_hash(text, probe);
43 if (!hex_to_hash(hash, text) || memcmp(hash, probe, sizeof(probe))) {
44 test_failf(__FILE__, __LINE__, "round trip failed for byte value %zu", i);
45 return;
46 }
47 }
48 ++test_checks;
49}
50
51static void case_decode_is_case_insensitive(void) {
52 ot_hash upper, lower;
53
54 test_case("lower case digits decode the same as upper case");
55 CHECK(hex_to_hash(upper, "ABCDEF0123456789ABCDEF0123456789ABCDEF01"));
56 CHECK(hex_to_hash(lower, "abcdef0123456789abcdef0123456789abcdef01"));
57 CHECK_MEM(lower, upper, sizeof(ot_hash));
58}
59
60static void case_rejects_non_digits(void) {
61 ot_hash hash;
62
63 test_case("a non hex character anywhere rejects the whole string");
64 CHECK_INT(hex_to_hash(hash, "g00123456789ABCDEFFF102030405060708090A0"), 0);
65 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF102030405060708090Ag"), 0);
66 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEF:F102030405060708090A"), 0);
67}
68
69static void case_rejects_short_input(void) {
70 ot_hash hash;
71
72 test_case("a string shorter than forty digits is rejected");
73 CHECK_INT(hex_to_hash(hash, ""), 0);
74 CHECK_INT(hex_to_hash(hash, "00"), 0);
75 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF102030405060708090A"), 0);
76}
77
78static void case_leaves_hash_untouched_on_failure(void) {
79 ot_hash hash;
80
81 test_case("a rejected string leaves the destination untouched");
82 memset(hash, 0x5a, sizeof(hash));
83 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF10203040506070809XX0"), 0);
84 CHECK_MEM(hash, "\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a", sizeof(hash));
85}
86
87static void case_stops_at_the_terminator(void) {
88 /* The saved state parser hands this whole buffers that may end early. The
89 decoder must not read past the zero that stopped it. */
90 char guarded[8];
91 ot_hash hash;
92
93 test_case("decoding stops at a terminator rather than running past it");
94 memcpy(guarded, "0012", 4);
95 guarded[4] = 0;
96 memset(guarded + 5, 'f', 3);
97 CHECK_INT(hex_to_hash(hash, guarded), 0);
98}
99
100static void case_isdigit(void) {
101 test_case("hex_isdigit accepts exactly the hex digits");
102 CHECK(hex_isdigit('0'));
103 CHECK(hex_isdigit('9'));
104 CHECK(hex_isdigit('a'));
105 CHECK(hex_isdigit('f'));
106 CHECK(hex_isdigit('A'));
107 CHECK(hex_isdigit('F'));
108 CHECK_INT(hex_isdigit('g'), 0);
109 CHECK_INT(hex_isdigit('G'), 0);
110 CHECK_INT(hex_isdigit(':'), 0);
111 CHECK_INT(hex_isdigit('\n'), 0);
112 CHECK_INT(hex_isdigit(0), 0);
113 CHECK_INT(hex_isdigit(0x80), 0);
114}
115
116void test_hex(void) {
117 case_encode();
118 case_decode();
119 case_round_trip();
120 case_decode_is_case_insensitive();
121 case_rejects_non_digits();
122 case_rejects_short_input();
123 case_leaves_hash_untouched_on_failure();
124 case_stops_at_the_terminator();
125 case_isdigit();
126}
diff --git a/tests/t_iovec.c b/tests/t_iovec.c
new file mode 100644
index 0000000..1e8206d
--- /dev/null
+++ b/tests/t_iovec.c
@@ -0,0 +1,122 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7#include <sys/uio.h>
8
9/* Opentracker */
10#include "ot_iovec.h"
11#include "test.h"
12
13static void case_increase_and_length(void) {
14 size_t entries = 0;
15 struct iovec *vector = NULL;
16 void *first, *second;
17
18 test_case("increase appends an entry and length is their sum");
19 first = iovec_new_chunk(&entries, &vector, 100);
20 CHECK(first != NULL);
21 CHECK_INT(entries, 1);
22 CHECK_INT(vector[0].iov_len, 100);
23 CHECK_PTR(vector[0].iov_base, first);
24
25 second = iovec_new_chunk(&entries, &vector, 50);
26 CHECK(second != NULL);
27 CHECK_INT(entries, 2);
28 CHECK_INT(vector[1].iov_len, 50);
29 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 150);
30
31 iovec_free(&entries, &vector);
32}
33
34static void case_free_resets(void) {
35 size_t entries = 0;
36 struct iovec *vector = NULL;
37
38 test_case("free releases the entries and resets the vector");
39 CHECK(iovec_new_chunk(&entries, &vector, 10) != NULL);
40 CHECK(iovec_new_chunk(&entries, &vector, 10) != NULL);
41 iovec_free(&entries, &vector);
42 CHECK_INT(entries, 0);
43 CHECK_PTR(vector, NULL);
44 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 0);
45}
46
47static void case_fixlast_shrinks(void) {
48 size_t entries = 0;
49 struct iovec *vector = NULL;
50 char *block;
51
52 test_case("fixlast trims the last entry to the bytes actually used");
53 CHECK(iovec_new_chunk(&entries, &vector, 64) != NULL);
54 block = iovec_new_chunk(&entries, &vector, 1000);
55 CHECK(block != NULL);
56 memset(block, 'x', 20);
57
58 iovec_trim_last(&entries, &vector, block + 20);
59 CHECK_INT(entries, 2);
60 CHECK_INT(vector[1].iov_len, 20);
61 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 84);
62 CHECK_MEM(vector[1].iov_base, "xxxxxxxxxxxxxxxxxxxx", 20);
63
64 iovec_free(&entries, &vector);
65}
66
67static void case_fixlast_on_empty(void) {
68 size_t entries = 0;
69 struct iovec *vector = NULL;
70
71 test_case("fixlast on an empty vector does nothing");
72 iovec_trim_last(&entries, &vector, NULL);
73 CHECK_INT(entries, 0);
74 CHECK_PTR(vector, NULL);
75}
76
77static void case_append_takes_ownership(void) {
78 size_t entries = 0;
79 struct iovec *vector = NULL;
80 struct iovec source;
81
82 test_case("append moves the buffer and clears the source");
83 source.iov_base = malloc(10);
84 CHECK(source.iov_base != NULL);
85 memcpy(source.iov_base, "0123456789", 10);
86 source.iov_len = 10;
87
88 CHECK(iovec_append(&entries, &vector, &source) != NULL);
89 CHECK_INT(entries, 1);
90 CHECK_INT(vector[0].iov_len, 10);
91 CHECK_MEM(vector[0].iov_base, "0123456789", 10);
92 CHECK_PTR(source.iov_base, NULL);
93 CHECK_INT(source.iov_len, 0);
94
95 iovec_free(&entries, &vector);
96}
97
98static void case_fix_increase(void) {
99 size_t entries = 0;
100 struct iovec *vector = NULL;
101 char *block;
102
103 test_case("fix_increase trims the previous entry and adds a new one");
104 block = iovec_new_chunk(&entries, &vector, 500);
105 CHECK(block != NULL);
106 block = iovec_next_chunk(&entries, &vector, block + 30, 200);
107 CHECK(block != NULL);
108 CHECK_INT(entries, 2);
109 CHECK_INT(vector[0].iov_len, 30);
110 CHECK_INT(vector[1].iov_len, 200);
111
112 iovec_free(&entries, &vector);
113}
114
115void test_iovec(void) {
116 case_increase_and_length();
117 case_free_resets();
118 case_fixlast_shrinks();
119 case_fixlast_on_empty();
120 case_append_takes_ownership();
121 case_fix_increase();
122}
diff --git a/tests/t_ip.c b/tests/t_ip.c
new file mode 100644
index 0000000..218d3ff
--- /dev/null
+++ b/tests/t_ip.c
@@ -0,0 +1,215 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_ip.h"
10#include "test.h"
11
12static char text[64];
13
14static const char *formatted(const char *ip) {
15 text[ip_format(text, ip)] = 0;
16 return text;
17}
18
19/* ------------------------------------------------------------------ IPv4 */
20
21/* ------------------------------------------------------- RFC 5952 output */
22
23static void case_format_rfc5952(void) {
24 test_case("4.1 leading zeros in a group are suppressed");
25 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "2001:db8::1");
26
27 test_case("4.2.1 the longest run of zero groups becomes ::");
28 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01"), "2001:db8::2:1");
29
30 test_case("4.2.2 a single zero group is never shortened");
31 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01"), "2001:db8:0:1:1:1:1:1");
32
33 test_case("4.2.1 a longer run wins over an earlier shorter one");
34 CHECK_STR(formatted("\x20\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01"), "2001:0:0:1::1");
35
36 test_case("4.2.3 of two runs of equal length the first is shortened");
37 CHECK_STR(formatted("\x20\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x01\x00\x01"), "2001::1:0:0:1:1");
38
39 test_case("4.3 hexadecimal digits are lower case");
40 CHECK_STR(formatted("\xab\xcd\xef\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "abcd:ef01::1");
41
42 test_case("the unspecified and loopback addresses");
43 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), "::");
44 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "::1");
45
46 test_case("a full address with no zero group");
47 CHECK_STR(formatted("\x11\x11\x22\x22\x33\x33\x44\x44\x55\x55\x66\x66\x77\x77\x88\x88"), "1111:2222:3333:4444:5555:6666:7777:8888");
48}
49
50static void case_format_trailing_zero_group(void) {
51 /* libowfat's formatter looked two bytes past the address to decide this
52 one, so a peer address ending in a zero group came out as "::" whenever
53 the bytes that happened to follow were not themselves zero. In
54 ot_stats.c those bytes are the peer's port. */
55 const char ip[] = "\x20\x01\x0d\xb8\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x00";
56
57 test_case("a single trailing zero group is written out, not shortened");
58 CHECK_STR(formatted(ip), "2001:db8:1:2:3:4:5:0");
59
60 test_case("and nothing beyond the sixteen bytes is consulted");
61 {
62 char padded[20];
63 memcpy(padded, ip, 16);
64 memset(padded + 16, 0xff, 4); /* a port and flags, as a peer record has */
65 CHECK_STR(formatted(padded), "2001:db8:1:2:3:4:5:0");
66 memset(padded + 16, 0x00, 4);
67 CHECK_STR(formatted(padded), "2001:db8:1:2:3:4:5:0");
68 }
69}
70
71static void case_v4mapped(void) {
72 const char mapped[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x0a\x00\x00\x01";
73 const char unmapped[] = "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01";
74
75 test_case("a v4 mapped address is recognised");
76 CHECK(ip_is_v4mapped(mapped));
77 CHECK_INT(ip_is_v4mapped(unmapped), 0);
78
79 /* The tracker has only ever shown the plain quad, so that is the one
80 form the formatter produces; "::ffff:10.0.0.1" is not written anywhere */
81 test_case("a mapped address is written as the plain dotted quad");
82 CHECK_STR(formatted(mapped), "10.0.0.1");
83 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00"), "0.0.0.0");
84 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff"), "255.255.255.255");
85
86 test_case("anything else follows RFC 5952");
87 CHECK_STR(formatted(unmapped), "2001:db8::1");
88}
89
90/* -------------------------------------------------------- RFC 4291 input */
91
92static void case_scan_forms(void) {
93 char ip[16];
94
95 test_case("2.2 form 1, every group spelled out");
96 CHECK_INT(ip_parse("1111:2222:3333:4444:5555:6666:7777:8888", ip), 39);
97 CHECK_MEM(ip, "\x11\x11\x22\x22\x33\x33\x44\x44\x55\x55\x66\x66\x77\x77\x88\x88", 16);
98
99 test_case("2.2 form 2, zero groups abbreviated");
100 CHECK_INT(ip_parse("2001:db8::1", ip), 11);
101 CHECK_MEM(ip, "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
102 CHECK_INT(ip_parse("::1", ip), 3);
103 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
104 CHECK_INT(ip_parse("::", ip), 2);
105 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
106 CHECK_INT(ip_parse("1::", ip), 3);
107 CHECK_MEM(ip, "\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
108
109 test_case("2.2 form 3, a dotted quad in the last two groups");
110 CHECK_INT(ip_parse("::ffff:1.2.3.4", ip), 14);
111 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x01\x02\x03\x04", 16);
112 CHECK_INT(ip_parse("1:2:3:4:5:6:1.2.3.4", ip), 19);
113 CHECK_MEM(ip, "\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x01\x02\x03\x04", 16);
114
115 test_case("upper case input is accepted");
116 CHECK_INT(ip_parse("2001:DB8::1", ip), 11);
117 CHECK_MEM(ip, "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
118}
119
120static void case_scan_accepts_bare_ipv4(void) {
121 char ip[16];
122
123 /* Every address opentracker holds is sixteen bytes, so an operator writing
124 a plain IPv4 address in the config has to land as the v4 mapped form */
125 test_case("a bare IPv4 address is stored v4 mapped");
126 CHECK_INT(ip_parse("10.0.0.1", ip), 8);
127 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x0a\x00\x00\x01", 16);
128 CHECK(ip_is_v4mapped(ip));
129}
130
131static void case_scan_reports_length(void) {
132 char ip[16];
133
134 /* The config parser continues from where the address ended, which is how
135 "address:port" and "address/bits" are read */
136 test_case("scanning stops at the character after the address");
137 CHECK_INT(ip_parse("10.0.0.1:6969", ip), 8);
138 CHECK_INT(ip_parse("2001:db8::1/64", ip), 11);
139 CHECK_INT(ip_parse("::1]", ip), 3);
140 CHECK_INT(ip_parse("1:2:3:4:5:6:7:8 trailing", ip), 15);
141}
142
143static void case_scan_rejects(void) {
144 char ip[16];
145
146 test_case("an empty or junk string is refused");
147 CHECK_INT(ip_parse("", ip), 0);
148 CHECK_INT(ip_parse("x", ip), 0);
149 CHECK_INT(ip_parse(":", ip), 0);
150 CHECK_INT(ip_parse(":1:2", ip), 0);
151
152 test_case("too few groups without :: are refused");
153 CHECK_INT(ip_parse("1:2:3:4:5:6:7", ip), 0);
154 CHECK_INT(ip_parse("2001:db8:1", ip), 0);
155
156 /* libowfat accepted a prefix of each of these and carried on. Taking only
157 part of a malformed address is worse than refusing it, especially where
158 the text comes from a config file or an X-Forwarded-For header. */
159 test_case("a second :: is refused rather than truncated");
160 CHECK_INT(ip_parse("1::2::3", ip), 0);
161 CHECK_INT(ip_parse("::1::", ip), 0);
162 CHECK_INT(ip_parse("::::", ip), 0);
163
164 test_case("more than eight groups is refused");
165 CHECK_INT(ip_parse("1:2:3:4:5:6:7:8:9", ip), 0);
166
167 test_case("a group of more than four digits is refused, not truncated");
168 CHECK_INT(ip_parse("12345::1", ip), 0);
169 CHECK_INT(ip_parse("fffff::1", ip), 0);
170}
171
172static void case_round_trip(void) {
173 /* Whatever the formatter writes, the scanner has to read back */
174 static const char *const samples[] = {"::",
175 "::1",
176 "1::",
177 "2001:db8::1",
178 "2001:db8:1:2:3:4:5:0",
179 "1111:2222:3333:4444:5555:6666:7777:8888",
180 "2001::1:0:0:1",
181 "abcd:ef01::1",
182 NULL};
183 char ip[16], again[16];
184 size_t i;
185
186 test_case("every formatted address scans back to the same bytes");
187 for (i = 0; samples[i]; ++i) {
188 size_t n = ip_parse(samples[i], ip);
189 if (n != strlen(samples[i])) {
190 test_failf(__FILE__, __LINE__, "\"%s\" consumed %zu of %zu", samples[i], n, strlen(samples[i]));
191 return;
192 }
193 text[ip_format(text, ip)] = 0;
194 if (strcmp(text, samples[i])) {
195 test_failf(__FILE__, __LINE__, "\"%s\" formatted back as \"%s\"", samples[i], text);
196 return;
197 }
198 if (!ip_parse(text, again) || memcmp(ip, again, 16)) {
199 test_failf(__FILE__, __LINE__, "\"%s\" did not survive a second pass", samples[i]);
200 return;
201 }
202 }
203 ++test_checks;
204}
205
206void test_ip(void) {
207 case_format_rfc5952();
208 case_format_trailing_zero_group();
209 case_v4mapped();
210 case_scan_forms();
211 case_scan_accepts_bare_ipv4();
212 case_scan_reports_length();
213 case_scan_rejects();
214 case_round_trip();
215}
diff --git a/tests/t_mutex.c b/tests/t_mutex.c
new file mode 100644
index 0000000..c0c41cc
--- /dev/null
+++ b/tests/t_mutex.c
@@ -0,0 +1,136 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <string.h>
8#include <unistd.h>
9
10/* Opentracker */
11#include "ot_mutex.h"
12#include "test.h"
13
14/* Every announce passes through here, and what it has to get right is which
15 bucket a hash belongs to and that two threads never hold one bucket at
16 once. Both are checked against real mutexes rather than a stand-in. */
17
18/* A hash that lands in a chosen bucket: the bucket is the top
19 OT_BUCKET_COUNT_BITS of the first four bytes, read in network order */
20static void hash_for_bucket(ot_hash hash, int bucket) {
21 memset(hash, 0, sizeof(ot_hash));
22 hash[0] = (uint8_t)(bucket >> (OT_BUCKET_COUNT_BITS - 8));
23 hash[1] = (uint8_t)((bucket << (16 - OT_BUCKET_COUNT_BITS)) & 0xff);
24}
25
26static void case_a_hash_names_its_bucket(void) {
27 static const int buckets[] = {0, 1, 2, 17, OT_BUCKET_COUNT / 2 - 1, OT_BUCKET_COUNT / 2, OT_BUCKET_COUNT - 1};
28 size_t i;
29
30 test_case("a hash is served by the bucket its leading bits name");
31 for (i = 0; i < sizeof(buckets) / sizeof(buckets[0]); ++i) {
32 ot_hash hash;
33 ot_vector *by_hash, *by_number;
34
35 hash_for_bucket(hash, buckets[i]);
36 by_hash = mutex_bucket_lock_by_hash(hash);
37 mutex_bucket_unlock_by_hash(hash, 0);
38
39 by_number = mutex_bucket_lock(buckets[i]);
40 mutex_bucket_unlock(buckets[i], 0);
41
42 CHECK(by_hash == by_number);
43 }
44}
45
46static void case_every_bucket_is_its_own(void) {
47 ot_vector *first, *last, *middle;
48
49 test_case("no two buckets are the same one");
50 first = mutex_bucket_lock(0);
51 mutex_bucket_unlock(0, 0);
52 middle = mutex_bucket_lock(OT_BUCKET_COUNT / 2);
53 mutex_bucket_unlock(OT_BUCKET_COUNT / 2, 0);
54 last = mutex_bucket_lock(OT_BUCKET_COUNT - 1);
55 mutex_bucket_unlock(OT_BUCKET_COUNT - 1, 0);
56
57 CHECK(first != middle);
58 CHECK(middle != last);
59 CHECK(first != last);
60}
61
62static void case_the_count_follows_what_unlock_is_told(void) {
63 size_t before = mutex_get_torrent_count();
64
65 test_case("the torrent count moves by what unlocking reports, and not otherwise");
66 mutex_bucket_lock(3);
67 mutex_bucket_unlock(3, 0);
68 CHECK_INT((int)(mutex_get_torrent_count() - before), 0);
69
70 mutex_bucket_lock(3);
71 mutex_bucket_unlock(3, 5);
72 CHECK_INT((int)(mutex_get_torrent_count() - before), 5);
73
74 mutex_bucket_lock(3);
75 mutex_bucket_unlock(3, -2);
76 CHECK_INT((int)(mutex_get_torrent_count() - before), 3);
77}
78
79static _Atomic int g_other_got_in;
80
81static void *take_a_bucket(void *args) {
82 int bucket = (int)(intptr_t)args;
83
84 mutex_bucket_lock(bucket);
85 atomic_store(&g_other_got_in, 1);
86 mutex_bucket_unlock(bucket, 0);
87 return NULL;
88}
89
90static int waited_for_entry(int patience_ms) {
91 int waited;
92
93 for (waited = 0; waited < patience_ms && !atomic_load(&g_other_got_in); ++waited)
94 usleep(1000);
95 return atomic_load(&g_other_got_in);
96}
97
98static void case_a_held_bucket_keeps_others_out(void) {
99 pthread_t other;
100
101 test_case("a second thread waits for the bucket this one holds");
102 atomic_store(&g_other_got_in, 0);
103 mutex_bucket_lock(9);
104 CHECK_INT(pthread_create(&other, NULL, take_a_bucket, (void *)(intptr_t)9), 0);
105
106 CHECK_INT(waited_for_entry(200), 0);
107
108 mutex_bucket_unlock(9, 0);
109 CHECK_INT(waited_for_entry(2000), 1);
110 pthread_join(other, NULL);
111}
112
113static void case_another_bucket_is_free_meanwhile(void) {
114 pthread_t other;
115
116 test_case("and a different bucket is not held up by it");
117 atomic_store(&g_other_got_in, 0);
118 mutex_bucket_lock(9);
119 CHECK_INT(pthread_create(&other, NULL, take_a_bucket, (void *)(intptr_t)10), 0);
120
121 CHECK_INT(waited_for_entry(2000), 1);
122 pthread_join(other, NULL);
123 mutex_bucket_unlock(9, 0);
124}
125
126void test_mutex(void) {
127 mutex_init();
128
129 case_a_hash_names_its_bucket();
130 case_every_bucket_is_its_own();
131 case_the_count_follows_what_unlock_is_told();
132 case_a_held_bucket_keeps_others_out();
133 case_another_bucket_is_free_meanwhile();
134
135 mutex_deinit();
136}
diff --git a/tests/t_random.c b/tests/t_random.c
new file mode 100644
index 0000000..b070c3f
--- /dev/null
+++ b/tests/t_random.c
@@ -0,0 +1,112 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_random.h"
10#include "test.h"
11
12/* Nothing here can test that the bytes are unpredictable, which is a property
13 of the generator the build selected. What these cases do pin is that the
14 wrapper hands the whole buffer to it, writes nothing beyond the length it
15 was given, and is actually wired to something that varies. The first of
16 those matters: the fallback this module replaced filled only the first
17 sixteen bytes of the sixty-four byte key buffer in ot_udp.c. */
18
19#define DRAWS 32
20#define BUFLEN 64
21
22static void case_every_byte_varies(void) {
23 unsigned char first[BUFLEN], draw[BUFLEN];
24 unsigned char varied[BUFLEN];
25 size_t i, n;
26
27 test_case("every byte of the buffer comes from the generator");
28 memset(varied, 0, sizeof(varied));
29 random_bytes(first, sizeof(first));
30
31 for (n = 0; n < DRAWS; ++n) {
32 random_bytes(draw, sizeof(draw));
33 for (i = 0; i < BUFLEN; ++i)
34 if (draw[i] != first[i])
35 varied[i] = 1;
36 }
37
38 /* A byte position that never moved across 32 draws is not being written.
39 A false alarm needs all 32 draws to agree by chance, around 256^-31. */
40 for (i = 0; i < BUFLEN; ++i)
41 if (!varied[i]) {
42 test_failf(__FILE__, __LINE__, "byte %zu never changed over %d draws", i, DRAWS);
43 return;
44 }
45 ++test_checks;
46}
47
48static void case_respects_length(void) {
49 unsigned char buf[32];
50 size_t i;
51
52 test_case("nothing is written past the requested length");
53 memset(buf, 0xA5, sizeof(buf));
54 random_bytes(buf, 8);
55 for (i = 8; i < sizeof(buf); ++i)
56 if (buf[i] != 0xA5) {
57 test_failf(__FILE__, __LINE__, "byte %zu past the end was overwritten", i);
58 return;
59 }
60 ++test_checks;
61}
62
63static void case_zero_length(void) {
64 unsigned char buf[4];
65
66 test_case("a zero length request writes nothing");
67 memset(buf, 0x5A, sizeof(buf));
68 random_bytes(buf, 0);
69 CHECK_MEM(buf, "\x5a\x5a\x5a\x5a", 4);
70}
71
72static void case_successive_draws_differ(void) {
73 unsigned char a[32], b[32];
74
75 test_case("two draws differ");
76 random_bytes(a, sizeof(a));
77 random_bytes(b, sizeof(b));
78 CHECK(memcmp(a, b, sizeof(a)) != 0);
79}
80
81static void case_uint32_varies(void) {
82 uint32_t first = random_uint32();
83 int differs = 0;
84 size_t n;
85
86 test_case("random_uint32 does not return a constant");
87 for (n = 0; n < DRAWS; ++n)
88 if (random_uint32() != first)
89 differs = 1;
90 CHECK(differs);
91}
92
93static void case_uint32_uses_the_top_bit(void) {
94 uint32_t seen = 0;
95 size_t n;
96
97 test_case("random_uint32 spans the full 32 bits");
98 /* random() never sets bit 31, so a build that returned it unmixed would
99 fail this. Over 64 draws the chance of a false alarm is 2^-64. */
100 for (n = 0; n < 64; ++n)
101 seen |= random_uint32();
102 CHECK_INT(seen & 0x80000000u, 0x80000000u);
103}
104
105void test_random(void) {
106 case_every_byte_varies();
107 case_respects_length();
108 case_zero_length();
109 case_successive_draws_differ();
110 case_uint32_varies();
111 case_uint32_uses_the_top_bit();
112}
diff --git a/tests/t_scan.c b/tests/t_scan.c
new file mode 100644
index 0000000..05c4a67
--- /dev/null
+++ b/tests/t_scan.c
@@ -0,0 +1,210 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_scan.h"
10#include "test.h"
11
12static void case_plain_numbers(void) {
13 uint64_t value;
14
15 test_case("a decimal number is read and its length reported");
16 CHECK_INT(scan_uint("0", &value, 65535), 1);
17 CHECK_INT(value, 0);
18 CHECK_INT(scan_uint("7", &value, 65535), 1);
19 CHECK_INT(value, 7);
20 CHECK_INT(scan_uint("6969", &value, 65535), 4);
21 CHECK_INT(value, 6969);
22 CHECK_INT(scan_uint("65535", &value, 65535), 5);
23 CHECK_INT(value, 65535);
24}
25
26static void case_stops_at_non_digit(void) {
27 uint64_t value;
28
29 test_case("scanning stops at the first character that is not a digit");
30 CHECK_INT(scan_uint("6969:rest", &value, 65535), 4);
31 CHECK_INT(value, 6969);
32 CHECK_INT(scan_uint("128/8", &value, 65535), 3);
33 CHECK_INT(value, 128);
34 CHECK_INT(scan_uint("42\n", &value, 65535), 2);
35 CHECK_INT(value, 42);
36}
37
38static void case_rejects_whitespace(void) {
39 uint64_t value = 0xdead;
40
41 test_case("leading whitespace is not skipped");
42 CHECK_INT(scan_uint(" 1", &value, 65535), 0);
43 CHECK_INT(scan_uint("\t1", &value, 65535), 0);
44 CHECK_INT(scan_uint("\n1", &value, 65535), 0);
45 CHECK_INT(value, 0xdead);
46}
47
48static void case_rejects_sign(void) {
49 uint64_t value = 0xdead;
50
51 test_case("a sign is not accepted");
52 CHECK_INT(scan_uint("+1", &value, 65535), 0);
53 CHECK_INT(scan_uint("-1", &value, 65535), 0);
54 CHECK_INT(scan_uint("-0", &value, 65535), 0);
55 CHECK_INT(value, 0xdead);
56}
57
58static void case_rejects_empty_and_junk(void) {
59 uint64_t value = 0xdead;
60
61 test_case("a string with no leading digit yields nothing");
62 CHECK_INT(scan_uint("", &value, 65535), 0);
63 CHECK_INT(scan_uint("x", &value, 65535), 0);
64 CHECK_INT(scan_uint(":80", &value, 65535), 0);
65 CHECK_INT(value, 0xdead);
66}
67
68static void case_no_alternative_bases(void) {
69 uint64_t value;
70
71 test_case("hexadecimal and octal notations are read as plain decimal");
72 CHECK_INT(scan_uint("0x10", &value, 65535), 1);
73 CHECK_INT(value, 0);
74 CHECK_INT(scan_uint("010", &value, 65535), 3);
75 CHECK_INT(value, 10);
76}
77
78static void case_refuses_out_of_range(void) {
79 uint64_t value = 0xdead;
80
81 test_case("a value above max is refused, not truncated");
82 CHECK_INT(scan_uint("65536", &value, 65535), 0);
83 CHECK_INT(scan_uint("99999", &value, 65535), 0);
84 CHECK_INT(scan_uint("129", &value, 128), 0);
85 CHECK_INT(value, 0xdead);
86
87 test_case("the boundary itself is accepted");
88 CHECK_INT(scan_uint("128", &value, 128), 3);
89 CHECK_INT(value, 128);
90}
91
92static void case_sixty_four_bit_range(void) {
93 uint64_t value;
94
95 test_case("the full unsigned 64 bit range is available");
96 CHECK_INT(scan_uint("18446744073709551615", &value, UINT64_MAX), 20);
97 CHECK(value == UINT64_MAX);
98
99 test_case("a number too large for 64 bits is refused");
100 CHECK_INT(scan_uint("18446744073709551616", &value, UINT64_MAX), 0);
101 CHECK_INT(scan_uint("99999999999999999999999999", &value, UINT64_MAX), 0);
102}
103
104static void case_leading_zeros_allowed(void) {
105 uint64_t value;
106
107 test_case("leading zeros are accepted outside bencode");
108 CHECK_INT(scan_uint("007", &value, 65535), 3);
109 CHECK_INT(value, 7);
110 CHECK_INT(scan_uint("0000", &value, 65535), 4);
111 CHECK_INT(value, 0);
112}
113
114static void case_bencode_rejects_leading_zeros(void) {
115 uint64_t value = 0xdead;
116
117 test_case("bencode refuses a leading zero on anything but zero");
118 CHECK_INT(scan_uint_bencode("007", &value, 65535), 0);
119 CHECK_INT(scan_uint_bencode("0000", &value, 65535), 0);
120 CHECK_INT(scan_uint_bencode("01", &value, 65535), 0);
121 CHECK_INT(value, 0xdead);
122}
123
124static void case_bencode_accepts_canonical(void) {
125 uint64_t value;
126
127 test_case("bencode accepts a canonically written number");
128 CHECK_INT(scan_uint_bencode("0", &value, 65535), 1);
129 CHECK_INT(value, 0);
130 CHECK_INT(scan_uint_bencode("0:", &value, 65535), 1);
131 CHECK_INT(value, 0);
132 CHECK_INT(scan_uint_bencode("160:", &value, 65535), 3);
133 CHECK_INT(value, 160);
134}
135
136static void case_bencode_inherits_the_rest(void) {
137 uint64_t value = 0xdead;
138
139 test_case("bencode is no laxer than the plain scanner");
140 CHECK_INT(scan_uint_bencode(" 1", &value, 65535), 0);
141 CHECK_INT(scan_uint_bencode("-1", &value, 65535), 0);
142 CHECK_INT(scan_uint_bencode("+1", &value, 65535), 0);
143 CHECK_INT(scan_uint_bencode("65536", &value, 65535), 0);
144 CHECK_INT(value, 0xdead);
145}
146
147/* ------------------------------------------- fixed width signed integers */
148
149/* A value lifted out of a query string arrives as a pointer and a length
150 with nothing terminating it, and the whole of it has to be the number. */
151
152static void case_int_whole_field(void) {
153 int64_t value = 0;
154
155 test_case("the whole field is read, sign and all");
156 CHECK_INT(scan_int("123", 3, &value), 0);
157 CHECK_INT(value, 123);
158 CHECK_INT(scan_int("-45", 3, &value), 0);
159 CHECK_INT(value, -45);
160
161 test_case("and only as far as the length given");
162 CHECK_INT(scan_int("12345", 3, &value), 0);
163 CHECK_INT(value, 123);
164}
165
166static void case_int_rejects_the_rest(void) {
167 int64_t value = 4711;
168
169 test_case("anything that is not all digits is refused");
170 CHECK_INT(scan_int("12a", 3, &value), -1);
171 CHECK_INT(scan_int("", 0, &value), -1);
172 CHECK_INT(scan_int("-", 1, &value), -1);
173 CHECK_INT(scan_int(" 12", 3, &value), -1);
174 CHECK_INT(scan_int("+12", 3, &value), -1);
175
176 test_case("and a refused field leaves the number alone");
177 CHECK_INT(value, 4711);
178}
179
180static void case_int_overflow(void) {
181 int64_t value = 0;
182
183 test_case("a field too long to fit is refused rather than wrapped");
184 CHECK_INT(scan_int("9223372036854775807", 19, &value), 0);
185 CHECK_INT(value, INT64_MAX);
186 CHECK_INT(scan_int("9223372036854775808", 19, &value), -1);
187 CHECK_INT(scan_int("99999999999999999999", 20, &value), -1);
188
189 test_case("including the negative side");
190 CHECK_INT(scan_int("-9223372036854775807", 20, &value), 0);
191 CHECK_INT(value, -INT64_MAX);
192}
193
194void test_scan(void) {
195 case_int_whole_field();
196 case_int_rejects_the_rest();
197 case_int_overflow();
198 case_plain_numbers();
199 case_stops_at_non_digit();
200 case_rejects_whitespace();
201 case_rejects_sign();
202 case_rejects_empty_and_junk();
203 case_no_alternative_bases();
204 case_refuses_out_of_range();
205 case_sixty_four_bit_range();
206 case_leading_zeros_allowed();
207 case_bencode_rejects_leading_zeros();
208 case_bencode_accepts_canonical();
209 case_bencode_inherits_the_rest();
210}
diff --git a/tests/t_socket.c b/tests/t_socket.c
new file mode 100644
index 0000000..6f07f95
--- /dev/null
+++ b/tests/t_socket.c
@@ -0,0 +1,416 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <fcntl.h>
7#include <netinet/in.h>
8#include <poll.h>
9#include <pthread.h>
10#include <signal.h>
11#include <stdatomic.h>
12#include <string.h>
13#include <sys/socket.h>
14#include <sys/time.h>
15#include <unistd.h>
16
17/* Opentracker */
18#include "ot_ip.h"
19#include "ot_socket.h"
20#include "trackerlogic.h"
21#include "test.h"
22
23/* These cases talk to the loopback interface rather than to a mock, because
24 what is worth pinning down here is the behaviour of the socket options the
25 rest of the tracker relies on, and only the kernel can report that. */
26
27static const char ip_any[16] = {0};
28static const char ip_loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
29static const char ip_v4_loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1};
30/* RFC 3849 reserves 2001:db8::/32 for documentation, so no host carries it */
31static const char ip_unassigned[16] = {0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
32
33/* What a socket ended up bound to, which is not always what was asked for: a
34 FreeBSD jail, for one, rewrites a loopback bind to the address it was given.
35 A datagram a socket sends to itself must come back carrying this, so the
36 cases below compare against it rather than against the address they passed
37 to the bind. */
38static void bound_address(int s, char ip[16], uint16_t *port) {
39 struct sockaddr_storage ss;
40 socklen_t len = sizeof(ss);
41
42 memset(&ss, 0, sizeof(ss));
43 memset(ip, 0, 16);
44 *port = 0;
45 if (getsockname(s, (struct sockaddr *)&ss, &len) == -1)
46 return;
47
48 /* Spelled out here rather than borrowed from ot_socket.c, so that a wrong
49 idea about how a kernel reports an address cannot hide in both at once */
50 if (ss.ss_family == AF_INET) {
51 const struct sockaddr_in *sa = (const struct sockaddr_in *)&ss;
52
53 memcpy(ip, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix));
54 memcpy(ip + sizeof(ip_v4mapped_prefix), &sa->sin_addr, 4);
55 *port = ntohs(sa->sin_port);
56 } else {
57 const struct sockaddr_in6 *sa = (const struct sockaddr_in6 *)&ss;
58
59 memcpy(ip, &sa->sin6_addr, 16);
60 *port = ntohs(sa->sin6_port);
61 }
62}
63
64static int is_nonblocking(int s) {
65 int flags = fcntl(s, F_GETFL, 0);
66 return flags != -1 && (flags & O_NONBLOCK) != 0;
67}
68
69static int sock_flag(int s, int level, int option) {
70 int value = -1;
71 socklen_t len = sizeof(value);
72
73 if (getsockopt(s, level, option, &value, &len) == -1)
74 return -1;
75 return value != 0;
76}
77
78/* Wait for one event, so a test never blocks forever on a lost packet */
79static int wait_for_ms(int s, short events, int timeout_ms) {
80 struct pollfd pfd;
81
82 pfd.fd = s;
83 pfd.events = events;
84 pfd.revents = 0;
85 return poll(&pfd, 1, timeout_ms) == 1;
86}
87
88static int wait_for(int s, short events) { return wait_for_ms(s, events, 2000); }
89
90/* ------------------------------------------------------------ invariants */
91
92/* Asked for the wildcard address, because a socket bound to one specific
93 IPv6 address cannot carry IPv4 traffic anyway and Linux turns IPV6_V6ONLY
94 back on in that case. The tracker's own default is the wildcard. */
95static void case_socket_options(void) {
96 int udp, tcp;
97
98 test_case("a bound udp socket is non blocking and serves both families");
99 udp = socket_udp_bind(ip_any, 0, SOCKET_EXCLUSIVE);
100 CHECK(udp != -1);
101 CHECK_INT(is_nonblocking(udp), 1);
102 CHECK_INT(sock_flag(udp, IPPROTO_IPV6, IPV6_V6ONLY), 0);
103 close(udp);
104
105 test_case("a listening tcp socket is non blocking and serves both families");
106 tcp = socket_tcp_listen(ip_any, 0, SOCKET_EXCLUSIVE);
107 CHECK(tcp != -1);
108 CHECK_INT(is_nonblocking(tcp), 1);
109 CHECK_INT(sock_flag(tcp, IPPROTO_IPV6, IPV6_V6ONLY), 0);
110 close(tcp);
111}
112
113#ifdef SO_REUSEPORT
114static void case_sharing_is_opt_in(void) {
115 int s;
116
117 test_case("an address is exclusive unless sharing is asked for");
118 s = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
119 CHECK(s != -1);
120 CHECK_INT(sock_flag(s, SOL_SOCKET, SO_REUSEPORT), 0);
121 close(s);
122
123 test_case("and shared when it is");
124 s = socket_udp_bind(ip_loopback, 0, SOCKET_SHARED);
125 CHECK(s != -1);
126 CHECK_INT(sock_flag(s, SOL_SOCKET, SO_REUSEPORT), 1);
127 close(s);
128}
129#endif
130
131/* ------------------------------------------------------------------- udp */
132
133static void case_udp_roundtrip(void) {
134 char buf[32], ip[16], own_ip[16];
135 uint16_t port = 0, own_port = 0;
136 int s;
137
138 test_case("a datagram comes back with the sender's address and port");
139 s = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
140 CHECK(s != -1);
141 bound_address(s, own_ip, &own_port);
142 CHECK(own_port != 0);
143 CHECK_INT(socket_send(s, "opentracker", 11, own_ip, own_port), 11);
144 CHECK_INT(wait_for(s, POLLIN), 1);
145 CHECK_INT(socket_recv(s, buf, sizeof(buf), ip, &port), 11);
146 CHECK_MEM(buf, "opentracker", 11);
147 CHECK_MEM(ip, own_ip, 16);
148 CHECK_INT(port, own_port);
149 close(s);
150}
151
152/* udp_workers_deinit and livesync_deinit end a read another thread is parked
153 in by signalling that thread. Which mechanisms wake a blocked reader
154 differs between kernels -- shutting the socket down does so on Linux and
155 FreeBSD but not on Darwin, closing it does so on Darwin but not on Linux --
156 so the one the tracker relies on is checked rather than assumed. The
157 watchdog is the test's own: where a reader is not woken this fails with a
158 figure to look at instead of hanging the suite. */
159static _Atomic int reader_returned;
160static int reader_socket;
161
162static void reader_wake(int s) { (void)s; }
163
164static void *blocked_reader(void *args) {
165 char buf[32], ip[16];
166 uint16_t port = 0;
167
168 (void)args;
169 socket_recv(reader_socket, buf, sizeof(buf), ip, &port);
170 atomic_store(&reader_returned, 1);
171 return NULL;
172}
173
174static void case_a_signal_ends_a_blocking_read(void) {
175 struct sigaction sa;
176 struct timeval watchdog = {2, 0};
177 pthread_t thread;
178 int waited;
179
180 test_case("a signal ends a read another thread is parked in");
181 memset(&sa, 0, sizeof(sa));
182 sa.sa_handler = reader_wake;
183 sa.sa_flags = 0; /* SA_RESTART would resume the read instead of ending it */
184 CHECK_INT(sigaction(OT_SIGNAL_WAKE, &sa, NULL), 0);
185
186 atomic_store(&reader_returned, 0);
187 reader_socket = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
188 CHECK(reader_socket != -1);
189 CHECK_INT(socket_set_blocking(reader_socket, 1), 0);
190 CHECK_INT(setsockopt(reader_socket, SOL_SOCKET, SO_RCVTIMEO, &watchdog, sizeof(watchdog)), 0);
191
192 CHECK_INT(pthread_create(&thread, NULL, blocked_reader, NULL), 0);
193 usleep(100000); /* long enough to be sure it reached the read */
194 CHECK_INT(pthread_kill(thread, OT_SIGNAL_WAKE), 0);
195
196 for (waited = 0; waited < 1000 && !atomic_load(&reader_returned); ++waited)
197 usleep(1000);
198 CHECK(waited < 1000);
199 pthread_join(thread, NULL);
200 close(reader_socket);
201}
202
203/* What a deferred accept is for is a descriptor that already has the request
204 in it, so what is checked is the silence before: a client that has
205 connected but said nothing must not make the listener readable. Kernels
206 that cannot do this say so, and then there is nothing to check. */
207static void case_deferred_accept(void) {
208 struct sockaddr_in6 address;
209 char ip[16];
210 uint16_t port = 0;
211 int listener, client;
212
213 test_case("a connection that has sent nothing is held back from accept");
214 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
215 CHECK(listener != -1);
216 if (socket_defer_accept(listener) == -1) {
217 close(listener);
218 return;
219 }
220 bound_address(listener, ip, &port);
221
222 client = socket(AF_INET6, SOCK_STREAM, 0);
223 CHECK(client != -1);
224 memset(&address, 0, sizeof(address));
225 address.sin6_family = AF_INET6;
226 address.sin6_port = htons(port);
227 memcpy(&address.sin6_addr, ip_loopback, 16);
228 CHECK_INT(connect(client, (struct sockaddr *)&address, sizeof(address)), 0);
229
230 CHECK_INT(wait_for_ms(listener, POLLIN, 300), 0);
231
232 CHECK_INT((int)write(client, "GET / HTTP/1.0\r\n\r\n", 18), 18);
233 CHECK_INT(wait_for(listener, POLLIN), 1);
234
235 close(client);
236 close(listener);
237}
238
239/* An IPv4 peer must arrive in the v4 mapped form opentracker stores, however
240 the kernel chose to report it. Linux fills a v4 mapped sockaddr_in6 here
241 and the BSDs fill a plain sockaddr_in, so this is the case that tells the
242 two apart. */
243static void case_udp_v4mapped(void) {
244 char buf[32], ip[16], receiver_ip[16], sender_ip[16];
245 uint16_t port = 0, receiver_port = 0, sender_port = 0;
246 int receiver, sender;
247
248 test_case("an IPv4 sender is reported in its v4 mapped form");
249 receiver = socket_udp_bind(ip_v4_loopback, 0, SOCKET_EXCLUSIVE);
250 CHECK(receiver != -1);
251 sender = socket_udp_bind(ip_v4_loopback, 0, SOCKET_EXCLUSIVE);
252 CHECK(sender != -1);
253 bound_address(receiver, receiver_ip, &receiver_port);
254 bound_address(sender, sender_ip, &sender_port);
255 CHECK_INT(ip_is_v4mapped(sender_ip), 1);
256
257 CHECK_INT(socket_send(sender, "v4", 2, receiver_ip, receiver_port), 2);
258 CHECK_INT(wait_for(receiver, POLLIN), 1);
259 CHECK_INT(socket_recv(receiver, buf, sizeof(buf), ip, &port), 2);
260 CHECK_INT(ip_is_v4mapped(ip), 1);
261 CHECK_MEM(ip, sender_ip, 16);
262 CHECK_INT(port, sender_port);
263 close(sender);
264 close(receiver);
265}
266
267/* ------------------------------------------------------------------- tcp */
268
269static void case_tcp_roundtrip(void) {
270 char ip[16], listener_ip[16], client_ip[16];
271 uint16_t port = 0, listener_port = 0, client_port = 0;
272 int listener, client, accepted;
273
274 test_case("a connection is accepted and carries the caller's address");
275 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
276 CHECK(listener != -1);
277 bound_address(listener, listener_ip, &listener_port);
278 CHECK(listener_port != 0);
279
280 client = socket_tcp_connect(ip_loopback, 0, listener_ip, listener_port);
281 CHECK(client != -1);
282 CHECK_INT(wait_for(client, POLLOUT), 1);
283 CHECK_INT(socket_is_connected(client), 1);
284 bound_address(client, client_ip, &client_port);
285
286 CHECK_INT(wait_for(listener, POLLIN), 1);
287 accepted = socket_accept(listener, ip, &port);
288 CHECK(accepted != -1);
289 CHECK_MEM(ip, client_ip, 16);
290 CHECK_INT(port, client_port);
291
292 test_case("the accepted socket is handed over non blocking");
293 CHECK_INT(is_nonblocking(accepted), 1);
294
295 close(accepted);
296 close(client);
297 close(listener);
298}
299
300static void case_connect_refused(void) {
301 char listener_ip[16];
302 int listener, client;
303 uint16_t port;
304
305 test_case("a refused connection is reported by socket_is_connected");
306 /* Take a port, then drop it, so nothing is listening on it any more */
307 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
308 CHECK(listener != -1);
309 bound_address(listener, listener_ip, &port);
310 close(listener);
311
312 client = socket_tcp_connect(ip_loopback, 0, listener_ip, port);
313 CHECK(client != -1);
314 CHECK_INT(wait_for(client, POLLOUT), 1);
315 CHECK_INT(socket_is_connected(client), 0);
316 CHECK_INT(errno, ECONNREFUSED);
317 close(client);
318}
319
320/* --------------------------------------------------------- failed binds */
321
322/* The lowest free descriptor is handed out first, so a number that stays put
323 across a failing call shows the call did not keep a socket behind. */
324static int next_descriptor(void) {
325 int fd = dup(0);
326
327 if (fd != -1)
328 close(fd);
329 return fd;
330}
331
332static void case_bind_failure(void) {
333 int before;
334
335 test_case("binding an address no interface carries fails");
336 before = next_descriptor();
337 CHECK(before != -1);
338 CHECK_INT(socket_tcp_listen(ip_unassigned, 0, SOCKET_EXCLUSIVE), -1);
339 CHECK_INT(socket_udp_bind(ip_unassigned, 0, SOCKET_EXCLUSIVE), -1);
340
341 test_case("a failed bind leaves no socket behind");
342 CHECK_INT(next_descriptor(), before);
343}
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
363#ifdef WANT_SYNC_LIVE
364/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs
365 with a single byte, so ask how much was written. */
366static int mcast_option(int s, int option) {
367 int value = 0;
368 socklen_t len = sizeof(value);
369
370 if (getsockopt(s, IPPROTO_IP, option, &value, &len) == -1)
371 return -1;
372 if (len == 1)
373 return *(unsigned char *)&value;
374 return value;
375}
376
377static void case_mcast_sender(void) {
378 int s;
379
380 test_case("the sending socket keeps its traffic on the local network");
381 s = socket_mcast_bind(ip_v4_loopback, 0, 0);
382 CHECK(s != -1);
383 CHECK_INT(mcast_option(s, IP_MULTICAST_TTL), 1);
384
385 test_case("and does not hear itself unless it is asked to");
386 CHECK_INT(mcast_option(s, IP_MULTICAST_LOOP), 0);
387
388 test_case("whoever sends from it is serving clients too, so it cannot block");
389 CHECK_INT(is_nonblocking(s), 1);
390 close(s);
391
392 test_case("the proxy asks to hear itself and gets it");
393 s = socket_mcast_bind(ip_v4_loopback, 0, 1);
394 CHECK(s != -1);
395 CHECK_INT(mcast_option(s, IP_MULTICAST_LOOP), 1);
396 close(s);
397}
398#endif
399
400void test_socket(void) {
401 case_socket_options();
402#ifdef SO_REUSEPORT
403 case_sharing_is_opt_in();
404#endif
405 case_udp_roundtrip();
406 case_a_signal_ends_a_blocking_read();
407 case_udp_v4mapped();
408 case_tcp_roundtrip();
409 case_deferred_accept();
410 case_connect_refused();
411 case_bind_failure();
412 case_a_taken_udp_address_is_noticed();
413#ifdef WANT_SYNC_LIVE
414 case_mcast_sender();
415#endif
416}
diff --git a/tests/t_trackerlogic.c b/tests/t_trackerlogic.c
new file mode 100644
index 0000000..1cf9141
--- /dev/null
+++ b/tests/t_trackerlogic.c
@@ -0,0 +1,241 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <signal.h>
7#include <pthread.h>
8#include <string.h>
9
10/* Opentracker */
11#include "ot_mutex.h"
12#include "trackerlogic.h"
13#include "test.h"
14
15/* The swarm itself: what an announce does to a torrent, and what a scrape
16 says about it afterwards. The counts are read back through the udp scrape
17 because that is the one reply the tracker builds as plain numbers. */
18
19static struct ot_workstruct ws;
20
21static void hash_named(ot_hash hash, const char *name) {
22 memset(hash, 0, sizeof(ot_hash));
23 memcpy(hash, name, strlen(name) < sizeof(ot_hash) ? strlen(name) : sizeof(ot_hash));
24}
25
26/* An IPv4 peer arrives as the v4 mapped form the tracker stores */
27static void peer_v4(ot_peer6 peer, uint8_t last, uint16_t port) {
28 ot_ip6 ip = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 10, 0, 0, 0};
29 uint16_t net_port = htons(port);
30
31 ip[15] = last;
32 memset(peer, 0, sizeof(ot_peer6));
33 OT_SETIP(peer, ip);
34 OT_SETPORT(peer, &net_port);
35 OT_PEERFLAG(peer) = 0;
36}
37
38static void peer_v6(ot_peer6 peer, uint8_t last, uint16_t port) {
39 ot_ip6 ip = {0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
40 uint16_t net_port = htons(port);
41
42 ip[15] = last;
43 memset(peer, 0, sizeof(ot_peer6));
44 OT_SETIP(peer, ip);
45 OT_SETPORT(peer, &net_port);
46 OT_PEERFLAG(peer) = 0;
47}
48
49static void announce(ot_hash *hash, ot_peer6 peer) {
50 ws.hash = hash;
51 memcpy(ws.peer, peer, sizeof(ot_peer6));
52 ws.reply = ws.outbuf;
53 add_peer_to_torrent_and_return_peers(FLAG_TCP, &ws, 50);
54}
55
56/* seeders, downloads completed, leechers */
57static void scrape(ot_hash hash, uint32_t counts[3]) {
58 char reply[12];
59
60 return_udp_scrape_for_torrent(hash, reply);
61 counts[0] = ntohl(((uint32_t *)reply)[0]);
62 counts[1] = ntohl(((uint32_t *)reply)[1]);
63 counts[2] = ntohl(((uint32_t *)reply)[2]);
64}
65
66static void case_an_announce_makes_a_torrent(void) {
67 ot_hash hash;
68 ot_peer6 peer;
69 uint32_t counts[3];
70 size_t before = mutex_get_torrent_count();
71
72 test_case("the first announce for a hash creates its torrent");
73 hash_named(hash, "first-announce");
74 peer_v4(peer, 1, 6881);
75 announce(&hash, peer);
76
77 CHECK_INT((int)(mutex_get_torrent_count() - before), 1);
78 scrape(hash, counts);
79 CHECK_INT((int)counts[2], 1); /* one leecher */
80 CHECK_INT((int)counts[0], 0);
81}
82
83static void case_the_same_peer_twice_is_one_peer(void) {
84 ot_hash hash;
85 ot_peer6 peer;
86 uint32_t counts[3];
87
88 test_case("announcing twice renews a peer rather than adding another");
89 hash_named(hash, "renewing");
90 peer_v4(peer, 2, 6881);
91 announce(&hash, peer);
92 announce(&hash, peer);
93
94 scrape(hash, counts);
95 CHECK_INT((int)counts[2], 1);
96}
97
98static void case_a_port_makes_a_different_peer(void) {
99 ot_hash hash;
100 ot_peer6 peer;
101 uint32_t counts[3];
102
103 test_case("the same address on another port is another peer");
104 hash_named(hash, "two-ports");
105 peer_v4(peer, 3, 6881);
106 announce(&hash, peer);
107 peer_v4(peer, 3, 6882);
108 announce(&hash, peer);
109
110 scrape(hash, counts);
111 CHECK_INT((int)counts[2], 2);
112}
113
114static void case_seeding_is_counted_apart(void) {
115 ot_hash hash;
116 ot_peer6 peer;
117 uint32_t counts[3];
118
119 test_case("a seeder counts as complete, a leecher as incomplete");
120 hash_named(hash, "seed-and-leech");
121 peer_v4(peer, 4, 6881);
122 OT_PEERFLAG(peer) |= PEER_FLAG_SEEDING;
123 announce(&hash, peer);
124 peer_v4(peer, 5, 6881);
125 announce(&hash, peer);
126
127 scrape(hash, counts);
128 CHECK_INT((int)counts[0], 1);
129 CHECK_INT((int)counts[2], 1);
130}
131
132static void case_completion_without_seeding_is_not_believed(void) {
133 ot_hash hash;
134 ot_peer6 peer;
135 uint32_t counts[3];
136
137 test_case("a peer that claims to have completed but is still leeching is not counted");
138 hash_named(hash, "claiming");
139 peer_v4(peer, 6, 6881);
140 OT_PEERFLAG(peer) |= PEER_FLAG_COMPLETED;
141 announce(&hash, peer);
142
143 scrape(hash, counts);
144 CHECK_INT((int)counts[1], 0);
145 CHECK_INT((int)counts[2], 1); /* still a leecher */
146}
147
148static void case_completing_is_counted_once(void) {
149 ot_hash hash;
150 ot_peer6 peer;
151 uint32_t counts[3];
152
153 test_case("a seeder reporting completion is counted once, however often it says so");
154 hash_named(hash, "completing");
155 peer_v4(peer, 7, 6881);
156 OT_PEERFLAG(peer) |= PEER_FLAG_COMPLETED | PEER_FLAG_SEEDING;
157 announce(&hash, peer);
158 announce(&hash, peer);
159 announce(&hash, peer);
160
161 scrape(hash, counts);
162 CHECK_INT((int)counts[1], 1);
163 CHECK_INT((int)counts[0], 1);
164}
165
166static void case_a_peer_can_leave(void) {
167 ot_hash hash;
168 ot_peer6 peer;
169 uint32_t counts[3];
170
171 test_case("a peer that stops is gone from the swarm");
172 hash_named(hash, "leaving");
173 peer_v4(peer, 7, 6881);
174 announce(&hash, peer);
175 peer_v4(peer, 8, 6881);
176 announce(&hash, peer);
177 scrape(hash, counts);
178 CHECK_INT((int)counts[2], 2);
179
180 ws.hash = &hash;
181 memcpy(ws.peer, peer, sizeof(ot_peer6));
182 remove_peer_from_torrent(FLAG_TCP, &ws);
183
184 scrape(hash, counts);
185 CHECK_INT((int)counts[2], 1);
186}
187
188static void case_the_families_are_kept_apart(void) {
189 ot_hash hash;
190 ot_peer6 peer;
191 uint32_t counts[3];
192
193 test_case("a v4 and a v6 peer of one swarm are both counted");
194 hash_named(hash, "dual-stack");
195 peer_v4(peer, 9, 6881);
196 announce(&hash, peer);
197 peer_v6(peer, 9, 6881);
198 announce(&hash, peer);
199
200 scrape(hash, counts);
201 CHECK_INT((int)counts[2], 2);
202}
203
204static void case_a_hash_nobody_announced(void) {
205 ot_hash hash;
206 uint32_t counts[3];
207
208 test_case("a hash nobody has announced scrapes as nothing at all");
209 hash_named(hash, "never-seen");
210 scrape(hash, counts);
211 CHECK_INT((int)counts[0], 0);
212 CHECK_INT((int)counts[1], 0);
213 CHECK_INT((int)counts[2], 0);
214}
215
216void test_trackerlogic(void) {
217 sigset_t signal_mask;
218
219 /* accesslist_init starts a thread that waits for SIGHUP and is stopped by
220 being sent one, so the signal has to be blocked here as the tracker
221 blocks it, or stopping the tracker logic ends this process instead */
222 sigemptyset(&signal_mask);
223 sigaddset(&signal_mask, SIGHUP);
224 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
225
226 trackerlogic_init();
227 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
228
229 case_an_announce_makes_a_torrent();
230 case_the_same_peer_twice_is_one_peer();
231 case_a_port_makes_a_different_peer();
232 case_seeding_is_counted_apart();
233 case_completion_without_seeding_is_not_believed();
234 case_completing_is_counted_once();
235 case_a_peer_can_leave();
236 case_the_families_are_kept_apart();
237 case_a_hash_nobody_announced();
238
239 workstruct_deinit(&ws);
240 trackerlogic_deinit();
241}
diff --git a/tests/t_urlencoded.c b/tests/t_urlencoded.c
new file mode 100644
index 0000000..9935c1c
--- /dev/null
+++ b/tests/t_urlencoded.c
@@ -0,0 +1,363 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <string.h>
6
7/* Opentracker */
8#include "ot_urlencoded.h"
9#include "test.h"
10
11/* The scanner returns the number of bytes written to the destination, or
12 -1 for a parse error and -2 for a hard terminator encountered before any
13 output was produced. It advances the source pointer past the separator it
14 stopped on, except for hard terminators and the '&' ending a parameter,
15 which it leaves for the next call to see. */
16
17static void case_path(void) {
18 char query[] = "/announce?info_hash=A";
19 char dest[64];
20 char *p = query;
21 ssize_t n;
22
23 test_case("path stops at the question mark");
24 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
25 CHECK_INT(n, 9);
26 dest[n] = 0;
27 CHECK_STR(dest, "/announce");
28 CHECK_INT(*p, 'i');
29}
30
31static void case_param_and_value(void) {
32 char query[] = "info_hash=abc&port=80";
33 char dest[64];
34 char *p = query;
35 ssize_t n;
36
37 test_case("parameter stops at '=', value stops at '&'");
38 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
39 CHECK_INT(n, 9);
40 dest[n] = 0;
41 CHECK_STR(dest, "info_hash");
42
43 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
44 CHECK_INT(n, 3);
45 dest[n] = 0;
46 CHECK_STR(dest, "abc");
47
48 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
49 CHECK_INT(n, 4);
50 dest[n] = 0;
51 CHECK_STR(dest, "port");
52
53 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
54 CHECK_INT(n, 2);
55 dest[n] = 0;
56 CHECK_STR(dest, "80");
57}
58
59static void case_percent_decoding(void) {
60 char query[] = "%41%42%43&x=1";
61 char dest[64];
62 char *p = query;
63 ssize_t n;
64
65 test_case("percent escapes decode");
66 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
67 CHECK_INT(n, 3);
68 CHECK_MEM(dest, "ABC", 3);
69}
70
71static void case_binary_info_hash(void) {
72 /* The twenty byte info_hash is what the announce path really decodes */
73 char query[] = "%00%01%02%ff%fe%7f%80ABCDEFGHIJKLM&x=1";
74 unsigned char want[] = {0x00, 0x01, 0x02, 0xff, 0xfe, 0x7f, 0x80, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
75 char dest[64];
76 char *p = query;
77 ssize_t n;
78
79 test_case("twenty byte binary value survives decoding");
80 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
81 CHECK_INT(n, 20);
82 CHECK_MEM(dest, want, 20);
83}
84
85static void case_in_place(void) {
86 char query[] = "%41%42&x=1";
87 char *p = query;
88 ssize_t n;
89
90 test_case("decoding in place over the source is safe");
91 n = urlencoded_parse(&p, query, query + sizeof(query), SCAN_SEARCHPATH_VALUE);
92 CHECK_INT(n, 2);
93 CHECK_MEM(query, "AB", 2);
94}
95
96static void case_bad_escape(void) {
97 char query[] = "%zz";
98 char dest[64];
99 char *p = query;
100 ssize_t n;
101
102 test_case("a non hexadecimal escape is a parse error");
103 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
104 CHECK_INT(n, -1);
105}
106
107static void case_truncated_escape(void) {
108 char query[] = "%4";
109 char dest[64];
110 char *p = query;
111 ssize_t n;
112
113 test_case("an escape cut short by the terminator is a parse error");
114 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
115 CHECK_INT(n, -1);
116}
117
118static void case_terminator(void) {
119 char empty[] = "";
120 char space[] = " rest";
121 char dest[64];
122 char *p = empty;
123 ssize_t n;
124
125 test_case("a hard terminator before any output reports end of input");
126 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
127 CHECK_INT(n, -2);
128
129 p = space;
130 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
131 CHECK_INT(n, -2);
132}
133
134static void case_terminator_after_output(void) {
135 char query[] = "abc";
136 char dest[64];
137 char *p = query;
138 ssize_t n;
139
140 test_case("a hard terminator after output is left for the next call");
141 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
142 CHECK_INT(n, 3);
143 CHECK_INT(*p, 0);
144 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
145 CHECK_INT(n, -2);
146}
147
148/* The character matrix makes '?' terminate a path only, and '=' terminate a
149 path or a parameter only. Both are ordinary characters inside a value, so a
150 value is free to contain a nested query string. */
151
152static void case_separators_are_contextual(void) {
153 char question[] = "a?b&x=1";
154 char equals[] = "a=b&x=1";
155 char dest[64];
156 char *p = question;
157 ssize_t n;
158
159 test_case("a question mark is literal inside a value");
160 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
161 CHECK_INT(n, 3);
162 dest[n] = 0;
163 CHECK_STR(dest, "a?b");
164
165 test_case("an equals sign is literal inside a value");
166 p = equals;
167 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
168 CHECK_INT(n, 3);
169 dest[n] = 0;
170 CHECK_STR(dest, "a=b");
171}
172
173static void case_ampersand_in_path(void) {
174 char query[] = "/path&x";
175 char dest[64];
176 char *p = query;
177 ssize_t n;
178
179 test_case("an ampersand in a path is a parse error");
180 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
181 CHECK_INT(n, -1);
182}
183
184static void case_raw_high_byte(void) {
185 char query[] = {'a', 'b', (char)0x80, 0};
186 char dest[64];
187 char *p = query;
188 ssize_t n;
189
190 test_case("an undecoded byte above ASCII is a parse error");
191 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
192 CHECK_INT(n, -1);
193}
194
195static void case_skipvalue(void) {
196 char query[] = "abc&next=1";
197 char bare[] = "abc";
198 char *p = query;
199
200 test_case("skipvalue steps over the value and its separator");
201 urlencoded_skip_value(&p);
202 CHECK_STR(p, "next=1");
203
204 test_case("skipvalue leaves a hard terminator in place");
205 p = bare;
206 urlencoded_skip_value(&p);
207 CHECK_INT(*p, 0);
208}
209
210static void case_find_keywords(void) {
211 static const ot_keywords keywords[] = {{"port", 1}, {"left", 2}, {"compact", 3}, {NULL, -3}};
212 char match[] = "left=0";
213 char nomatch[] = "bogus=1";
214 char prefix[] = "por=1";
215 char *p = match;
216
217 test_case("a known keyword returns its value");
218 CHECK_INT(urlencoded_match_keyword(keywords, &p, match + sizeof(match), SCAN_SEARCHPATH_PARAM), 2);
219
220 test_case("an unknown keyword returns -3");
221 p = nomatch;
222 CHECK_INT(urlencoded_match_keyword(keywords, &p, nomatch + sizeof(nomatch), SCAN_SEARCHPATH_PARAM), -3);
223
224 test_case("a prefix of a keyword does not match it");
225 p = prefix;
226 CHECK_INT(urlencoded_match_keyword(keywords, &p, prefix + sizeof(prefix), SCAN_SEARCHPATH_PARAM), -3);
227}
228
229/* The encoding direction. Which bytes survive unescaped is fixed by what
230 existing parsers of the urlencoded full scrape expect, so these cases pin
231 the set rather than describe a preference. */
232
233static void case_fmt_passes_safe_bytes(void) {
234 const uint8_t src[] = "aZ09$-./=_~";
235 char dest[64];
236 size_t n;
237
238 test_case("alphanumerics and the safe punctuation pass through");
239 n = urlencoded_format(dest, src, 11);
240 dest[n] = 0;
241 CHECK_INT(n, 11);
242 CHECK_STR(dest, "aZ09$-./=_~");
243}
244
245static void case_fmt_escapes_the_rest(void) {
246 const uint8_t src[] = {' ', '%', '&', '+', ':', '?'};
247 char dest[64];
248 size_t n;
249
250 test_case("everything else becomes a percent escape");
251 n = urlencoded_format(dest, src, sizeof(src));
252 dest[n] = 0;
253 CHECK_INT(n, 18);
254 CHECK_STR(dest, "%20%25%26%2b%3a%3f");
255}
256
257static void case_fmt_hex_is_lower_case(void) {
258 const uint8_t src[] = {0x00, 0xab, 0xff};
259 char dest[64];
260 size_t n;
261
262 test_case("escapes use lower case hex digits");
263 n = urlencoded_format(dest, src, sizeof(src));
264 dest[n] = 0;
265 CHECK_INT(n, 9);
266 CHECK_STR(dest, "%00%ab%ff");
267}
268
269static void case_fmt_zero_length(void) {
270 char dest[4];
271
272 test_case("a zero length input writes nothing");
273 memset(dest, 0x5a, sizeof(dest));
274 CHECK_INT(urlencoded_format(dest, (const uint8_t *)"abc", 0), 0);
275 CHECK_MEM(dest, "\x5a\x5a\x5a\x5a", 4);
276}
277
278static void case_fmt_worst_case_fits(void) {
279 uint8_t src[20];
280 char dest[61];
281 size_t i, n;
282
283 test_case("a hash of entirely unsafe bytes needs three times its length");
284 for (i = 0; i < sizeof(src); ++i)
285 src[i] = 0xff;
286 n = urlencoded_format(dest, src, sizeof(src));
287 dest[n] = 0;
288 CHECK_INT(n, 60);
289 for (i = 0; i < 20; ++i)
290 if (memcmp(dest + 3 * i, "%ff", 3)) {
291 test_failf(__FILE__, __LINE__, "escape %zu is wrong", i);
292 return;
293 }
294 ++test_checks;
295}
296
297static void case_fmt_decoder_disagrees_on_dollar(void) {
298 /* Documenting a known asymmetry rather than a wish. Of the bytes the
299 encoder passes through unescaped, '$' is the only one the decoder then
300 refuses, and it refuses the whole string rather than stopping short.
301 Output of the urlencoded full scrape therefore does not round trip
302 through urlencoded_parse when a hash contains 0x24. Harmless today
303 because only third party tooling reads that output. */
304 const uint8_t src[] = {'a', '$', 'b'};
305 char dest[16];
306 char scanned[16];
307 char *p = dest;
308 size_t n;
309 ssize_t got;
310
311 test_case("the encoder passes '$' but the decoder rejects it");
312 n = urlencoded_format(dest, src, sizeof(src));
313 dest[n] = 0;
314 CHECK_STR(dest, "a$b");
315
316 got = urlencoded_parse(&p, scanned, scanned + sizeof(scanned), SCAN_SEARCHPATH_VALUE);
317 CHECK_INT(got, -1);
318}
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
340void test_urlencoded(void) {
341 case_path();
342 case_param_and_value();
343 case_percent_decoding();
344 case_binary_info_hash();
345 case_in_place();
346 case_bad_escape();
347 case_truncated_escape();
348 case_terminator();
349 case_terminator_after_output();
350 case_separators_are_contextual();
351 case_ampersand_in_path();
352 case_raw_high_byte();
353 case_skipvalue();
354 case_find_keywords();
355 case_value_stops_at_dest_end();
356 case_keyword_with_decoded_nul_does_not_match();
357 case_fmt_passes_safe_bytes();
358 case_fmt_escapes_the_rest();
359 case_fmt_hex_is_lower_case();
360 case_fmt_zero_length();
361 case_fmt_worst_case_fits();
362 case_fmt_decoder_disagrees_on_dollar();
363}
diff --git a/tests/t_vector.c b/tests/t_vector.c
new file mode 100644
index 0000000..42ce31a
--- /dev/null
+++ b/tests/t_vector.c
@@ -0,0 +1,308 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <stdlib.h>
7#include <string.h>
8
9/* Opentracker */
10#include "ot_vector.h"
11#include "trackerlogic.h"
12#include "test.h"
13
14/* vector_binary_search returns the matching member when there is one, and otherwise
15 the position at which the key would have to be inserted to keep the vector
16 sorted. exactmatch distinguishes the two. */
17
18static const unsigned char sorted[5][4] = {{0, 0, 0, 1}, {0, 0, 0, 3}, {0, 0, 0, 5}, {0, 0, 0, 7}, {0, 0, 0, 9}};
19
20static void case_search_finds_member(void) {
21 const unsigned char key[4] = {0, 0, 0, 5};
22 int exactmatch;
23 void *found;
24
25 test_case("an existing key is found");
26 found = vector_binary_search(key, sorted, 5, 4, 4, &exactmatch);
27 CHECK(exactmatch != 0);
28 CHECK_PTR(found, sorted[2]);
29}
30
31static void case_search_finds_first_and_last(void) {
32 const unsigned char first[4] = {0, 0, 0, 1};
33 const unsigned char last[4] = {0, 0, 0, 9};
34 int exactmatch;
35
36 test_case("the first and last members are found");
37 CHECK_PTR(vector_binary_search(first, sorted, 5, 4, 4, &exactmatch), sorted[0]);
38 CHECK(exactmatch != 0);
39 CHECK_PTR(vector_binary_search(last, sorted, 5, 4, 4, &exactmatch), sorted[4]);
40 CHECK(exactmatch != 0);
41}
42
43static void case_search_insert_position(void) {
44 const unsigned char middle[4] = {0, 0, 0, 4};
45 const unsigned char before[4] = {0, 0, 0, 0};
46 int exactmatch;
47 void *slot;
48
49 test_case("a missing key yields its insert position");
50 slot = vector_binary_search(middle, sorted, 5, 4, 4, &exactmatch);
51 CHECK_INT(exactmatch, 0);
52 CHECK_PTR(slot, sorted[2]);
53
54 slot = vector_binary_search(before, sorted, 5, 4, 4, &exactmatch);
55 CHECK_INT(exactmatch, 0);
56 CHECK_PTR(slot, sorted[0]);
57}
58
59static void case_search_past_the_end(void) {
60 const unsigned char beyond[4] = {0, 0, 0, 0xff};
61 int exactmatch;
62 void *slot;
63
64 test_case("a key above every member yields the position past the end");
65 slot = vector_binary_search(beyond, sorted, 5, 4, 4, &exactmatch);
66 CHECK_INT(exactmatch, 0);
67 CHECK_PTR(slot, sorted[5]);
68}
69
70static void case_search_empty(void) {
71 int exactmatch;
72 void *base = (void *)sorted;
73
74 test_case("searching an empty vector reports no match at the base");
75 CHECK_PTR(vector_binary_search(sorted[0], base, 0, 4, 4, &exactmatch), base);
76 CHECK_INT(exactmatch, 0);
77}
78
79static void case_insert_keeps_order(void) {
80 ot_vector vector = {NULL, 0, 0};
81 const unsigned char five[4] = {0, 0, 0, 5};
82 const unsigned char one[4] = {0, 0, 0, 1};
83 const unsigned char nine[4] = {0, 0, 0, 9};
84 int exactmatch;
85 void *slot;
86
87 test_case("inserts land in sorted order and grow the vector");
88 slot = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
89 CHECK(slot != NULL);
90 CHECK_INT(exactmatch, 0);
91 memcpy(slot, five, 4);
92 CHECK_INT(vector.size, 1);
93 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS);
94
95 slot = vector_find_or_insert(&vector, (void *)one, 4, 4, &exactmatch);
96 CHECK(slot != NULL);
97 CHECK_INT(exactmatch, 0);
98 memcpy(slot, one, 4);
99 CHECK_INT(vector.size, 2);
100
101 slot = vector_find_or_insert(&vector, (void *)nine, 4, 4, &exactmatch);
102 CHECK(slot != NULL);
103 CHECK_INT(exactmatch, 0);
104 memcpy(slot, nine, 4);
105 CHECK_INT(vector.size, 3);
106 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS * OT_VECTOR_GROW_RATIO);
107
108 CHECK_MEM(vector.data, "\0\0\0\1\0\0\0\5\0\0\0\11", 12);
109
110 free(vector.data);
111}
112
113/* The peer variant is reached with an empty vector on every first announce
114 for a torrent, and again whenever a swarm empties and refills, because
115 vector_fixup_peers drops the allocation and nulls the data pointer. */
116
117static void case_insert_peer_into_empty_vector(void) {
118 ot_vector vector = {NULL, 0, 0};
119 ot_peer6 low, high;
120 int exactmatch;
121 ot_peer *slot;
122
123 memset(low, 0x11, sizeof(low));
124 memset(high, 0x99, sizeof(high));
125
126 test_case("the first peer goes into a vector that has no allocation yet");
127 slot = vector_find_or_insert_peer(&vector, low, OT_PEER_SIZE6, &exactmatch);
128 CHECK(slot != NULL);
129 CHECK_INT(exactmatch, 0);
130 memcpy(slot, low, OT_PEER_SIZE6);
131 CHECK_INT(vector.size, 1);
132 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS);
133 CHECK_PTR(slot, vector.data);
134
135 test_case("a second peer keeps the order");
136 slot = vector_find_or_insert_peer(&vector, high, OT_PEER_SIZE6, &exactmatch);
137 CHECK(slot != NULL);
138 CHECK_INT(exactmatch, 0);
139 memcpy(slot, high, OT_PEER_SIZE6);
140 CHECK_INT(vector.size, 2);
141 CHECK_MEM((char *)vector.data, low, OT_PEER_COMPARE_SIZE6);
142 CHECK_MEM((char *)vector.data + OT_PEER_SIZE6, high, OT_PEER_COMPARE_SIZE6);
143
144 test_case("and emptying the vector hands the allocation back");
145 CHECK(vector_remove_peer(&vector, low, OT_PEER_SIZE6) != 0);
146 CHECK(vector_remove_peer(&vector, high, OT_PEER_SIZE6) != 0);
147 CHECK_INT(vector.size, 0);
148 CHECK_PTR(vector.data, NULL);
149
150 test_case("so the next peer starts from no allocation again");
151 slot = vector_find_or_insert_peer(&vector, low, OT_PEER_SIZE6, &exactmatch);
152 CHECK(slot != NULL);
153 CHECK_INT(vector.size, 1);
154
155 free(vector.data);
156}
157
158static void case_insert_finds_existing(void) {
159 ot_vector vector = {NULL, 0, 0};
160 const unsigned char five[4] = {0, 0, 0, 5};
161 int exactmatch;
162 void *slot, *again;
163
164 test_case("a second insert of the same key returns the existing member");
165 slot = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
166 CHECK(slot != NULL);
167 memcpy(slot, five, 4);
168
169 again = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
170 CHECK(exactmatch != 0);
171 CHECK_PTR(again, vector.data);
172 CHECK_INT(vector.size, 1);
173
174 free(vector.data);
175}
176
177static void case_insert_compare_prefix(void) {
178 ot_vector vector = {NULL, 0, 0};
179 unsigned char first[6] = {1, 2, 3, 0xaa, 0xaa, 0xaa};
180 unsigned char second[6] = {1, 2, 3, 0xbb, 0xbb, 0xbb};
181 int exactmatch;
182 void *slot;
183
184 test_case("only the compare prefix decides identity");
185 slot = vector_find_or_insert(&vector, first, 6, 3, &exactmatch);
186 CHECK(slot != NULL);
187 memcpy(slot, first, 6);
188
189 slot = vector_find_or_insert(&vector, second, 6, 3, &exactmatch);
190 CHECK(exactmatch != 0);
191 CHECK_INT(vector.size, 1);
192 CHECK_MEM(slot, first, 6);
193
194 free(vector.data);
195}
196
197/* ------------------------------------------------- bucket redistribution */
198
199/* A flat peer list of count distinct v4 peers. The low byte of the index goes
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
202 sorted whether or not vector_redistribute_buckets sorted it. */
203static void build_flat_vector(ot_vector *peers, size_t count) {
204 size_t i;
205
206 memset(peers, 0, sizeof(*peers));
207 peers->data = malloc(count * OT_PEER_SIZE4);
208 peers->size = count;
209 peers->space = count;
210
211 for (i = 0; i < count; ++i) {
212 uint8_t *peer = (uint8_t *)peers->data + i * OT_PEER_SIZE4;
213
214 memset(peer, 0, OT_PEER_SIZE4);
215 peer[0] = (uint8_t)i;
216 peer[1] = (uint8_t)(i >> 8);
217 peer[2] = (uint8_t)(i >> 16);
218 peer[3] = 1;
219 }
220}
221
222static void case_redistribute_holds_every_peer(void) {
223 const size_t count = 513;
224 ot_vector peers;
225 size_t bucket, total_size = 0, empty = 0, largest = 0;
226 ot_vector *buckets;
227
228 test_case("a peer list past the threshold is split into buckets");
229 build_flat_vector(&peers, count);
230 CHECK(peers.data != NULL);
231 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
232 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
233 CHECK_INT(peers.size, 16);
234
235 buckets = peers.data;
236 for (bucket = 0; bucket < peers.size; ++bucket) {
237 total_size += buckets[bucket].size;
238 if (!buckets[bucket].size)
239 ++empty;
240 if (buckets[bucket].size > largest)
241 largest = buckets[bucket].size;
242 }
243
244 test_case("no peer is lost on the way");
245 CHECK_INT(total_size, count);
246
247 /* The point of the exercise is that a lookup only searches one bucket, so
248 a hash that piled everything into one would defeat it. The input and the
249 hash are both fixed, so this is not a matter of luck. */
250 test_case("and they are spread over the buckets rather than piled up");
251 CHECK_INT(empty, 0);
252 CHECK(largest < count / 2);
253
254 vector_clean_list(peers.data, peers.size);
255}
256
257static void case_redistribute_sorts_each_bucket(void) {
258 const size_t count = 1000;
259 ot_vector peers;
260 size_t bucket, i, out_of_order = 0;
261 ot_vector *buckets;
262
263 test_case("every bucket comes back sorted, so bsearch can be used on it");
264 build_flat_vector(&peers, count);
265 CHECK(peers.data != NULL);
266 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
267 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
268
269 buckets = peers.data;
270 for (bucket = 0; bucket < peers.size; ++bucket)
271 for (i = 1; i < buckets[bucket].size; ++i) {
272 const uint8_t *prev = (uint8_t *)buckets[bucket].data + (i - 1) * OT_PEER_SIZE4;
273 const uint8_t *next = (uint8_t *)buckets[bucket].data + i * OT_PEER_SIZE4;
274
275 if (memcmp(prev, next, OT_PEER_COMPARE_SIZE4) >= 0)
276 ++out_of_order;
277 }
278 CHECK_INT(out_of_order, 0);
279
280 vector_clean_list(peers.data, peers.size);
281}
282
283static void case_redistribute_below_threshold(void) {
284 ot_vector peers;
285
286 test_case("a small peer list is left flat");
287 build_flat_vector(&peers, 100);
288 CHECK(peers.data != NULL);
289 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, 100);
290 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 0);
291 CHECK_INT(peers.size, 100);
292 free(peers.data);
293}
294
295void test_vector(void) {
296 case_search_finds_member();
297 case_search_finds_first_and_last();
298 case_search_insert_position();
299 case_search_past_the_end();
300 case_search_empty();
301 case_insert_keeps_order();
302 case_insert_peer_into_empty_vector();
303 case_insert_finds_existing();
304 case_insert_compare_prefix();
305 case_redistribute_holds_every_peer();
306 case_redistribute_sorts_each_bucket();
307 case_redistribute_below_threshold();
308}
diff --git a/tests/t_workqueue.c b/tests/t_workqueue.c
new file mode 100644
index 0000000..660d882
--- /dev/null
+++ b/tests/t_workqueue.c
@@ -0,0 +1,157 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_fdstate.h"
10#include "ot_workqueue.h"
11#include "test.h"
12
13/* A worker asks for a class of task and blocks until one turns up, so a task
14 whose class matches no worker is never claimed and whoever is waiting for
15 its answer waits forever. These cases pin the matching. */
16
17static void case_task_goes_to_its_own_class(void) {
18 ot_tasktype asked;
19 ot_taskid taskid;
20
21 test_case("a worker is handed the task of the class it asked for");
22 CHECK_INT(workqueue_pushtask(41, TASK_FULLSCRAPE_TPB_ASCII), 0);
23 asked = TASK_FULLSCRAPE;
24 taskid = workqueue_poptask(&asked);
25 CHECK(taskid != 0);
26
27 test_case("and the full task type, not just its class");
28 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_ASCII);
29 workqueue_canceltask(41);
30}
31
32static void case_flags_survive_the_queue(void) {
33 ot_tasktype asked;
34
35 test_case("flags outside the class mask are carried through");
36 CHECK_INT(workqueue_pushtask(42, TASK_FULLSCRAPE_TPB_URLENCODED | TASK_FLAG_GZIP), 0);
37 asked = TASK_FULLSCRAPE;
38 CHECK(workqueue_poptask(&asked) != 0);
39 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_URLENCODED | TASK_FLAG_GZIP);
40 workqueue_canceltask(42);
41}
42
43static void case_classes_do_not_cross(void) {
44 ot_tasktype asked;
45 ot_taskid taskid;
46
47 test_case("a stats worker passes over a fullscrape task");
48 CHECK_INT(workqueue_pushtask(43, TASK_FULLSCRAPE_TPB_BINARY), 0);
49 CHECK_INT(workqueue_pushtask(44, TASK_STATS_PEERS), 0);
50
51 asked = TASK_STATS;
52 taskid = workqueue_poptask(&asked);
53 CHECK(taskid != 0);
54 CHECK_INT(asked, TASK_STATS_PEERS);
55
56 test_case("and leaves it for the one that wants it");
57 asked = TASK_FULLSCRAPE;
58 taskid = workqueue_poptask(&asked);
59 CHECK(taskid != 0);
60 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_BINARY);
61
62 workqueue_canceltask(43);
63 workqueue_canceltask(44);
64}
65
66static void case_every_task_gets_its_own_id(void) {
67 ot_tasktype asked;
68 ot_taskid first, second;
69
70 test_case("two queued tasks are handed out under different ids");
71 CHECK_INT(workqueue_pushtask(45, TASK_FULLSCRAPE), 0);
72 CHECK_INT(workqueue_pushtask(46, TASK_FULLSCRAPE), 0);
73
74 asked = TASK_FULLSCRAPE;
75 first = workqueue_poptask(&asked);
76 asked = TASK_FULLSCRAPE;
77 second = workqueue_poptask(&asked);
78 CHECK(first != 0);
79 CHECK(second != 0);
80 CHECK(first != second);
81
82 workqueue_canceltask(45);
83 workqueue_canceltask(46);
84}
85
86static void case_cancelled_task_is_not_handed_out(void) {
87 ot_tasktype asked;
88
89 test_case("a cancelled task is gone before any worker sees it");
90 CHECK_INT(workqueue_pushtask(47, TASK_FULLSCRAPE_TPB_ASCII_PLUS), 0);
91 CHECK_INT(workqueue_pushtask(48, TASK_FULLSCRAPE), 0);
92 workqueue_canceltask(47);
93
94 asked = TASK_FULLSCRAPE;
95 CHECK(workqueue_poptask(&asked) != 0);
96 CHECK_INT(asked, TASK_FULLSCRAPE);
97 workqueue_canceltask(48);
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
149void test_workqueue(void) {
150 case_task_goes_to_its_own_class();
151 case_flags_survive_the_queue();
152 case_classes_do_not_cross();
153 case_every_task_gets_its_own_id();
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();
157}
diff --git a/tests/test.c b/tests/test.c
new file mode 100644
index 0000000..33f77bd
--- /dev/null
+++ b/tests/test.c
@@ -0,0 +1,56 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdarg.h>
6#include <stdio.h>
7
8/* Opentracker */
9#include "test.h"
10
11unsigned long test_checks;
12unsigned long test_failures;
13
14static const char *current_module = "";
15static const char *current_case = "";
16
17void test_module(const char *name) {
18 current_module = name;
19 current_case = "";
20 printf("%s\n", name);
21}
22
23void test_case(const char *name) { current_case = name; }
24
25static void test_where(const char *file, int line) {
26 ++test_failures;
27 printf(" FAIL %s/%s (%s:%d)\n ", current_module, current_case, file, line);
28}
29
30void test_failf(const char *file, int line, const char *fmt, ...) {
31 va_list ap;
32 test_where(file, line);
33 va_start(ap, fmt);
34 vprintf(fmt, ap);
35 va_end(ap);
36 printf("\n");
37}
38
39void test_failmem(const char *file, int line, const char *what, const void *got, const void *want, size_t len) {
40 const unsigned char *g = got, *w = want;
41 size_t i;
42
43 test_where(file, line);
44 printf("%s: %zu bytes differ\n got ", what, len);
45 for (i = 0; i < len; ++i)
46 printf("%02x", g[i]);
47 printf("\n want ");
48 for (i = 0; i < len; ++i)
49 printf("%02x", w[i]);
50 printf("\n");
51}
52
53int test_summary(void) {
54 printf("\n%lu checks, %lu failures\n", test_checks, test_failures);
55 return test_failures != 0;
56}
diff --git a/tests/test.h b/tests/test.h
new file mode 100644
index 0000000..9b569c7
--- /dev/null
+++ b/tests/test.h
@@ -0,0 +1,96 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_TEST_H__
5#define OT_TEST_H__
6
7#include <stddef.h>
8#include <string.h>
9
10/* Minimal scaffolding for opentracker's unit tests. No external dependencies.
11
12 Tests are grouped into modules, one per source file under test. A module is
13 a list of small case functions, each pinning one behaviour. A failing CHECK
14 reports file, line and the offending values, then returns from the case it
15 is in, so a single run reports as many independent problems as it can.
16 Because the macros return, they may only be used in functions returning
17 void. */
18
19void test_module(const char *name);
20void test_case(const char *name);
21void test_failf(const char *file, int line, const char *fmt, ...);
22void test_failmem(const char *file, int line, const char *what, const void *got, const void *want, size_t len);
23int test_summary(void);
24
25extern unsigned long test_checks;
26extern unsigned long test_failures;
27
28#define CHECK(cond) \
29 do { \
30 ++test_checks; \
31 if (!(cond)) { \
32 test_failf(__FILE__, __LINE__, "expected %s", #cond); \
33 return; \
34 } \
35 } while (0)
36
37#define CHECK_INT(got, want) \
38 do { \
39 long long got_ = (long long)(got), want_ = (long long)(want); \
40 ++test_checks; \
41 if (got_ != want_) { \
42 test_failf(__FILE__, __LINE__, "%s: got %lld, want %lld", #got, got_, want_); \
43 return; \
44 } \
45 } while (0)
46
47#define CHECK_PTR(got, want) \
48 do { \
49 const void *got_ = (const void *)(got), *want_ = (const void *)(want); \
50 ++test_checks; \
51 if (got_ != want_) { \
52 test_failf(__FILE__, __LINE__, "%s: got %p, want %p", #got, got_, want_); \
53 return; \
54 } \
55 } while (0)
56
57#define CHECK_MEM(got, want, len) \
58 do { \
59 ++test_checks; \
60 if (memcmp((got), (want), (len))) { \
61 test_failmem(__FILE__, __LINE__, #got, (got), (want), (len)); \
62 return; \
63 } \
64 } while (0)
65
66#define CHECK_STR(got, want) \
67 do { \
68 const char *got_ = (got), *want_ = (want); \
69 ++test_checks; \
70 if (strcmp(got_, want_)) { \
71 test_failf(__FILE__, __LINE__, "%s: got \"%s\", want \"%s\"", #got, got_, want_); \
72 return; \
73 } \
74 } while (0)
75
76/* One entry point per module under test */
77void test_urlencoded(void);
78void test_iovec(void);
79void test_vector(void);
80void test_random(void);
81void test_hex(void);
82void test_accesslist(void);
83void test_scan(void);
84void test_buf(void);
85void test_ip(void);
86void test_socket(void);
87void test_mutex(void);
88void test_trackerlogic(void);
89void test_clean(void);
90void test_workqueue(void);
91void test_batch(void);
92void test_fdstate(void);
93void test_event(void);
94void test_fmt(void);
95
96#endif
diff --git a/tests/testsuite2.sh b/tests/testsuite2.sh
index c9a5a6a..da5181b 100644
--- a/tests/testsuite2.sh
+++ b/tests/testsuite2.sh
@@ -2,13 +2,21 @@
2 2
3while true; do 3while true; do
4 request_string="GET /announce?info_hash=012345678901234567\ 4 request_string="GET /announce?info_hash=012345678901234567\
5%$(printf %02X $(( $RANDOM & 0xff )) )\ 5$(printf %02X $(( $RANDOM & 0xff )) )\
6%$(printf %02X $(( $RANDOM & 0xff )) )\ 6&ip=$(( $RANDOM & 0xff )).17.13.15&port=$(( $RANDOM & 0xff )) HTTP/1.0"
7&ip=$(( $RANDOM & 0xff )).17.13.15&port=$(( $RANDOM & 0xff )) HTTP/1.0\n"
8 7
9 echo $request_string 8# echo $request_string
10 echo 9# echo
11 echo $request_string | nc 23.23.23.237 6969 >/dev/null 10 printf "%s\n\n" "$request_string" | nc 84.200.61.9 6969 | hexdump -C
12 echo 11
12 request_string="GET /announce?info_hash=012345678901234567\
13$(printf %02X $(( $RANDOM & 0xff )) )\
14&ip=2001:1608:6:27::$(( $RANDOM & 0xff ))&port=$(( $RANDOM & 0xff )) HTTP/1.0"
15 printf "%s\n\n" "$request_string" | nc 2001:1608:6:27::9 6969 | hexdump -C
16 printf "%s\n\n" "$request_string"
17
18 request_string="GET /scrape?info_hash=012345678901234567\
19$(printf %02X $(( $RANDOM & 0xff )) ) HTTP/1.0"
20 printf "%s\n\n" "$request_string" | nc 2001:1608:6:27::9 6969 | hexdump -C
13 21
14done 22done
diff --git a/tests/udp_load.c b/tests/udp_load.c
new file mode 100644
index 0000000..d86c157
--- /dev/null
+++ b/tests/udp_load.c
@@ -0,0 +1,202 @@
1/* A UDP load generator speaking the tracker's own protocol.
2
3 Each thread keeps a socket of its own, does the BEP 15 connect handshake
4 once and then announces in a loop, counting replies. Separate sockets
5 matter: the kernel spreads datagrams across a SO_REUSEPORT group by a hash
6 of the four tuple, so a generator sending everything from one source port
7 would pile every packet onto one of the tracker's workers and measure the
8 wrong thing.
9
10 cc -O2 -pthread -o udp_load tests/udp_load.c
11 ./udp_load 127.0.0.1 6969 4 5 10000 64
12
13 The last argument is how many announces each thread keeps in flight. With
14 one, a thread sends and waits, so the offered load is threads divided by
15 the round trip and the figure says more about scheduling than about the
16 tracker: measured here, a tracker answering 60k/s that way was using
17 three quarters of one core. Raising the window offers load without
18 needing a thread per outstanding request, which is what lets the tracker
19 be pushed to the point where it is actually the limit.
20
21 The last argument is how many distinct torrents to announce. It is what
22 keeps the figure honest: a fresh info hash every time measures how fast
23 the tracker can insert a million torrents into sorted vectors, which is
24 not what a tracker spends its life doing, and which punishes whichever
25 configuration is quickest because it reaches the expensive end of the run
26 soonest. Cycling a fixed set reaches a steady state where almost every
27 announce renews a peer that is already there. */
28
29#include <arpa/inet.h>
30#include <netinet/in.h>
31#include <pthread.h>
32#include <stdatomic.h>
33#include <stdint.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <sys/socket.h>
38#include <sys/time.h>
39#include <time.h>
40#include <unistd.h>
41
42#define CONNECT_MAGIC 0x41727101980ULL
43
44static struct sockaddr_in g_tracker;
45static long g_torrents = 10000;
46static long g_window = 64;
47static _Atomic long long g_sent = 0;
48static _Atomic int g_running = 1;
49static _Atomic long long g_replies = 0;
50static _Atomic long long g_timeouts = 0;
51
52static double seconds(void) {
53 struct timespec now;
54 clock_gettime(CLOCK_MONOTONIC, &now);
55 return now.tv_sec + now.tv_nsec / 1e9;
56}
57
58static void put64(unsigned char *at, uint64_t value) {
59 int i;
60 for (i = 0; i < 8; ++i)
61 at[i] = (unsigned char)(value >> (56 - 8 * i));
62}
63static void put32(unsigned char *at, uint32_t value) {
64 at[0] = (unsigned char)(value >> 24);
65 at[1] = (unsigned char)(value >> 16);
66 at[2] = (unsigned char)(value >> 8);
67 at[3] = (unsigned char)value;
68}
69static uint64_t get64(const unsigned char *at) {
70 uint64_t value = 0;
71 int i;
72 for (i = 0; i < 8; ++i)
73 value = (value << 8) | at[i];
74 return value;
75}
76
77static void *loader(void *args) {
78 long index = (long)args;
79 unsigned char request[98], reply[1500];
80 uint64_t connection_id = 0;
81 int sock = socket(AF_INET, SOCK_DGRAM, 0);
82 struct timeval patience = {0, 50000}; /* 50 ms */
83 unsigned seed = (unsigned)index * 2654435761u + 1;
84
85 if (sock < 0)
86 return NULL;
87 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &patience, sizeof(patience));
88
89 /* connect handshake */
90 memset(request, 0, sizeof(request));
91 put64(request, CONNECT_MAGIC);
92 put32(request + 8, 0);
93 put32(request + 12, (uint32_t)index);
94 if (sendto(sock, request, 16, 0, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) != 16) {
95 close(sock);
96 return NULL;
97 }
98 if (recvfrom(sock, reply, sizeof(reply), 0, NULL, NULL) < 16) {
99 fprintf(stderr, " thread %ld: no answer to connect\n", index);
100 close(sock);
101 return NULL;
102 }
103 connection_id = get64(reply + 8);
104
105 /* Keep g_window announces outstanding: send that many, then drain what has
106 come back, rather than waiting for each reply in turn */
107 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
108 ssize_t got;
109 int i;
110 long outstanding;
111
112 for (outstanding = 0; outstanding < g_window; ++outstanding) {
113 memset(request, 0, sizeof(request));
114 put64(request, connection_id);
115 put32(request + 8, 1); /* announce */
116 put32(request + 12, (uint32_t)index);
117 /* One of a fixed set, so that after the first pass almost every announce
118 renews a peer rather than creating a torrent. The index is hashed into
119 all twenty bytes so the buckets, which key off the first four, are
120 spread rather than walked in order. */
121 {
122 unsigned which = (unsigned)((seed = seed * 1103515245u + 12345u) >> 8) % (unsigned)g_torrents;
123 unsigned spread;
124 for (i = 0; i < 20; ++i) {
125 spread = which * 2654435761u + (unsigned)i * 40503u;
126 spread ^= spread >> 13;
127 request[16 + i] = (unsigned char)(spread >> 11);
128 }
129 }
130 for (i = 0; i < 20; ++i)
131 request[36 + i] = (unsigned char)('a' + (i % 26));
132 put64(request + 56, 0); /* downloaded */
133 put64(request + 64, 0); /* left: a seeder */
134 put64(request + 72, 0); /* uploaded */
135 put32(request + 80, 0); /* event */
136 put32(request + 84, 0); /* ip */
137 put32(request + 88, (uint32_t)index); /* key */
138 put32(request + 92, (uint32_t)-1); /* num_want */
139 /* A port of this thread's own, so each thread is a distinct peer and the
140 swarms hold more than one */
141 request[96] = (unsigned char)((6881 + index) >> 8);
142 request[97] = (unsigned char)((6881 + index) & 0xff);
143
144 if (sendto(sock, request, 98, 0, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) != 98)
145 break;
146 atomic_fetch_add_explicit(&g_sent, 1, memory_order_relaxed);
147 }
148
149 for (outstanding = 0; outstanding < g_window; ++outstanding) {
150 got = recvfrom(sock, reply, sizeof(reply), 0, NULL, NULL);
151 if (got >= 20)
152 atomic_fetch_add_explicit(&g_replies, 1, memory_order_relaxed);
153 else {
154 atomic_fetch_add_explicit(&g_timeouts, 1, memory_order_relaxed);
155 break; /* nothing more is coming; go round and send again */
156 }
157 }
158 }
159
160 close(sock);
161 return NULL;
162}
163
164int main(int argc, char **argv) {
165 const char *host = argc > 1 ? argv[1] : "127.0.0.1";
166 int port = argc > 2 ? atoi(argv[2]) : 6969;
167 long threads = argc > 3 ? atol(argv[3]) : 16;
168 double run_for = argc > 4 ? atof(argv[4]) : 5.0;
169 long torrents = argc > 5 ? atol(argv[5]) : 10000;
170 long window = argc > 6 ? atol(argv[6]) : 64;
171 pthread_t *ids = calloc((size_t)threads, sizeof(pthread_t));
172 long i;
173 double started, elapsed;
174
175 g_torrents = torrents > 0 ? torrents : 1;
176 g_window = window > 0 ? window : 1;
177
178 memset(&g_tracker, 0, sizeof(g_tracker));
179 g_tracker.sin_family = AF_INET;
180 g_tracker.sin_port = htons((uint16_t)port);
181 if (inet_pton(AF_INET, host, &g_tracker.sin_addr) != 1) {
182 fprintf(stderr, "cannot parse address %s\n", host);
183 return 1;
184 }
185
186 for (i = 0; i < threads; ++i)
187 pthread_create(ids + i, NULL, loader, (void *)i);
188
189 started = seconds();
190 usleep((useconds_t)(run_for * 1e6));
191 atomic_store(&g_running, 0);
192 elapsed = seconds() - started;
193
194 for (i = 0; i < threads; ++i)
195 pthread_join(ids[i], NULL);
196
197 printf("%.0f replies/s (%.0f sent/s, %lld replies, %lld lost, %ld threads x %ld in flight, %.1f s)\n",
198 (double)atomic_load(&g_replies) / elapsed, (double)atomic_load(&g_sent) / elapsed,
199 (long long)atomic_load(&g_replies), (long long)atomic_load(&g_timeouts), threads, g_window, elapsed);
200 free(ids);
201 return 0;
202}
diff --git a/tests/udp_modes.c b/tests/udp_modes.c
new file mode 100644
index 0000000..654cfd8
--- /dev/null
+++ b/tests/udp_modes.c
@@ -0,0 +1,240 @@
1/* A receiver with the udp arrangements we are choosing between, so they can
2 be compared without any of them being built into the tracker first.
3
4 It echoes what it is sent, so tests/udp_load.c drives it unchanged. There
5 is no tracker work here on purpose: with nothing else happening, whatever
6 the kernel's receive path costs is the whole figure, which is the clearest
7 view of it. Pass a work time to dilute that back towards realism.
8
9 cc -O2 -pthread -o udp_modes tests/udp_modes.c
10 ./udp_modes 6969 4 shared 1
11 ./udp_modes 6969 4 shared 32
12 ./udp_modes 6969 4 per-thread 1
13 ./udp_modes 6969 4 per-thread 32
14
15 Arguments: port, threads, shared|per-thread, datagrams per syscall,
16 and optionally nanoseconds of pretend work per datagram. */
17
18#define _GNU_SOURCE /* struct mmsghdr on glibc */
19
20#include <errno.h>
21#include <netinet/in.h>
22#include <pthread.h>
23#include <signal.h>
24#include <stdatomic.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/socket.h>
29#include <time.h>
30#include <unistd.h>
31
32#if defined(__linux__) || defined(__FreeBSD__)
33#define HAVE_MMSG 1
34#endif
35
36#define MAX_BATCH 256
37#define BUFFER_SIZE 2048
38
39static int g_port;
40static long g_threads;
41static long g_batch;
42static long g_work_ns;
43static int g_shared_socket = -1; /* -1 means one socket per thread */
44static _Atomic int g_running = 1;
45
46static void stop(int sig) {
47 (void)sig;
48 atomic_store(&g_running, 0);
49}
50
51/* Which option the platform offers for spreading datagrams over a group of
52 sockets bound to one address. They are not the same thing: FreeBSD's plain
53 SO_REUSEPORT permits the bind without spreading anything, and Darwin's
54 hands every datagram to whichever socket bound last. */
55static const char *share_the_port(int sock) {
56 int one = 1;
57
58 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
59#ifdef SO_REUSEPORT_LB
60 if (!setsockopt(sock, SOL_SOCKET, SO_REUSEPORT_LB, &one, sizeof(one)))
61 return "SO_REUSEPORT_LB";
62#endif
63#ifdef SO_REUSEPORT
64 if (!setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)))
65 return "SO_REUSEPORT";
66#endif
67 return "neither";
68}
69
70static int bind_one(int share, const char **option) {
71 struct sockaddr_in address;
72 int sock = socket(AF_INET, SOCK_DGRAM, 0);
73
74 if (sock < 0)
75 return -1;
76 *option = share ? share_the_port(sock) : "exclusive";
77
78 memset(&address, 0, sizeof(address));
79 address.sin_family = AF_INET;
80 address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
81 address.sin_port = htons((uint16_t)g_port);
82 if (bind(sock, (struct sockaddr *)&address, sizeof(address)) < 0) {
83 close(sock);
84 return -1;
85 }
86 return sock;
87}
88
89static void pretend_to_work(void) {
90 struct timespec started, now;
91 long waited = 0;
92
93 if (!g_work_ns)
94 return;
95 clock_gettime(CLOCK_MONOTONIC, &started);
96 while (waited < g_work_ns) {
97 clock_gettime(CLOCK_MONOTONIC, &now);
98 waited = (now.tv_sec - started.tv_sec) * 1000000000L + (now.tv_nsec - started.tv_nsec);
99 }
100}
101
102static void one_at_a_time(int sock) {
103 char buffer[BUFFER_SIZE];
104 struct sockaddr_in from;
105 socklen_t length;
106 ssize_t got;
107
108 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
109 length = sizeof(from);
110 got = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&from, &length);
111 if (got < 0) {
112 if (errno == EINTR || errno == EAGAIN)
113 continue;
114 return;
115 }
116 pretend_to_work();
117 sendto(sock, buffer, (size_t)got, 0, (struct sockaddr *)&from, length);
118 }
119}
120
121#ifdef HAVE_MMSG
122static void in_batches(int sock) {
123 static _Thread_local char buffers[MAX_BATCH][BUFFER_SIZE];
124 static _Thread_local struct sockaddr_in froms[MAX_BATCH];
125 static _Thread_local struct iovec iovecs[MAX_BATCH];
126 static _Thread_local struct mmsghdr messages[MAX_BATCH];
127 int got, i;
128
129 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
130 for (i = 0; i < g_batch; ++i) {
131 iovecs[i].iov_base = buffers[i];
132 iovecs[i].iov_len = BUFFER_SIZE;
133 memset(messages + i, 0, sizeof(messages[i]));
134 messages[i].msg_hdr.msg_name = froms + i;
135 messages[i].msg_hdr.msg_namelen = sizeof(froms[i]);
136 messages[i].msg_hdr.msg_iov = iovecs + i;
137 messages[i].msg_hdr.msg_iovlen = 1;
138 }
139
140 /* WAITFORONE so a quiet receiver behaves like the unbatched one rather
141 than holding the first datagram until the batch fills */
142 got = recvmmsg(sock, messages, (unsigned)g_batch, MSG_WAITFORONE, NULL);
143 if (got < 0) {
144 if (errno == EINTR || errno == EAGAIN)
145 continue;
146 return;
147 }
148
149 for (i = 0; i < got; ++i) {
150 pretend_to_work();
151 iovecs[i].iov_len = messages[i].msg_len;
152 messages[i].msg_hdr.msg_namelen = sizeof(froms[i]);
153 }
154 sendmmsg(sock, messages, (unsigned)got, 0);
155 }
156}
157#endif
158
159static void *worker(void *args) {
160 const char *option = "";
161 int sock = g_shared_socket;
162
163 (void)args;
164 if (sock < 0) {
165 sock = bind_one(1, &option);
166 if (sock < 0) {
167 fprintf(stderr, " a worker could not bind: %s\n", strerror(errno));
168 return NULL;
169 }
170 }
171
172#ifdef HAVE_MMSG
173 if (g_batch > 1)
174 in_batches(sock);
175 else
176#endif
177 one_at_a_time(sock);
178
179 if (g_shared_socket < 0)
180 close(sock);
181 return NULL;
182}
183
184int main(int argc, char **argv) {
185 const char *how = argc > 3 ? argv[3] : "shared";
186 const char *option = "";
187 pthread_t *threads;
188 long i;
189
190 g_port = argc > 1 ? atoi(argv[1]) : 6969;
191 g_threads = argc > 2 ? atol(argv[2]) : 1;
192 g_batch = argc > 4 ? atol(argv[4]) : 1;
193 g_work_ns = argc > 5 ? atol(argv[5]) : 0;
194 if (g_batch < 1)
195 g_batch = 1;
196 if (g_batch > MAX_BATCH)
197 g_batch = MAX_BATCH;
198
199#ifndef HAVE_MMSG
200 if (g_batch > 1) {
201 fprintf(stderr, " no recvmmsg on this platform; batching unavailable\n");
202 return 2;
203 }
204#endif
205
206 signal(SIGINT, stop);
207 signal(SIGTERM, stop);
208
209 if (!strcmp(how, "shared")) {
210 g_shared_socket = bind_one(0, &option);
211 if (g_shared_socket < 0) {
212 fprintf(stderr, " bind failed: %s\n", strerror(errno));
213 return 1;
214 }
215 } else {
216 /* Probe once so the mode line can say what the platform gave us */
217 int probe = bind_one(1, &option);
218 if (probe < 0) {
219 fprintf(stderr, " bind failed: %s\n", strerror(errno));
220 return 1;
221 }
222 close(probe);
223 }
224
225 printf(" port %d, %ld threads, %s socket%s (%s), %ld per syscall, %ld ns work\n",
226 g_port, g_threads, strcmp(how, "shared") ? "one per thread" : "one shared",
227 strcmp(how, "shared") ? "s" : "", option, g_batch, g_work_ns);
228 fflush(stdout);
229
230 threads = calloc((size_t)g_threads, sizeof(pthread_t));
231 for (i = 0; i < g_threads; ++i)
232 pthread_create(threads + i, NULL, worker, NULL);
233 for (i = 0; i < g_threads; ++i)
234 pthread_join(threads[i], NULL);
235
236 if (g_shared_socket >= 0)
237 close(g_shared_socket);
238 free(threads);
239 return 0;
240}
diff --git a/tests/udp_modes.py b/tests/udp_modes.py
new file mode 100644
index 0000000..19cd264
--- /dev/null
+++ b/tests/udp_modes.py
@@ -0,0 +1,139 @@
1"""The four udp arrangements, side by side.
2
3 cc -O2 -pthread -o /tmp/udp_modes tests/udp_modes.c
4 cc -O2 -pthread -o /tmp/udp_load tests/udp_load.c
5 python3 tests/udp_modes.py
6
7Two questions at once. Down the table: does a shared socket stop scaling as
8threads are added? Across it: does taking several datagrams per syscall make
9that better, or only cheaper?
10
11The receiver does no tracker work by default, so the figure is the kernel's
12receive path and nothing else. WORK_NS=1500 dilutes it back towards what the
13tracker actually costs per announce.
14
15The number reported is cpu microseconds the receiver spent per datagram
16answered, not throughput. Throughput here says more about the load generator
17than the receiver, because both run on the same machine and an echo costs so
18little that the generator runs out of cores first. Cpu per datagram does not
19care: it is what the receive path costs, whoever is the bottleneck.
20"""
21import os
22import signal
23import socket
24import subprocess
25import sys
26import time
27
28MODES = os.environ.get("MODES", "shared per-thread").split()
29BATCHES = [int(n) for n in os.environ.get("BATCHES", "1 8 32").split()]
30THREAD_COUNTS = [int(n) for n in os.environ.get("THREADS", "1 2 4 8").split()]
31LOAD_THREADS = int(os.environ.get("LOAD_THREADS", "4"))
32WINDOW = int(os.environ.get("WINDOW", "32"))
33SECONDS = float(os.environ.get("SECONDS", "3"))
34REPEATS = int(os.environ.get("REPEATS", "2"))
35WORK_NS = int(os.environ.get("WORK_NS", "0"))
36RECEIVER = os.environ.get("UDP_MODES", "/tmp/udp_modes")
37LOADER = os.environ.get("UDP_LOAD", "/tmp/udp_load")
38PORT_BASE = int(os.environ.get("PORT_BASE", "20100"))
39
40
41def cpu_seconds(pid):
42 try:
43 out = subprocess.run(["ps", "-o", "time=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
44 except OSError:
45 return None
46 if not out:
47 return None
48 total = 0.0
49 for part in out.replace("-", ":").split(":"):
50 total = total * 60 + float(part)
51 return total
52
53
54def one_run(port, threads, mode, batch):
55 receiver = subprocess.Popen(
56 [RECEIVER, str(port), str(threads), mode, str(batch), str(WORK_NS)],
57 stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
58 )
59 for _ in range(200):
60 if receiver.poll() is not None:
61 return None, None
62 probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
63 probe.settimeout(0.1)
64 try:
65 probe.sendto(b"\x00" * 16, ("127.0.0.1", port))
66 probe.recv(64)
67 probe.close()
68 break
69 except OSError:
70 probe.close()
71 time.sleep(0.02)
72 else:
73 receiver.send_signal(signal.SIGINT)
74 receiver.wait()
75 return None, None
76
77 try:
78 subprocess.run([LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), "1", "10000", str(WINDOW)],
79 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
80 spent, wall = cpu_seconds(receiver.pid), time.time()
81 out = subprocess.run(
82 [LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), str(SECONDS), "10000", str(WINDOW)],
83 capture_output=True, text=True,
84 ).stdout.strip()
85 used = cpu_seconds(receiver.pid)
86 finally:
87 receiver.send_signal(signal.SIGINT)
88 try:
89 receiver.wait(timeout=5)
90 except subprocess.TimeoutExpired:
91 receiver.kill()
92 receiver.wait()
93
94 head = out.split()
95 if not head or not head[0].replace(".", "").isdigit():
96 return None, None
97 cores = (used - spent) / max(time.time() - wall, 1e-9) if (used is not None and spent is not None) else None
98 return float(head[0]), cores
99
100
101def main():
102 for binary in (RECEIVER, LOADER):
103 if not os.path.exists(binary):
104 raise SystemExit("missing %s; see the comment at the top of tests/udp_modes.c" % binary)
105
106 print(" %d load threads x %d in flight, %.0f s x %d runs, %d ns work per datagram"
107 % (LOAD_THREADS, WINDOW, SECONDS, REPEATS, WORK_NS))
108 print(" cpu microseconds per datagram, and the throughput it was measured at")
109 header = " %-14s %-8s" % ("sockets", "threads")
110 for batch in BATCHES:
111 header += "%20s" % ("%d per syscall" % batch)
112 print(header)
113
114 port = PORT_BASE
115 for mode in MODES:
116 for threads in THREAD_COUNTS:
117 row = " %-14s %-8d" % (mode, threads)
118 for batch in BATCHES:
119 results = []
120 for _ in range(REPEATS):
121 port += 1
122 rate, cores = one_run(port, threads, mode, batch)
123 if rate:
124 results.append((rate, cores))
125 if not results:
126 row += "%18s" % "-"
127 continue
128 results.sort()
129 rate, cores = results[len(results) // 2]
130 if cores:
131 row += "%9.2f us %6.0fk/s" % (cores * 1e6 / rate, rate / 1000.0)
132 else:
133 row += "%20s" % ("%.0fk/s" % (rate / 1000.0))
134 print(row)
135 sys.stdout.flush()
136
137
138if __name__ == "__main__":
139 main()
diff --git a/tests/udp_scaling.py b/tests/udp_scaling.py
new file mode 100644
index 0000000..7691fcb
--- /dev/null
+++ b/tests/udp_scaling.py
@@ -0,0 +1,159 @@
1"""Does listen.udp.workers help or hurt, on this platform, with this tracker?
2
3Starts a tracker once per worker count and drives it with tests/udp_load.c,
4which speaks the real protocol, so what comes out is the tracker's own
5throughput rather than an echo server's.
6
7 cc -O2 -pthread -o /tmp/udp_load tests/udp_load.c
8 make opentracker
9 python3 tests/udp_scaling.py
10
11Worker count 0 means no dedicated workers: udp is served from the main event
12loop, which is what a default build does.
13
14LOAD_THREADS and WINDOW decide how much load is offered. Both matter. Too
15little and the tracker idles while the figure measures round trips; too much
16and the kernel drops datagrams, every lost reply costs the generator a
17timeout, and the figure collapses.
18
19Three columns say which side the number came from. "cores" is the tracker's
20cpu, "load" the generator's. Whichever is near its machine's core count is
21the one being measured. "lost" counts datagrams that went unanswered: once
22it leaves zero the throughput figure is timeouts, not service, and the run
23needs a smaller WINDOW.
24"""
25import os
26import resource
27import signal
28import socket
29import subprocess
30import sys
31import tempfile
32import time
33
34TRACKER = os.environ.get("OPENTRACKER", "./opentracker")
35LOADER = os.environ.get("UDP_LOAD", "/tmp/udp_load")
36WORKER_COUNTS = [int(n) for n in os.environ.get("WORKERS", "0 1 2 4 8").split()]
37LOAD_THREADS = int(os.environ.get("LOAD_THREADS", "4"))
38SECONDS = float(os.environ.get("SECONDS", "5"))
39TORRENTS = int(os.environ.get("TORRENTS", "10000"))
40WINDOW = int(os.environ.get("WINDOW", "32"))
41REPEATS = int(os.environ.get("REPEATS", "3"))
42PORT_BASE = int(os.environ.get("PORT_BASE", "19960"))
43
44
45def start(port, workers):
46 directory = tempfile.mkdtemp(prefix="ot-udpscale-")
47 config = "listen.tcp 127.0.0.1:%d\nlisten.udp 127.0.0.1:%d\n" % (port, port)
48 if workers:
49 config += "listen.udp.workers %d\n" % workers
50 with open(os.path.join(directory, "conf"), "w") as handle:
51 handle.write(config)
52 log = open(os.path.join(directory, "log"), "w+b")
53 tracker = subprocess.Popen([TRACKER, "-f", os.path.join(directory, "conf")], stdout=log, stderr=log)
54 for _ in range(300):
55 if tracker.poll() is not None:
56 log.seek(0)
57 raise SystemExit("tracker exited at once on port %d with %d workers:\n%s"
58 % (port, workers, log.read().decode("utf-8", "replace")))
59 try:
60 socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
61 return tracker, log
62 except OSError:
63 time.sleep(0.02)
64 tracker.kill()
65 raise SystemExit("tracker never listened on %d" % port)
66
67
68def cpu_seconds(pid):
69 """Cumulative cpu time of a process, the one spelling ps has everywhere."""
70 try:
71 out = subprocess.run(["ps", "-o", "time=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
72 except OSError:
73 return None
74 if not out:
75 return None
76 total, parts = 0.0, out.replace("-", ":").split(":")
77 for part in parts:
78 total = total * 60 + float(part)
79 return total
80
81
82def reaped_cpu_seconds():
83 """Cpu of every child already waited for. The generator is the only one
84 that starts and finishes inside a measured run."""
85 spent = resource.getrusage(resource.RUSAGE_CHILDREN)
86 return spent.ru_utime + spent.ru_stime
87
88
89def stop(tracker):
90 tracker.send_signal(signal.SIGINT)
91 try:
92 tracker.wait(timeout=10)
93 except subprocess.TimeoutExpired:
94 tracker.kill()
95 tracker.wait()
96
97
98def parse(line):
99 """replies/s and the count of announces that were never answered"""
100 words = line.split()
101 if not words or not words[0].replace(".", "").isdigit():
102 return None, None
103 lost = 0
104 if "lost," in words:
105 lost = int(words[words.index("lost,") - 1])
106 return float(words[0]), lost
107
108
109def main():
110 if not os.path.exists(LOADER):
111 raise SystemExit("build the generator first: cc -O2 -pthread -o %s tests/udp_load.c" % LOADER)
112
113 print(" tracker %s, %d load threads x %d in flight, %d torrents, %.0f s x %d runs"
114 % (TRACKER, LOAD_THREADS, WINDOW, TORRENTS, SECONDS, REPEATS))
115 print(" %-8s %12s %7s %7s %7s %10s %s"
116 % ("workers", "median/s", "spread", "cores", "load", "lost", "vs 0 workers"))
117 baseline = None
118 for index, workers in enumerate(WORKER_COUNTS):
119 results = []
120 for repeat in range(REPEATS):
121 port = PORT_BASE + index * 16 + repeat
122 tracker, log = start(port, workers)
123 try:
124 # Warm up until the torrent set exists and the peers are in
125 # place, so the measured run is renewals rather than insertions
126 subprocess.run([LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), "2", str(TORRENTS), str(WINDOW)],
127 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
128 spent, offered, wall = cpu_seconds(tracker.pid), reaped_cpu_seconds(), time.time()
129 result = subprocess.run(
130 [LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), str(SECONDS), str(TORRENTS), str(WINDOW)],
131 capture_output=True, text=True,
132 )
133 used, drove, elapsed = cpu_seconds(tracker.pid), reaped_cpu_seconds(), max(time.time() - wall, 1e-9)
134 finally:
135 stop(tracker)
136 log.close()
137 rate, lost = parse(result.stdout.strip())
138 if rate is None:
139 continue
140 cores = (used - spent) / elapsed if (used is not None and spent is not None) else None
141 results.append((rate, cores, (drove - offered) / elapsed, lost))
142
143 if not results:
144 print(" %-8s no result" % workers)
145 continue
146 results.sort()
147 rate, cores, load, lost = results[len(results) // 2]
148 if baseline is None:
149 baseline = rate
150 # A spread wider than the differences between rows means the rows are
151 # not telling you anything
152 spread = 100.0 * (results[-1][0] - results[0][0]) / rate
153 print(" %-8s %12.0f %6.0f%% %7s %7.2f %10d %.2fx"
154 % (workers, rate, spread, ("%.2f" % cores) if cores else "?", load, lost, rate / baseline))
155 sys.stdout.flush()
156
157
158if __name__ == "__main__":
159 main()
diff --git a/tests/udp_wake_probe.c b/tests/udp_wake_probe.c
new file mode 100644
index 0000000..e948c34
--- /dev/null
+++ b/tests/udp_wake_probe.c
@@ -0,0 +1,121 @@
1/* Four ways to get a thread out of a blocking recvfrom, tested rather than
2 assumed: close the socket, shut it down, give it a receive timeout, or
3 send it a signal.
4
5 This decides how udp workers are stopped. The sockets of a SO_REUSEPORT
6 group all share one address, so a worker cannot be singled out by sending
7 it a datagram, and the two mechanisms differ in what they cost while the
8 tracker is running: a receive timeout wakes every worker on every tick
9 forever, a signal and a shutdown cost nothing until the one moment they
10 are used.
11
12 cc -O2 -pthread -o /tmp/wake tests/udp_wake_probe.c && /tmp/wake
13
14 On Linux 6.1: close does not wake it, the other three do. */
15#include <errno.h>
16#include <netinet/in.h>
17#include <pthread.h>
18#include <stdatomic.h>
19#include <stdio.h>
20#include <string.h>
21#include <sys/socket.h>
22#include <signal.h>
23#include <sys/time.h>
24#include <unistd.h>
25
26#define WAKE_SIGNAL SIGUSR1
27
28static _Atomic int returned;
29static _Atomic int saved_errno;
30static int sock;
31
32static void *reader(void *args) {
33 char buffer[64];
34 (void)args;
35 if (recvfrom(sock, buffer, sizeof(buffer), 0, NULL, NULL) < 0)
36 atomic_store(&saved_errno, errno);
37 atomic_store(&returned, 1);
38 return NULL;
39}
40
41/* A handler that does nothing is all it takes: the point is the return from
42 recvfrom with EINTR, not anything the handler does. SA_RESTART must stay
43 off or the kernel resumes the call instead of reporting it. */
44static void noop(int s) { (void)s; }
45
46static int bind_udp(int timeout_ms) {
47 struct sockaddr_in address;
48 int s = socket(AF_INET, SOCK_DGRAM, 0);
49
50 memset(&address, 0, sizeof(address));
51 address.sin_family = AF_INET;
52 address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
53 address.sin_port = 0;
54 bind(s, (struct sockaddr *)&address, sizeof(address));
55
56 if (timeout_ms) {
57 struct timeval how_long;
58 how_long.tv_sec = timeout_ms / 1000;
59 how_long.tv_usec = (timeout_ms % 1000) * 1000;
60 setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &how_long, sizeof(how_long));
61 }
62 return s;
63}
64
65static void try_it(const char *name, int timeout_ms, int do_close, int do_shutdown, int do_signal) {
66 pthread_t thread;
67 int waited;
68
69 atomic_store(&returned, 0);
70 atomic_store(&saved_errno, 0);
71 sock = bind_udp(timeout_ms);
72 pthread_create(&thread, NULL, reader, NULL);
73 usleep(300000); /* let it reach recvfrom */
74
75 if (do_shutdown)
76 shutdown(sock, SHUT_RD);
77 if (do_signal)
78 pthread_kill(thread, WAKE_SIGNAL);
79 if (do_close)
80 close(sock);
81
82 for (waited = 0; waited < 2000 && !atomic_load(&returned); ++waited)
83 usleep(1000);
84
85 if (atomic_load(&returned)) {
86 printf(" %-24s returned after %4d ms, errno %s\n", name, waited,
87 atomic_load(&saved_errno) ? strerror(atomic_load(&saved_errno)) : "none");
88 pthread_join(thread, NULL);
89 } else {
90 printf(" %-24s STILL BLOCKED after 2000 ms\n", name);
91 /* unblock it so the probe can finish */
92 struct sockaddr_in to;
93 socklen_t length = sizeof(to);
94 int poke = socket(AF_INET, SOCK_DGRAM, 0);
95 if (!getsockname(sock, (struct sockaddr *)&to, &length))
96 sendto(poke, "x", 1, 0, (struct sockaddr *)&to, length);
97 close(poke);
98 usleep(200000);
99 if (atomic_load(&returned))
100 pthread_join(thread, NULL);
101 else
102 pthread_detach(thread);
103 }
104 if (!do_close)
105 close(sock);
106}
107
108int main(void) {
109 struct sigaction sa;
110
111 memset(&sa, 0, sizeof(sa));
112 sa.sa_handler = noop;
113 sa.sa_flags = 0;
114 sigaction(WAKE_SIGNAL, &sa, NULL);
115
116 try_it("close() the socket", 0, 1, 0, 0);
117 try_it("shutdown(SHUT_RD)", 0, 0, 1, 0);
118 try_it("SO_RCVTIMEO 500 ms", 500, 0, 0, 0);
119 try_it("pthread_kill(SIGUSR1)", 0, 0, 0, 1);
120 return 0;
121}
diff --git a/trackerlogic.c b/trackerlogic.c
deleted file mode 100644
index 310466c..0000000
--- a/trackerlogic.c
+++ /dev/null
@@ -1,457 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6/* System */
7#include <stdlib.h>
8#include <string.h>
9#include <stdio.h>
10#include <arpa/inet.h>
11#include <unistd.h>
12#include <errno.h>
13#include <stdint.h>
14
15/* Libowfat */
16#include "byte.h"
17#include "io.h"
18#include "iob.h"
19#include "array.h"
20
21/* Opentracker */
22#include "trackerlogic.h"
23#include "ot_mutex.h"
24#include "ot_stats.h"
25#include "ot_clean.h"
26#include "ot_http.h"
27#include "ot_accesslist.h"
28#include "ot_fullscrape.h"
29#include "ot_livesync.h"
30
31/* Forward declaration */
32size_t return_peers_for_torrent( ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto );
33
34void free_peerlist( ot_peerlist *peer_list ) {
35 if( peer_list->peers.data ) {
36 if( OT_PEERLIST_HASBUCKETS( peer_list ) ) {
37 ot_vector *bucket_list = (ot_vector*)(peer_list->peers.data);
38
39 while( peer_list->peers.size-- )
40 free( bucket_list++->data );
41 }
42 free( peer_list->peers.data );
43 }
44 free( peer_list );
45}
46
47void add_torrent_from_saved_state( ot_hash hash, ot_time base, size_t down_count ) {
48 int exactmatch;
49 ot_torrent *torrent;
50 ot_vector *torrents_list = mutex_bucket_lock_by_hash( hash );
51
52 if( !accesslist_hashisvalid( hash ) )
53 return mutex_bucket_unlock_by_hash( hash, 0 );
54
55 torrent = vector_find_or_insert( torrents_list, (void*)hash, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
56 if( !torrent || exactmatch )
57 return mutex_bucket_unlock_by_hash( hash, 0 );
58
59 /* Create a new torrent entry, then */
60 memcpy( torrent->hash, hash, sizeof(ot_hash) );
61
62 if( !( torrent->peer_list = malloc( sizeof (ot_peerlist) ) ) ) {
63 vector_remove_torrent( torrents_list, torrent );
64 return mutex_bucket_unlock_by_hash( hash, 0 );
65 }
66
67 byte_zero( torrent->peer_list, sizeof( ot_peerlist ) );
68 torrent->peer_list->base = base;
69 torrent->peer_list->down_count = down_count;
70
71 return mutex_bucket_unlock_by_hash( hash, 1 );
72}
73
74size_t add_peer_to_torrent_and_return_peers( PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount ) {
75 int exactmatch, delta_torrentcount = 0;
76 ot_torrent *torrent;
77 ot_peer *peer_dest;
78 ot_vector *torrents_list = mutex_bucket_lock_by_hash( *ws->hash );
79
80 if( !accesslist_hashisvalid( *ws->hash ) ) {
81 mutex_bucket_unlock_by_hash( *ws->hash, 0 );
82 if( proto == FLAG_TCP ) {
83 const char invalid_hash[] = "d14:failure reason63:Requested download is not authorized for use with this tracker.e";
84 memcpy( ws->reply, invalid_hash, strlen( invalid_hash ) );
85 return strlen( invalid_hash );
86 }
87 return 0;
88 }
89
90 torrent = vector_find_or_insert( torrents_list, (void*)ws->hash, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
91 if( !torrent ) {
92 mutex_bucket_unlock_by_hash( *ws->hash, 0 );
93 return 0;
94 }
95
96 if( !exactmatch ) {
97 /* Create a new torrent entry, then */
98 memcpy( torrent->hash, *ws->hash, sizeof(ot_hash) );
99
100 if( !( torrent->peer_list = malloc( sizeof (ot_peerlist) ) ) ) {
101 vector_remove_torrent( torrents_list, torrent );
102 mutex_bucket_unlock_by_hash( *ws->hash, 0 );
103 return 0;
104 }
105
106 byte_zero( torrent->peer_list, sizeof( ot_peerlist ) );
107 delta_torrentcount = 1;
108 } else
109 clean_single_torrent( torrent );
110
111 torrent->peer_list->base = g_now_minutes;
112
113 /* Check for peer in torrent */
114 peer_dest = vector_find_or_insert_peer( &(torrent->peer_list->peers), &ws->peer, &exactmatch );
115 if( !peer_dest ) {
116 mutex_bucket_unlock_by_hash( *ws->hash, delta_torrentcount );
117 return 0;
118 }
119
120 /* Tell peer that it's fresh */
121 OT_PEERTIME( &ws->peer ) = 0;
122
123 /* Sanitize flags: Whoever claims to have completed download, must be a seeder */
124 if( ( OT_PEERFLAG( &ws->peer ) & ( PEER_FLAG_COMPLETED | PEER_FLAG_SEEDING ) ) == PEER_FLAG_COMPLETED )
125 OT_PEERFLAG( &ws->peer ) ^= PEER_FLAG_COMPLETED;
126
127 /* If we hadn't had a match create peer there */
128 if( !exactmatch ) {
129
130#ifdef WANT_SYNC_LIVE
131 if( proto == FLAG_MCA )
132 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_FROM_SYNC;
133 else
134 livesync_tell( ws );
135#endif
136
137 torrent->peer_list->peer_count++;
138 if( OT_PEERFLAG(&ws->peer) & PEER_FLAG_COMPLETED ) {
139 torrent->peer_list->down_count++;
140 stats_issue_event( EVENT_COMPLETED, 0, (uintptr_t)ws );
141 }
142 if( OT_PEERFLAG(&ws->peer) & PEER_FLAG_SEEDING )
143 torrent->peer_list->seed_count++;
144
145 } else {
146 stats_issue_event( EVENT_RENEW, 0, OT_PEERTIME( peer_dest ) );
147#ifdef WANT_SPOT_WOODPECKER
148 if( ( OT_PEERTIME(peer_dest) > 0 ) && ( OT_PEERTIME(peer_dest) < 20 ) )
149 stats_issue_event( EVENT_WOODPECKER, 0, (uintptr_t)&ws->peer );
150#endif
151#ifdef WANT_SYNC_LIVE
152 /* Won't live sync peers that come back too fast. Only exception:
153 fresh "completed" reports */
154 if( proto != FLAG_MCA ) {
155 if( OT_PEERTIME( peer_dest ) > OT_CLIENT_SYNC_RENEW_BOUNDARY ||
156 ( !(OT_PEERFLAG(peer_dest) & PEER_FLAG_COMPLETED ) && (OT_PEERFLAG(&ws->peer) & PEER_FLAG_COMPLETED ) ) )
157 livesync_tell( ws );
158 }
159#endif
160
161 if( (OT_PEERFLAG(peer_dest) & PEER_FLAG_SEEDING ) && !(OT_PEERFLAG(&ws->peer) & PEER_FLAG_SEEDING ) )
162 torrent->peer_list->seed_count--;
163 if( !(OT_PEERFLAG(peer_dest) & PEER_FLAG_SEEDING ) && (OT_PEERFLAG(&ws->peer) & PEER_FLAG_SEEDING ) )
164 torrent->peer_list->seed_count++;
165 if( !(OT_PEERFLAG(peer_dest) & PEER_FLAG_COMPLETED ) && (OT_PEERFLAG(&ws->peer) & PEER_FLAG_COMPLETED ) ) {
166 torrent->peer_list->down_count++;
167 stats_issue_event( EVENT_COMPLETED, 0, (uintptr_t)ws );
168 }
169 if( OT_PEERFLAG(peer_dest) & PEER_FLAG_COMPLETED )
170 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_COMPLETED;
171 }
172
173 memcpy( peer_dest, &ws->peer, sizeof(ot_peer) );
174#ifdef WANT_SYNC
175 if( proto == FLAG_MCA ) {
176 mutex_bucket_unlock_by_hash( *ws->hash, delta_torrentcount );
177 return 0;
178 }
179#endif
180
181 ws->reply_size = return_peers_for_torrent( torrent, amount, ws->reply, proto );
182 mutex_bucket_unlock_by_hash( *ws->hash, delta_torrentcount );
183 return ws->reply_size;
184}
185
186static size_t return_peers_all( ot_peerlist *peer_list, char *reply ) {
187 unsigned int bucket, num_buckets = 1;
188 ot_vector * bucket_list = &peer_list->peers;
189 size_t result = OT_PEER_COMPARE_SIZE * peer_list->peer_count;
190 char * r_end = reply + result;
191
192 if( OT_PEERLIST_HASBUCKETS(peer_list) ) {
193 num_buckets = bucket_list->size;
194 bucket_list = (ot_vector *)bucket_list->data;
195 }
196
197 for( bucket = 0; bucket<num_buckets; ++bucket ) {
198 ot_peer * peers = (ot_peer*)bucket_list[bucket].data;
199 size_t peer_count = bucket_list[bucket].size;
200 while( peer_count-- ) {
201 if( OT_PEERFLAG(peers) & PEER_FLAG_SEEDING ) {
202 r_end-=OT_PEER_COMPARE_SIZE;
203 memcpy(r_end,peers++,OT_PEER_COMPARE_SIZE);
204 } else {
205 memcpy(reply,peers++,OT_PEER_COMPARE_SIZE);
206 reply+=OT_PEER_COMPARE_SIZE;
207 }
208 }
209 }
210 return result;
211}
212
213static size_t return_peers_selection( ot_peerlist *peer_list, size_t amount, char *reply ) {
214 unsigned int bucket_offset, bucket_index = 0, num_buckets = 1;
215 ot_vector * bucket_list = &peer_list->peers;
216 unsigned int shifted_pc = peer_list->peer_count;
217 unsigned int shifted_step = 0;
218 unsigned int shift = 0;
219 size_t result = OT_PEER_COMPARE_SIZE * amount;
220 char * r_end = reply + result;
221
222 if( OT_PEERLIST_HASBUCKETS(peer_list) ) {
223 num_buckets = bucket_list->size;
224 bucket_list = (ot_vector *)bucket_list->data;
225 }
226
227 /* Make fixpoint arithmetic as exact as possible */
228#define MAXPRECBIT (1<<(8*sizeof(int)-3))
229 while( !(shifted_pc & MAXPRECBIT ) ) { shifted_pc <<= 1; shift++; }
230 shifted_step = shifted_pc/amount;
231#undef MAXPRECBIT
232
233 /* Initialize somewhere in the middle of peers so that
234 fixpoint's aliasing doesn't alway miss the same peers */
235 bucket_offset = random() % peer_list->peer_count;
236
237 while( amount-- ) {
238 ot_peer * peer;
239
240 /* This is the aliased, non shifted range, next value may fall into */
241 unsigned int diff = ( ( ( amount + 1 ) * shifted_step ) >> shift ) -
242 ( ( amount * shifted_step ) >> shift );
243 bucket_offset += 1 + random() % diff;
244
245 while( bucket_offset >= bucket_list[bucket_index].size ) {
246 bucket_offset -= bucket_list[bucket_index].size;
247 bucket_index = ( bucket_index + 1 ) % num_buckets;
248 }
249 peer = ((ot_peer*)bucket_list[bucket_index].data) + bucket_offset;
250 if( OT_PEERFLAG(peer) & PEER_FLAG_SEEDING ) {
251 r_end-=OT_PEER_COMPARE_SIZE;
252 memcpy(r_end,peer,OT_PEER_COMPARE_SIZE);
253 } else {
254 memcpy(reply,peer,OT_PEER_COMPARE_SIZE);
255 reply+=OT_PEER_COMPARE_SIZE;
256 }
257 }
258 return result;
259}
260
261/* Compiles a list of random peers for a torrent
262 * reply must have enough space to hold 92+6*amount bytes
263 * does not yet check not to return self
264*/
265size_t return_peers_for_torrent( ot_torrent *torrent, size_t amount, char *reply, PROTO_FLAG proto ) {
266 ot_peerlist *peer_list = torrent->peer_list;
267 char *r = reply;
268
269 if( amount > peer_list->peer_count )
270 amount = peer_list->peer_count;
271
272 if( proto == FLAG_TCP ) {
273 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM;
274 r += sprintf( r, "d8:completei%zde10:downloadedi%zde10:incompletei%zde8:intervali%ie12:min intervali%ie" PEERS_BENCODED "%zd:", peer_list->seed_count, peer_list->down_count, peer_list->peer_count-peer_list->seed_count, erval, erval/2, OT_PEER_COMPARE_SIZE*amount );
275 } else {
276 *(uint32_t*)(r+0) = htonl( OT_CLIENT_REQUEST_INTERVAL_RANDOM );
277 *(uint32_t*)(r+4) = htonl( peer_list->peer_count - peer_list->seed_count );
278 *(uint32_t*)(r+8) = htonl( peer_list->seed_count );
279 r += 12;
280 }
281
282 if( amount ) {
283 if( amount == peer_list->peer_count )
284 r += return_peers_all( peer_list, r );
285 else
286 r += return_peers_selection( peer_list, amount, r );
287 }
288
289 if( proto == FLAG_TCP )
290 *r++ = 'e';
291
292 return r - reply;
293}
294
295/* Fetches scrape info for a specific torrent */
296size_t return_udp_scrape_for_torrent( ot_hash hash, char *reply ) {
297 int exactmatch, delta_torrentcount = 0;
298 ot_vector *torrents_list = mutex_bucket_lock_by_hash( hash );
299 ot_torrent *torrent = binary_search( hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
300
301 if( !exactmatch ) {
302 memset( reply, 0, 12);
303 } else {
304 uint32_t *r = (uint32_t*) reply;
305
306 if( clean_single_torrent( torrent ) ) {
307 vector_remove_torrent( torrents_list, torrent );
308 memset( reply, 0, 12);
309 delta_torrentcount = -1;
310 } else {
311 r[0] = htonl( torrent->peer_list->seed_count );
312 r[1] = htonl( torrent->peer_list->down_count );
313 r[2] = htonl( torrent->peer_list->peer_count-torrent->peer_list->seed_count );
314 }
315 }
316 mutex_bucket_unlock_by_hash( hash, delta_torrentcount );
317 return 12;
318}
319
320/* Fetches scrape info for a specific torrent */
321size_t return_tcp_scrape_for_torrent( ot_hash *hash_list, int amount, char *reply ) {
322 char *r = reply;
323 int exactmatch, i;
324
325 r += sprintf( r, "d5:filesd" );
326
327 for( i=0; i<amount; ++i ) {
328 int delta_torrentcount = 0;
329 ot_hash *hash = hash_list + i;
330 ot_vector *torrents_list = mutex_bucket_lock_by_hash( *hash );
331 ot_torrent *torrent = binary_search( hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
332
333 if( exactmatch ) {
334 if( clean_single_torrent( torrent ) ) {
335 vector_remove_torrent( torrents_list, torrent );
336 delta_torrentcount = -1;
337 } else {
338 *r++='2';*r++='0';*r++=':';
339 memcpy( r, hash, sizeof(ot_hash) ); r+=sizeof(ot_hash);
340 r += sprintf( r, "d8:completei%zde10:downloadedi%zde10:incompletei%zdee",
341 torrent->peer_list->seed_count, torrent->peer_list->down_count, torrent->peer_list->peer_count-torrent->peer_list->seed_count );
342 }
343 }
344 mutex_bucket_unlock_by_hash( *hash, delta_torrentcount );
345 }
346
347 *r++ = 'e'; *r++ = 'e';
348 return r - reply;
349}
350
351static ot_peerlist dummy_list;
352size_t remove_peer_from_torrent( PROTO_FLAG proto, struct ot_workstruct *ws ) {
353 int exactmatch;
354 ot_vector *torrents_list = mutex_bucket_lock_by_hash( *ws->hash );
355 ot_torrent *torrent = binary_search( ws->hash, torrents_list->data, torrents_list->size, sizeof( ot_torrent ), OT_HASH_COMPARE_SIZE, &exactmatch );
356 ot_peerlist *peer_list = &dummy_list;
357
358#ifdef WANT_SYNC_LIVE
359 if( proto != FLAG_MCA ) {
360 OT_PEERFLAG( &ws->peer ) |= PEER_FLAG_STOPPED;
361 livesync_tell( ws );
362 }
363#endif
364
365 if( exactmatch ) {
366 peer_list = torrent->peer_list;
367 switch( vector_remove_peer( &peer_list->peers, &ws->peer ) ) {
368 case 2: peer_list->seed_count--; /* Fall throughs intended */
369 case 1: peer_list->peer_count--; /* Fall throughs intended */
370 default: break;
371 }
372 }
373
374 if( proto == FLAG_TCP ) {
375 int erval = OT_CLIENT_REQUEST_INTERVAL_RANDOM;
376 ws->reply_size = sprintf( ws->reply, "d8:completei%zde10:incompletei%zde8:intervali%ie12:min intervali%ie" PEERS_BENCODED "0:e", peer_list->seed_count, peer_list->peer_count - peer_list->seed_count, erval, erval / 2 );
377 }
378
379 /* Handle UDP reply */
380 if( proto == FLAG_UDP ) {
381 ((uint32_t*)ws->reply)[2] = htonl( OT_CLIENT_REQUEST_INTERVAL_RANDOM );
382 ((uint32_t*)ws->reply)[3] = htonl( peer_list->peer_count - peer_list->seed_count );
383 ((uint32_t*)ws->reply)[4] = htonl( peer_list->seed_count);
384 ws->reply_size = 20;
385 }
386
387 mutex_bucket_unlock_by_hash( *ws->hash, 0 );
388 return ws->reply_size;
389}
390
391void iterate_all_torrents( int (*for_each)( ot_torrent* torrent, uintptr_t data ), uintptr_t data ) {
392 int bucket;
393 size_t j;
394
395 for( bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
396 ot_vector *torrents_list = mutex_bucket_lock( bucket );
397 ot_torrent *torrents = (ot_torrent*)(torrents_list->data);
398
399 for( j=0; j<torrents_list->size; ++j )
400 if( for_each( torrents + j, data ) )
401 break;
402
403 mutex_bucket_unlock( bucket, 0 );
404 if( !g_opentracker_running ) return;
405 }
406}
407
408void exerr( char * message ) {
409 fprintf( stderr, "%s\n", message );
410 exit( 111 );
411}
412
413void trackerlogic_init( ) {
414 g_tracker_id = random();
415
416 if( !g_stats_path )
417 g_stats_path = "stats";
418 g_stats_path_len = strlen( g_stats_path );
419
420 /* Initialise background worker threads */
421 mutex_init( );
422 clean_init( );
423 fullscrape_init( );
424 accesslist_init( );
425 livesync_init( );
426 stats_init( );
427}
428
429void trackerlogic_deinit( void ) {
430 int bucket, delta_torrentcount = 0;
431 size_t j;
432
433 /* Free all torrents... */
434 for(bucket=0; bucket<OT_BUCKET_COUNT; ++bucket ) {
435 ot_vector *torrents_list = mutex_bucket_lock( bucket );
436 if( torrents_list->size ) {
437 for( j=0; j<torrents_list->size; ++j ) {
438 ot_torrent *torrent = ((ot_torrent*)(torrents_list->data)) + j;
439 free_peerlist( torrent->peer_list );
440 delta_torrentcount -= 1;
441 }
442 free( torrents_list->data );
443 }
444 mutex_bucket_unlock( bucket, delta_torrentcount );
445 }
446
447 /* Deinitialise background worker threads */
448 stats_deinit( );
449 livesync_deinit( );
450 accesslist_deinit( );
451 fullscrape_deinit( );
452 clean_deinit( );
453 /* Release mutexes */
454 mutex_deinit( );
455}
456
457const char *g_version_trackerlogic_c = "$Source$: $Revision$\n";
diff --git a/trackerlogic.h b/trackerlogic.h
deleted file mode 100644
index 721ba6e..0000000
--- a/trackerlogic.h
+++ /dev/null
@@ -1,172 +0,0 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3
4 $id$ */
5
6#ifndef OT_TRACKERLOGIC_H__
7#define OT_TRACKERLOGIC_H__
8
9#include <sys/types.h>
10#include <sys/time.h>
11#include <time.h>
12#include <stdint.h>
13
14typedef uint8_t ot_hash[20];
15typedef time_t ot_time;
16typedef char ot_ip6[16];
17typedef struct { ot_ip6 address; int bits; }
18 ot_net;
19#ifdef WANT_V6
20#define OT_IP_SIZE 16
21#define PEERS_BENCODED "6:peers6"
22#else
23#define OT_IP_SIZE 4
24#define PEERS_BENCODED "5:peers"
25#endif
26
27/* Some tracker behaviour tunable */
28#define OT_CLIENT_TIMEOUT 30
29#define OT_CLIENT_TIMEOUT_CHECKINTERVAL 10
30#define OT_CLIENT_TIMEOUT_SEND (60*15)
31#define OT_CLIENT_REQUEST_INTERVAL (60*30)
32#define OT_CLIENT_REQUEST_VARIATION (60*6)
33
34#define OT_TORRENT_TIMEOUT_HOURS 24
35#define OT_TORRENT_TIMEOUT (60*OT_TORRENT_TIMEOUT_HOURS)
36
37#define OT_CLIENT_REQUEST_INTERVAL_RANDOM ( OT_CLIENT_REQUEST_INTERVAL - OT_CLIENT_REQUEST_VARIATION/2 + (int)( random( ) % OT_CLIENT_REQUEST_VARIATION ) )
38
39/* If WANT_MODEST_FULLSCRAPES is on, ip addresses may not
40 fullscrape more frequently than this amount in seconds */
41#define OT_MODEST_PEER_TIMEOUT (60*5)
42
43/* If peers come back before 10 minutes, don't live sync them */
44#define OT_CLIENT_SYNC_RENEW_BOUNDARY 10
45
46/* Number of tracker admin ip addresses allowed */
47#define OT_ADMINIP_MAX 64
48#define OT_MAX_THREADS 64
49
50#define OT_PEER_TIMEOUT 45
51
52/* We maintain a list of 1024 pointers to sorted list of ot_torrent structs
53 Sort key is, of course, its hash */
54#define OT_BUCKET_COUNT_BITS 10
55
56#define OT_BUCKET_COUNT (1<<OT_BUCKET_COUNT_BITS)
57#define OT_BUCKET_COUNT_SHIFT (32-OT_BUCKET_COUNT_BITS)
58
59/* From opentracker.c */
60extern time_t g_now_seconds;
61extern volatile int g_opentracker_running;
62#define g_now_minutes (g_now_seconds/60)
63
64extern uint32_t g_tracker_id;
65typedef enum { FLAG_TCP, FLAG_UDP, FLAG_MCA, FLAG_SELFPIPE } PROTO_FLAG;
66
67typedef struct {
68 uint8_t data[OT_IP_SIZE+2+2];
69} ot_peer;
70static const uint8_t PEER_FLAG_SEEDING = 0x80;
71static const uint8_t PEER_FLAG_COMPLETED = 0x40;
72static const uint8_t PEER_FLAG_STOPPED = 0x20;
73static const uint8_t PEER_FLAG_FROM_SYNC = 0x10;
74static const uint8_t PEER_FLAG_LEECHING = 0x00;
75
76#ifdef WANT_V6
77#define OT_SETIP(peer,ip) memcpy((peer),(ip),(OT_IP_SIZE))
78#else
79#define OT_SETIP(peer,ip) memcpy((peer),(((uint8_t*)ip)+12),(OT_IP_SIZE))
80#endif
81#define OT_SETPORT(peer,port) memcpy(((uint8_t*)(peer))+(OT_IP_SIZE),(port),2)
82#define OT_PEERFLAG(peer) (((uint8_t*)(peer))[(OT_IP_SIZE)+2])
83#define OT_PEERTIME(peer) (((uint8_t*)(peer))[(OT_IP_SIZE)+3])
84
85#define OT_HASH_COMPARE_SIZE (sizeof(ot_hash))
86#define OT_PEER_COMPARE_SIZE ((OT_IP_SIZE)+2)
87
88struct ot_peerlist;
89typedef struct ot_peerlist ot_peerlist;
90typedef struct {
91 ot_hash hash;
92 ot_peerlist *peer_list;
93} ot_torrent;
94
95#include "ot_vector.h"
96
97struct ot_peerlist {
98 ot_time base;
99 size_t seed_count;
100 size_t peer_count;
101 size_t down_count;
102/* normal peers vector or
103 pointer to ot_vector[32] buckets if data != NULL and space == 0
104*/
105 ot_vector peers;
106};
107#define OT_PEERLIST_HASBUCKETS(peer_list) ((peer_list)->peers.size > (peer_list)->peers.space)
108
109struct ot_workstruct {
110 /* Thread specific, static */
111 char *inbuf;
112#define G_INBUF_SIZE 8192
113 char *outbuf;
114#define G_OUTBUF_SIZE 8192
115#ifdef _DEBUG_HTTPERROR
116 char *debugbuf;
117#define G_DEBUGBUF_SIZE 8192
118#endif
119
120 /* The peer currently in the working */
121 ot_peer peer;
122
123 /* Pointers into the request buffer */
124 ot_hash *hash;
125 char *peer_id;
126
127 /* HTTP specific, non static */
128 int keep_alive;
129 char *request;
130 ssize_t request_size;
131 ssize_t header_size;
132 char *reply;
133 ssize_t reply_size;
134};
135
136/*
137 Exported functions
138*/
139
140#ifdef WANT_SYNC_LIVE
141#define WANT_SYNC
142#endif
143
144#ifdef WANT_SYNC
145#define WANT_SYNC_PARAM( param ) , param
146#else
147#define WANT_SYNC_PARAM( param )
148#endif
149
150#ifdef WANT_LOG_NETWORKS
151#error Live logging networks disabled at the moment.
152#endif
153
154void trackerlogic_init( );
155void trackerlogic_deinit( void );
156void exerr( char * message );
157
158/* add_peer_to_torrent does only release the torrent bucket if from_sync is set,
159 otherwise it is released in return_peers_for_torrent */
160size_t add_peer_to_torrent_and_return_peers( PROTO_FLAG proto, struct ot_workstruct *ws, size_t amount );
161size_t remove_peer_from_torrent( PROTO_FLAG proto, struct ot_workstruct *ws );
162size_t return_tcp_scrape_for_torrent( ot_hash *hash, int amount, char *reply );
163size_t return_udp_scrape_for_torrent( ot_hash hash, char *reply );
164void add_torrent_from_saved_state( ot_hash hash, ot_time base, size_t down_count );
165
166/* torrent iterator */
167void iterate_all_torrents( int (*for_each)( ot_torrent* torrent, uintptr_t data ), uintptr_t data );
168
169/* Helper, before it moves to its own object */
170void free_peerlist( ot_peerlist *peer_list );
171
172#endif