blob: a80f2996c4d010b86b4a35f1c16dec284da9d8b3 [file] [log] [blame]
Andreea Costinas41e06442020-03-09 09:41:51 +01001// Copyright 2020 The Chromium OS 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 "system-proxy/server_proxy.h"
6
7#include <iostream>
8#include <string>
9#include <utility>
10#include <vector>
11
12#include <base/bind.h>
13#include <base/bind_helpers.h>
14#include <base/callback_helpers.h>
15#include <base/posix/eintr_wrapper.h>
16#include <base/files/file_util.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010017#include <base/strings/string_util.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010018#include <base/threading/thread.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010019#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010020#include <brillo/data_encoding.h>
21#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090022#include <chromeos/patchpanel/socket.h>
23#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010024
25#include "bindings/worker_common.pb.h"
26#include "system-proxy/protobuf_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010027#include "system-proxy/proxy_connect_job.h"
Andreea Costinas41e06442020-03-09 09:41:51 +010028
29namespace system_proxy {
30
Andreea Costinas44cefa22020-03-09 09:07:39 +010031namespace {
Andreea Costinase45d54b2020-03-10 09:21:14 +010032
33constexpr int kMaxConn = 100;
34
35// Returns the URL encoded value of |text|. It also verifies if the string was
36// already encoded and, if true it returns it unmodified.
37std::string UrlEncode(const std::string& text) {
38 if (text == brillo::data_encoding::UrlDecode(text.c_str()))
39 return brillo::data_encoding::UrlEncode(text.c_str(), false);
40 return text;
41}
42
Andreea Costinas44cefa22020-03-09 09:07:39 +010043} // namespace
44
Andreea Costinas41e06442020-03-09 09:41:51 +010045ServerProxy::ServerProxy(base::OnceClosure quit_closure)
Andreea Costinase45d54b2020-03-10 09:21:14 +010046 : quit_closure_(std::move(quit_closure)), weak_ptr_factory_(this) {}
47ServerProxy::~ServerProxy() = default;
Andreea Costinas41e06442020-03-09 09:41:51 +010048
49void ServerProxy::Init() {
50 // Start listening for input.
51 stdin_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +010052 GetStdinPipe(), base::Bind(&ServerProxy::HandleStdinReadable,
53 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas41e06442020-03-09 09:41:51 +010054
55 // Handle termination signals.
56 signal_handler_.Init();
57 for (int signal : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) {
58 signal_handler_.RegisterHandler(
59 signal, base::BindRepeating(&ServerProxy::HandleSignal,
60 base::Unretained(this)));
61 }
62}
63
Andreea Costinase45d54b2020-03-10 09:21:14 +010064void ServerProxy::ResolveProxy(const std::string& target_url,
65 OnProxyResolvedCallback callback) {
Andreea Costinas5862b102020-03-19 14:45:36 +010066 auto it = pending_proxy_resolution_requests_.find(target_url);
67 if (it != pending_proxy_resolution_requests_.end()) {
68 it->second.push_back(std::move(callback));
69 return;
70 }
71 ProxyResolutionRequest proxy_request;
72 proxy_request.set_target_url(target_url);
73 WorkerRequest request;
74 *request.mutable_proxy_resolution_request() = proxy_request;
75 if (!WriteProtobuf(GetStdoutPipe(), request)) {
76 LOG(ERROR) << "Failed to send proxy resolution request for url: "
77 << target_url;
78 std::move(callback).Run({brillo::http::kDirectProxy});
79 return;
80 }
81 pending_proxy_resolution_requests_[target_url].push_back(std::move(callback));
Andreea Costinase45d54b2020-03-10 09:21:14 +010082}
Andreea Costinas41e06442020-03-09 09:41:51 +010083
84void ServerProxy::HandleStdinReadable() {
85 WorkerConfigs config;
Andreea Costinas44cefa22020-03-09 09:07:39 +010086 if (!ReadProtobuf(GetStdinPipe(), &config)) {
87 LOG(ERROR) << "Error decoding protobuf configurations." << std::endl;
Andreea Costinas41e06442020-03-09 09:41:51 +010088 return;
89 }
Andreea Costinas44cefa22020-03-09 09:07:39 +010090
91 if (config.has_credentials()) {
Andreea Costinase45d54b2020-03-10 09:21:14 +010092 const std::string username = UrlEncode(config.credentials().username());
93 const std::string password = UrlEncode(config.credentials().password());
94 credentials_ = base::JoinString({username.c_str(), password.c_str()}, ":");
Andreea Costinas44cefa22020-03-09 09:07:39 +010095 }
96
97 if (config.has_listening_address()) {
98 if (listening_addr_ != 0) {
99 LOG(ERROR)
100 << "Failure to set configurations: listening port was already set."
101 << std::endl;
102 return;
103 }
104 listening_addr_ = config.listening_address().addr();
105 listening_port_ = config.listening_address().port();
106 CreateListeningSocket();
107 }
Andreea Costinas5862b102020-03-19 14:45:36 +0100108
109 if (config.has_proxy_resolution_reply()) {
110 std::list<std::string> proxies;
111 const ProxyResolutionReply& reply = config.proxy_resolution_reply();
112 for (auto const& proxy : reply.proxy_servers())
113 proxies.push_back(proxy);
114
115 OnProxyResolved(reply.target_url(), proxies);
116 }
Andreea Costinas41e06442020-03-09 09:41:51 +0100117}
118
119bool ServerProxy::HandleSignal(const struct signalfd_siginfo& siginfo) {
120 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
121 std::move(quit_closure_));
122 return true;
123}
124
Andreea Costinas44cefa22020-03-09 09:07:39 +0100125int ServerProxy::GetStdinPipe() {
126 return STDIN_FILENO;
127}
128
Andreea Costinas5862b102020-03-19 14:45:36 +0100129int ServerProxy::GetStdoutPipe() {
130 return STDOUT_FILENO;
131}
132
Andreea Costinas44cefa22020-03-09 09:07:39 +0100133void ServerProxy::CreateListeningSocket() {
Garrick Evans3388a032020-03-24 11:25:55 +0900134 listening_fd_ = std::make_unique<patchpanel::Socket>(
Andreea Costinas44cefa22020-03-09 09:07:39 +0100135 AF_INET, SOCK_STREAM | SOCK_NONBLOCK);
136
137 struct sockaddr_in addr = {0};
138 addr.sin_family = AF_INET;
139 addr.sin_port = htons(listening_port_);
140 addr.sin_addr.s_addr = listening_addr_;
141 if (!listening_fd_->Bind((const struct sockaddr*)&addr, sizeof(addr))) {
142 LOG(ERROR) << "Cannot bind source socket" << std::endl;
143 return;
144 }
145
146 if (!listening_fd_->Listen(kMaxConn)) {
147 LOG(ERROR) << "Cannot listen on source socket." << std::endl;
148 return;
149 }
150
151 fd_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100152 listening_fd_->fd(), base::BindRepeating(&ServerProxy::OnConnectionAccept,
153 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas44cefa22020-03-09 09:07:39 +0100154}
155
Andreea Costinase45d54b2020-03-10 09:21:14 +0100156void ServerProxy::OnConnectionAccept() {
Andreea Costinas44cefa22020-03-09 09:07:39 +0100157 struct sockaddr_storage client_src = {};
158 socklen_t sockaddr_len = sizeof(client_src);
159 if (auto client_conn =
160 listening_fd_->Accept((struct sockaddr*)&client_src, &sockaddr_len)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100161 auto connect_job = std::make_unique<ProxyConnectJob>(
162 std::move(client_conn), credentials_,
163 base::BindOnce(&ServerProxy::ResolveProxy, base::Unretained(this)),
164 base::BindOnce(&ServerProxy::OnConnectionSetupFinished,
165 base::Unretained(this)));
166 if (connect_job->Start())
167 pending_connect_jobs_[connect_job.get()] = std::move(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100168 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100169 // Cleanup any defunct forwarders.
170 // TODO(acostinas, chromium:1064536) Monitor the client and server sockets
171 // and remove the corresponding SocketForwarder when a socket closes.
172 for (auto it = forwarders_.begin(); it != forwarders_.end(); ++it) {
173 if (!(*it)->IsRunning() && (*it)->HasBeenStarted())
174 it = forwarders_.erase(it);
175 }
176}
177
Andreea Costinas5862b102020-03-19 14:45:36 +0100178void ServerProxy::OnProxyResolved(const std::string& target_url,
179 const std::list<std::string>& proxy_servers) {
180 auto callbacks = std::move(pending_proxy_resolution_requests_[target_url]);
181 pending_proxy_resolution_requests_.erase(target_url);
182
183 for (auto& callback : callbacks)
184 std::move(callback).Run(proxy_servers);
185}
186
Andreea Costinase45d54b2020-03-10 09:21:14 +0100187void ServerProxy::OnConnectionSetupFinished(
Garrick Evans3388a032020-03-24 11:25:55 +0900188 std::unique_ptr<patchpanel::SocketForwarder> fwd,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100189 ProxyConnectJob* connect_job) {
190 if (fwd) {
191 // The connection was set up successfully.
192 forwarders_.emplace_back(std::move(fwd));
193 }
194 pending_connect_jobs_.erase(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100195}
196
Andreea Costinas41e06442020-03-09 09:41:51 +0100197} // namespace system_proxy