Debian Codegraph @

srtcore/packetfilter.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2019 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 #include "platform_sys.h"
12
13 #include <string>
14 #include <map>
15 #include <vector>
16 #include <deque>
17 #include <iterator>
18
19 #include "packetfilter.h"
20 #include "packetfilter_builtin.h"
21 #include "core.h"
22 #include "packet.h"
23 #include "logging.h"
24
25 using namespace std;
26 using namespace srt_logging;
27 using namespace srt::sync;
28
29 namespace srt {
30 bool PacketFilter::Internal::ParseConfig(const string& s, SrtFilterConfig& w_config, PacketFilter::Factory** ppf)
31 {
32 if (!SrtParseConfig(s, (w_config)))
33 return false;
34
35 PacketFilter::Factory* fac = find(w_config.type);
36 if (!fac)
37 return false;
38
39 if (ppf)
40 *ppf = fac;
41 // Extract characteristic data
42 w_config.extra_size = fac->ExtraSize();
43
44 return true;
45 }
46
47 bool ParseFilterConfig(const std::string& s, SrtFilterConfig& w_config)
48 {
49 return PacketFilter::internal().ParseConfig(s, (w_config), NULL);
50 }
51
52 // Parameters are passed by value because they need to be potentially modicied inside.
53 bool PacketFilter::Internal::CheckFilterCompat(SrtFilterConfig& w_agent, const SrtFilterConfig& peer_in)
54 {
55 PacketFilter::Factory* fac = find(w_agent.type);
56 if (!fac)
57 return false;
58
59 SrtFilterConfig defaults;
60 if (!ParseConfig(fac->defaultConfig(), (defaults)))
61 {
62 return false;
63 }
64
65 // Make a copy so that modifications can be done. This is only required for internal checks.
66 SrtFilterConfig peer = peer_in;
67 set<string> keys;
68 // Extract all keys to identify also unspecified parameters on both sides
69 // Note that theoretically for FEC it could simply check for the "cols" parameter
70 // that is the only mandatory one, but this is a procedure for packet filters in
71 // general and every filter may define its own set of parameters and mandatory rules.
72 for (map<string, string>::iterator x = w_agent.parameters.begin(); x != w_agent.parameters.end(); ++x)
73 {
74 keys.insert(x->first);
75 if (peer.parameters.count(x->first) == 0)
76 peer.parameters[x->first] = x->second;
77 }
78 for (map<string, string>::iterator x = peer.parameters.begin(); x != peer.parameters.end(); ++x)
79 {
80 keys.insert(x->first);
81 if (w_agent.parameters.count(x->first) == 0)
82 w_agent.parameters[x->first] = x->second;
83 }
84
85 HLOGC(cnlog.Debug, log << "CheckFilterCompat: re-filled: AGENT:" << Printable(w_agent.parameters)
86 << " PEER:" << Printable(peer.parameters));
87
88 // Complete nonexistent keys with default values
89 for (map<string, string>::iterator x = defaults.parameters.begin(); x != defaults.parameters.end(); ++x)
90 {
91 if (!w_agent.parameters.count(x->first))
92 w_agent.parameters[x->first] = x->second;
93 if (!peer.parameters.count(x->first))
94 peer.parameters[x->first] = x->second;
95 }
96
97 for (set<string>::iterator x = keys.begin(); x != keys.end(); ++x)
98 {
99 // Note: operator[] will insert an element with default value
100 // if it doesn't exist. This will inject the empty string as value,
101 // which is acceptable.
102 if (w_agent.parameters[*x] != peer.parameters[*x])
103 {
104 LOGC(cnlog.Error, log << "Packet Filter (" << defaults.type << "): collision on '" << (*x)
105 << "' parameter (agent:" << w_agent.parameters[*x] << " peer:" << (peer.parameters[*x]) << ")");
106 return false;
107 }
108 }
109
110 // Mandatory parameters will be checked when trying to create the filter object.
111
112 return true;
113 }
114
115 struct SortBySequence
116 {
117 bool operator()(const CUnit* u1, const CUnit* u2)
118 {
119 int32_t s1 = u1->m_Packet.getSeqNo();
120 int32_t s2 = u2->m_Packet.getSeqNo();
121
122 return CSeqNo::seqcmp(s1, s2) < 0;
123 }
124 };
125
126 void PacketFilter::receive(CUnit* unit, std::vector<CUnit*>& w_incoming, loss_seqs_t& w_loss_seqs)
127 {
128 const CPacket& rpkt = unit->m_Packet;
129
130 if (m_filter->receive(rpkt, w_loss_seqs))
131 {
132 // For the sake of rebuilding MARK THIS UNIT GOOD, otherwise the
133 // unit factory will supply it from getNextAvailUnit() as if it were not in use.
134 unit->m_bTaken = true;
135 HLOGC(pflog.Debug, log << "FILTER: PASSTHRU current packet %" << unit->m_Packet.getSeqNo());
136 w_incoming.push_back(unit);
137 }
138 else
139 {
140 // Packet not to be passthru, update stats
141 ScopedLock lg(m_parent->m_StatsLock);
142 m_parent->m_stats.rcvr.recvdFilterExtra.count(1);
143 }
144
145 // w_loss_seqs enters empty into this function and can be only filled here. XXX ASSERT?
146 for (loss_seqs_t::iterator i = w_loss_seqs.begin();
147 i != w_loss_seqs.end(); ++i)
148 {
149 // Sequences here are low-high, if there happens any negative distance
150 // here, simply skip and report IPE.
151 int dist = CSeqNo::seqoff(i->first, i->second) + 1;
152 if (dist > 0)
153 {
154 ScopedLock lg(m_parent->m_StatsLock);
155 m_parent->m_stats.rcvr.lossFilter.count(dist);
156 }
157 else
158 {
159 LOGC(pflog.Error, log << "FILTER: IPE: loss record: invalid loss: %"
160 << i->first << " - %" << i->second);
161 }
162 }
163
164 // Pack first recovered packets, if any.
165 if (!m_provided.empty())
166 {
167 HLOGC(pflog.Debug, log << "FILTER: inserting REBUILT packets (" << m_provided.size() << "):");
168
169 size_t nsupply = m_provided.size();
170 InsertRebuilt(w_incoming, m_unitq);
171
172 ScopedLock lg(m_parent->m_StatsLock);
173 m_parent->m_stats.rcvr.suppliedByFilter.count((uint32_t)nsupply);
174 }
175
176 // Now that all units have been filled as they should be,
177 // SET THEM ALL FREE. This is because now it's up to the
178 // buffer to decide as to whether it wants them or not.
179 // Wanted units will be set GOOD flag, unwanted will remain
180 // with FREE and therefore will be returned at the next
181 // call to getNextAvailUnit().
182 unit->m_bTaken = false;
183 for (vector<CUnit*>::iterator i = w_incoming.begin(); i != w_incoming.end(); ++i)
184 {
185 CUnit* u = *i;
186 u->m_bTaken = false;
187 }
188
189 // Packets must be sorted by sequence number, ascending, in order
190 // not to challenge the SRT's contiguity checker.
191 sort(w_incoming.begin(), w_incoming.end(), SortBySequence());
192
193 // For now, report immediately the irrecoverable packets
194 // from the row.
195
196 // Later, the `irrecover_row` or `irrecover_col` will be
197 // reported only, depending on level settings. For example,
198 // with default LATELY level, packets will be reported as
199 // irrecoverable only when they are irrecoverable in the
200 // vertical group.
201
202 // With "always", do not report any losses, SRT will simply check
203 // them itself.
204
205 return;
206
207 }
208
209 bool PacketFilter::packControlPacket(int32_t seq, int kflg, CPacket& w_packet)
210 {
211 bool have = m_filter->packControlPacket(m_sndctlpkt, seq);
212 if (!have)
213 return false;
214
215 // Now this should be repacked back to CPacket.
216 // The header must be copied, it's always part of CPacket.
217 uint32_t* hdr = w_packet.getHeader();
218 memcpy((hdr), m_sndctlpkt.hdr, SRT_PH_E_SIZE * sizeof(*hdr));
219
220 // The buffer can be assigned.
221 w_packet.m_pcData = m_sndctlpkt.buffer;
222 w_packet.setLength(m_sndctlpkt.length);
223
224 // This sets only the Packet Boundary flags, while all other things:
225 // - Order
226 // - Rexmit
227 // - Crypto
228 // - Message Number
229 // will be set to 0/false
230 w_packet.set_msgflags(SRT_MSGNO_CONTROL | MSGNO_PACKET_BOUNDARY::wrap(PB_SOLO));
231
232 // ... and then fix only the Crypto flags
233 w_packet.setMsgCryptoFlags(EncryptionKeySpec(kflg));
234
235 // Don't set the ID, it will be later set for any kind of packet.
236 // Write the timestamp clip into the timestamp field.
237 return true;
238 }
239
240
241 void PacketFilter::InsertRebuilt(vector<CUnit*>& incoming, CUnitQueue* uq)
242 {
243 if (m_provided.empty())
244 return;
245
246 for (vector<SrtPacket>::iterator i = m_provided.begin(); i != m_provided.end(); ++i)
247 {
248 CUnit* u = uq->getNextAvailUnit();
249 if (!u)
250 {
251 LOGC(pflog.Error, log << "FILTER: LOCAL STORAGE DEPLETED. Can't return rebuilt packets.");
252 break;
253 }
254
255 // LOCK the unit as taken because otherwise the next
256 // call to getNextAvailUnit will return THE SAME UNIT.
257 u->m_bTaken = true;
258 // After returning from this function, all units will be
259 // set back to FREE so that the buffer can decide whether
260 // it wants them or not.
261
262 CPacket& packet = u->m_Packet;
263
264 memcpy((packet.getHeader()), i->hdr, CPacket::HDR_SIZE);
265 memcpy((packet.m_pcData), i->buffer, i->length);
266 packet.setLength(i->length);
267
268 HLOGC(pflog.Debug, log << "FILTER: PROVIDING rebuilt packet %" << packet.getSeqNo());
269
270 incoming.push_back(u);
271 }
272
273 m_provided.clear();
274 }
275
276 // Placement here is necessary in order to mark the location to
277 // store the PacketFilter::Factory class characteristic object.
278 PacketFilter::Factory::~Factory()
279 {
280 }
281
282 #if HAVE_CXX11
283
284 PacketFilter::Internal& PacketFilter::internal()
285 {
286 static PacketFilter::Internal instance;
287 return instance;
288 }
289
290 #else // !HAVE_CXX11
291
292 static pthread_once_t s_PacketFactoryOnce = PTHREAD_ONCE_INIT;
293
294 static PacketFilter::Internal *getInstance()
295 {
296 static PacketFilter::Internal instance;
297 return &instance;
298 }
299
300 PacketFilter::Internal& PacketFilter::internal()
301 {
302 // We don't want lock each time, pthread_once can be faster than mutex.
303 pthread_once(&s_PacketFactoryOnce, reinterpret_cast<void (*)()>(getInstance));
304 return *getInstance();
305 }
306
307 #endif
308
309 PacketFilter::Internal::Internal()
310 {
311 // Add here builtin packet filters and mark them
312 // as builtin. This will disallow users to register
313 // external filters with the same name.
314
315 m_filters["fec"] = new PacketFilter::Creator<FECFilterBuiltin>;
316 m_builtin_filters.insert("fec");
317 }
318
319 bool PacketFilter::configure(CUDT* parent, CUnitQueue* uq, const std::string& confstr)
320 {
321 m_parent = parent;
322
323 SrtFilterConfig cfg;
324 if (!internal().ParseConfig(confstr, (cfg)))
325 return false;
326
327 // Extract the "type" key from parameters, or use
328 // builtin if lacking.
329 PacketFilter::Factory *factory = internal().find(cfg.type);
330 if (factory == NULL)
331 return false;
332
333 SrtFilterInitializer init;
334 init.socket_id = parent->socketID();
335 init.snd_isn = parent->sndSeqNo();
336 init.rcv_isn = parent->rcvSeqNo();
337
338 // XXX This is a formula for a full "SRT payload" part that undergoes transmission,
339 // might be nice to have this formula as something more general.
340 init.payload_size = parent->OPT_PayloadSize() + parent->getAuthTagSize();
341 init.rcvbuf_size = parent->m_config.iRcvBufSize;
342
343 HLOGC(pflog.Debug, log << "PFILTER: @" << init.socket_id << " payload size="
344 << init.payload_size << " rcvbuf size=" << init.rcvbuf_size);
345
346 // Found a filter, so call the creation function
347 m_filter = factory->Create(init, m_provided, confstr);
348 if (!m_filter)
349 return false;
350
351 m_unitq = uq;
352
353 // The filter should have pinned in all events
354 // that are of its interest. It's stated that
355 // it's ready after creation.
356 return true;
357 }
358
359 bool PacketFilter::correctConfig(const SrtFilterConfig& conf)
360 {
361 const string* pname = map_getp(conf.parameters, "type");
362
363 if (!pname)
364 return true; // default, parameters ignored
365
366 if (*pname == "adaptive")
367 return true;
368
369 PacketFilter::Factory *factory = internal().find(*pname);
370 if (factory == NULL)
371 return false;
372
373 return true;
374 }
375
376 PacketFilter::~PacketFilter()
377 {
378 delete m_filter;
379 }
380
381 } // namespace srt