1 // Copyright 2018 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 #ifndef SERVICES_NETWORK_NET_LOG_EXPORTER_H_
6 #define SERVICES_NETWORK_NET_LOG_EXPORTER_H_
7
8 #include <memory>
9
10 #include "base/files/file.h"
11 #include "base/macros.h"
12 #include "base/threading/thread_checker.h"
13 #include "base/values.h"
14 #include "net/log/net_log.h"
15 #include "services/network/public/mojom/net_log.mojom.h"
16 #include "services/network/public/mojom/network_service.mojom.h"
17
18 namespace net {
19 class FileNetLogObserver;
20 } // namespace net
21
22 namespace network {
23
24 class NetworkContext;
25
26 // API implementation for exporting ongoing netlogs.
COMPONENT_EXPORT(NETWORK_SERVICE)27 class COMPONENT_EXPORT(NETWORK_SERVICE) NetLogExporter
28 : public mojom::NetLogExporter,
29 public base::SupportsWeakPtr<NetLogExporter> {
30 public:
31 // This expects to live on the same thread as NetworkContext, e.g.
32 // IO thread or NetworkService main thread.
33 explicit NetLogExporter(NetworkContext* network_context);
34 ~NetLogExporter() override;
35
36 void Start(base::File destination,
37 base::Value extra_constants,
38 net::NetLogCaptureMode capture_mode,
39 uint64_t max_file_size,
40 StartCallback callback) override;
41 void Stop(base::Value polled_data, StopCallback callback) override;
42
43 // Sets a callback that will be used to create a scratch directory instead
44 // of the normal codepath. For test use only.
45 void SetCreateScratchDirHandlerForTesting(
46 const base::RepeatingCallback<base::FilePath()>& handler);
47
48 private:
49 void CloseFileOffThread(base::File file);
50
51 // Run off-thread by task scheduler, as does disk I/O.
52 static base::FilePath CreateScratchDir(
53 base::RepeatingCallback<base::FilePath()>
54 scratch_dir_create_handler_for_tests);
55
56 static void StartWithScratchDirOrCleanup(
57 base::WeakPtr<NetLogExporter> object,
58 base::Value extra_constants,
59 net::NetLogCaptureMode capture_mode,
60 uint64_t max_file_size,
61 StartCallback callback,
62 const base::FilePath& scratch_dir_path);
63
64 void StartWithScratchDir(base::Value extra_constants,
65 net::NetLogCaptureMode capture_mode,
66 uint64_t max_file_size,
67 StartCallback callback,
68 const base::FilePath& scratch_dir_path);
69
70 // NetworkContext owns |this| via UniqueReceiverSet, so this object can't
71 // outlive it.
72 NetworkContext* network_context_;
73 enum State { STATE_IDLE, STATE_WAITING_DIR, STATE_RUNNING } state_;
74
75 std::unique_ptr<net::FileNetLogObserver> file_net_observer_;
76 base::File destination_;
77
78 // Test-only injectable replacement for CreateScratchDir.
79 base::RepeatingCallback<base::FilePath()>
80 scratch_dir_create_handler_for_tests_;
81
82 THREAD_CHECKER(thread_checker_);
83
84 DISALLOW_COPY_AND_ASSIGN(NetLogExporter);
85 };
86
87 } // namespace network
88
89 #endif // SERVICES_NETWORK_NET_LOG_EXPORTER_H_
90