1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/media/webrtc/webrtc_rtp_dump_handler.h"
6 
7 #include <utility>
8 
9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/task/post_task.h"
15 #include "base/task/thread_pool.h"
16 #include "base/threading/sequenced_task_runner_handle.h"
17 #include "base/time/time.h"
18 #include "chrome/browser/media/webrtc/webrtc_rtp_dump_writer.h"
19 
20 namespace {
21 
22 static const size_t kMaxOngoingRtpDumpsAllowed = 5;
23 
24 // The browser process wide total number of ongoing (i.e. started and not
25 // released) RTP dumps. Incoming and outgoing in one WebRtcDumpHandler are
26 // counted as one dump.
27 // Must be accessed on the browser IO thread.
28 static size_t g_ongoing_rtp_dumps = 0;
29 
FireGenericDoneCallback(WebRtcRtpDumpHandler::GenericDoneCallback callback,bool success,const std::string & error_message)30 void FireGenericDoneCallback(WebRtcRtpDumpHandler::GenericDoneCallback callback,
31                              bool success,
32                              const std::string& error_message) {
33   DCHECK(!callback.is_null());
34 
35   base::SequencedTaskRunnerHandle::Get()->PostTask(
36       FROM_HERE, base::BindOnce(std::move(callback), success, error_message));
37 }
38 
DumpTypeContainsIncoming(RtpDumpType type)39 bool DumpTypeContainsIncoming(RtpDumpType type) {
40   return type == RTP_DUMP_INCOMING || type == RTP_DUMP_BOTH;
41 }
42 
DumpTypeContainsOutgoing(RtpDumpType type)43 bool DumpTypeContainsOutgoing(RtpDumpType type) {
44   return type == RTP_DUMP_OUTGOING || type == RTP_DUMP_BOTH;
45 }
46 
47 }  // namespace
48 
WebRtcRtpDumpHandler(const base::FilePath & dump_dir)49 WebRtcRtpDumpHandler::WebRtcRtpDumpHandler(const base::FilePath& dump_dir)
50     : dump_dir_(dump_dir),
51       incoming_state_(STATE_NONE),
52       outgoing_state_(STATE_NONE) {}
53 
~WebRtcRtpDumpHandler()54 WebRtcRtpDumpHandler::~WebRtcRtpDumpHandler() {
55   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
56 
57   // Reset dump writer first to stop writing.
58   if (dump_writer_) {
59     --g_ongoing_rtp_dumps;
60     dump_writer_.reset();
61   }
62 
63   if (incoming_state_ != STATE_NONE && !incoming_dump_path_.empty()) {
64     base::ThreadPool::PostTask(
65         FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
66         base::BindOnce(base::GetDeleteFileCallback(), incoming_dump_path_));
67   }
68 
69   if (outgoing_state_ != STATE_NONE && !outgoing_dump_path_.empty()) {
70     base::ThreadPool::PostTask(
71         FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
72         base::BindOnce(base::GetDeleteFileCallback(), outgoing_dump_path_));
73   }
74 }
75 
StartDump(RtpDumpType type,std::string * error_message)76 bool WebRtcRtpDumpHandler::StartDump(RtpDumpType type,
77                                      std::string* error_message) {
78   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
79 
80   if (!dump_writer_ && g_ongoing_rtp_dumps >= kMaxOngoingRtpDumpsAllowed) {
81     *error_message = "Max RTP dump limit reached.";
82     DVLOG(2) << *error_message;
83     return false;
84   }
85 
86   // Returns an error if any type of dump specified by the caller cannot be
87   // started.
88   if ((DumpTypeContainsIncoming(type) && incoming_state_ != STATE_NONE) ||
89       (DumpTypeContainsOutgoing(type) && outgoing_state_ != STATE_NONE)) {
90     *error_message =
91         "RTP dump already started for type " + base::NumberToString(type);
92     return false;
93   }
94 
95   if (DumpTypeContainsIncoming(type))
96     incoming_state_ = STATE_STARTED;
97 
98   if (DumpTypeContainsOutgoing(type))
99     outgoing_state_ = STATE_STARTED;
100 
101   DVLOG(2) << "Start RTP dumping: type = " << type;
102 
103   if (!dump_writer_) {
104     ++g_ongoing_rtp_dumps;
105 
106     static const char kRecvDumpFilePrefix[] = "rtpdump_recv_";
107     static const char kSendDumpFilePrefix[] = "rtpdump_send_";
108     static const size_t kMaxDumpSize = 5 * 1024 * 1024;  // 5MB
109 
110     std::string dump_id = base::NumberToString(base::Time::Now().ToDoubleT());
111     incoming_dump_path_ =
112         dump_dir_.AppendASCII(std::string(kRecvDumpFilePrefix) + dump_id)
113             .AddExtension(FILE_PATH_LITERAL(".gz"));
114 
115     outgoing_dump_path_ =
116         dump_dir_.AppendASCII(std::string(kSendDumpFilePrefix) + dump_id)
117             .AddExtension(FILE_PATH_LITERAL(".gz"));
118 
119     // WebRtcRtpDumpWriter does not support changing the dump path after it's
120     // created. So we assign both incoming and outgoing dump path even if only
121     // one type of dumping has been started.
122     // For "Unretained(this)", see comments StopDump.
123     dump_writer_ = std::make_unique<WebRtcRtpDumpWriter>(
124         incoming_dump_path_, outgoing_dump_path_, kMaxDumpSize,
125         base::BindRepeating(&WebRtcRtpDumpHandler::OnMaxDumpSizeReached,
126                             base::Unretained(this)));
127   }
128 
129   return true;
130 }
131 
StopDump(RtpDumpType type,GenericDoneCallback callback)132 void WebRtcRtpDumpHandler::StopDump(RtpDumpType type,
133                                     GenericDoneCallback callback) {
134   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
135 
136   // Returns an error if any type of dump specified by the caller cannot be
137   // stopped.
138   if ((DumpTypeContainsIncoming(type) && incoming_state_ != STATE_STARTED) ||
139       (DumpTypeContainsOutgoing(type) && outgoing_state_ != STATE_STARTED)) {
140     if (!callback.is_null()) {
141       FireGenericDoneCallback(
142           std::move(callback), false,
143           "RTP dump not started or already stopped for type " +
144               base::NumberToString(type));
145     }
146     return;
147   }
148 
149   DVLOG(2) << "Stopping RTP dumping: type = " << type;
150 
151   if (DumpTypeContainsIncoming(type))
152     incoming_state_ = STATE_STOPPING;
153 
154   if (DumpTypeContainsOutgoing(type))
155     outgoing_state_ = STATE_STOPPING;
156 
157   // Using "Unretained(this)" because the this object owns the writer and the
158   // writer is guaranteed to cancel the callback before it goes away. Same for
159   // the other posted tasks bound to the writer.
160   dump_writer_->EndDump(
161       type,
162       base::BindOnce(&WebRtcRtpDumpHandler::OnDumpEnded, base::Unretained(this),
163                      callback.is_null()
164                          ? base::NullCallback()
165                          : base::BindOnce(&FireGenericDoneCallback,
166                                           std::move(callback), true, ""),
167                      type));
168 }
169 
ReadyToRelease() const170 bool WebRtcRtpDumpHandler::ReadyToRelease() const {
171   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
172 
173   return incoming_state_ != STATE_STARTED &&
174          incoming_state_ != STATE_STOPPING &&
175          outgoing_state_ != STATE_STARTED && outgoing_state_ != STATE_STOPPING;
176 }
177 
ReleaseDumps()178 WebRtcRtpDumpHandler::ReleasedDumps WebRtcRtpDumpHandler::ReleaseDumps() {
179   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
180   DCHECK(ReadyToRelease());
181 
182   base::FilePath incoming_dump, outgoing_dump;
183 
184   if (incoming_state_ == STATE_STOPPED) {
185     DVLOG(2) << "Incoming RTP dumps released: " << incoming_dump_path_.value();
186 
187     incoming_state_ = STATE_NONE;
188     incoming_dump = incoming_dump_path_;
189   }
190 
191   if (outgoing_state_ == STATE_STOPPED) {
192     DVLOG(2) << "Outgoing RTP dumps released: " << outgoing_dump_path_.value();
193 
194     outgoing_state_ = STATE_NONE;
195     outgoing_dump = outgoing_dump_path_;
196   }
197   return ReleasedDumps(incoming_dump, outgoing_dump);
198 }
199 
OnRtpPacket(const uint8_t * packet_header,size_t header_length,size_t packet_length,bool incoming)200 void WebRtcRtpDumpHandler::OnRtpPacket(const uint8_t* packet_header,
201                                        size_t header_length,
202                                        size_t packet_length,
203                                        bool incoming) {
204   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
205 
206   if ((incoming && incoming_state_ != STATE_STARTED) ||
207       (!incoming && outgoing_state_ != STATE_STARTED)) {
208     return;
209   }
210 
211   dump_writer_->WriteRtpPacket(
212       packet_header, header_length, packet_length, incoming);
213 }
214 
StopOngoingDumps(base::OnceClosure callback)215 void WebRtcRtpDumpHandler::StopOngoingDumps(base::OnceClosure callback) {
216   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
217   DCHECK(!callback.is_null());
218 
219   // No ongoing dumps, return directly.
220   if ((incoming_state_ == STATE_NONE || incoming_state_ == STATE_STOPPED) &&
221       (outgoing_state_ == STATE_NONE || outgoing_state_ == STATE_STOPPED)) {
222     std::move(callback).Run();
223     return;
224   }
225 
226   // If the background task runner is working on stopping the dumps, wait for it
227   // to complete and then check the states again.
228   if (incoming_state_ == STATE_STOPPING || outgoing_state_ == STATE_STOPPING) {
229     dump_writer_->background_task_runner()->PostTaskAndReply(
230         FROM_HERE, base::DoNothing(),
231         base::BindOnce(&WebRtcRtpDumpHandler::StopOngoingDumps,
232                        weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
233     return;
234   }
235 
236   // Either incoming or outgoing dump must be ongoing.
237   RtpDumpType type =
238       (incoming_state_ == STATE_STARTED)
239           ? (outgoing_state_ == STATE_STARTED ? RTP_DUMP_BOTH
240                                               : RTP_DUMP_INCOMING)
241           : RTP_DUMP_OUTGOING;
242 
243   if (incoming_state_ == STATE_STARTED)
244     incoming_state_ = STATE_STOPPING;
245 
246   if (outgoing_state_ == STATE_STARTED)
247     outgoing_state_ = STATE_STOPPING;
248 
249   DVLOG(2) << "Stopping ongoing dumps: type = " << type;
250 
251   dump_writer_->EndDump(
252       type, base::BindOnce(&WebRtcRtpDumpHandler::OnDumpEnded,
253                            base::Unretained(this), std::move(callback), type));
254 }
255 
SetDumpWriterForTesting(std::unique_ptr<WebRtcRtpDumpWriter> writer)256 void WebRtcRtpDumpHandler::SetDumpWriterForTesting(
257     std::unique_ptr<WebRtcRtpDumpWriter> writer) {
258   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
259 
260   dump_writer_ = std::move(writer);
261   ++g_ongoing_rtp_dumps;
262 
263   incoming_dump_path_ = dump_dir_.AppendASCII("recv");
264   outgoing_dump_path_ = dump_dir_.AppendASCII("send");
265 }
266 
OnMaxDumpSizeReached()267 void WebRtcRtpDumpHandler::OnMaxDumpSizeReached() {
268   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
269 
270   RtpDumpType type =
271       (incoming_state_ == STATE_STARTED)
272           ? (outgoing_state_ == STATE_STARTED ? RTP_DUMP_BOTH
273                                               : RTP_DUMP_INCOMING)
274           : RTP_DUMP_OUTGOING;
275   StopDump(type, GenericDoneCallback());
276 }
277 
OnDumpEnded(base::OnceClosure callback,RtpDumpType ended_type,bool incoming_success,bool outgoing_success)278 void WebRtcRtpDumpHandler::OnDumpEnded(base::OnceClosure callback,
279                                        RtpDumpType ended_type,
280                                        bool incoming_success,
281                                        bool outgoing_success) {
282   DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_);
283 
284   if (DumpTypeContainsIncoming(ended_type)) {
285     DCHECK_EQ(STATE_STOPPING, incoming_state_);
286     incoming_state_ = STATE_STOPPED;
287 
288     if (!incoming_success) {
289       base::ThreadPool::PostTask(
290           FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
291           base::BindOnce(base::GetDeleteFileCallback(), incoming_dump_path_));
292 
293       DVLOG(2) << "Deleted invalid incoming dump "
294                << incoming_dump_path_.value();
295       incoming_dump_path_.clear();
296     }
297   }
298 
299   if (DumpTypeContainsOutgoing(ended_type)) {
300     DCHECK_EQ(STATE_STOPPING, outgoing_state_);
301     outgoing_state_ = STATE_STOPPED;
302 
303     if (!outgoing_success) {
304       base::ThreadPool::PostTask(
305           FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
306           base::BindOnce(base::GetDeleteFileCallback(), outgoing_dump_path_));
307 
308       DVLOG(2) << "Deleted invalid outgoing dump "
309                << outgoing_dump_path_.value();
310       outgoing_dump_path_.clear();
311     }
312   }
313 
314   // Release the writer when it's no longer needed.
315   if (incoming_state_ != STATE_STOPPING && outgoing_state_ != STATE_STOPPING &&
316       incoming_state_ != STATE_STARTED && outgoing_state_ != STATE_STARTED) {
317     dump_writer_.reset();
318     --g_ongoing_rtp_dumps;
319   }
320 
321   // This object might be deleted after running the callback.
322   if (!callback.is_null())
323     std::move(callback).Run();
324 }
325