1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common/libs/utils/socket2socket_proxy.h"
18
19 #include <sys/socket.h>
20
21 #include <cstring>
22 #include <functional>
23 #include <memory>
24 #include <ostream>
25 #include <string>
26 #include <thread>
27
28 #include <android-base/logging.h>
29
30 namespace cuttlefish {
31 namespace {
32
Forward(const std::string & label,SharedFD from,SharedFD to)33 void Forward(const std::string& label, SharedFD from, SharedFD to) {
34 auto success = to->CopyAllFrom(*from);
35 if (!success) {
36 if (from->GetErrno()) {
37 LOG(ERROR) << label << ": Error reading: " << from->StrError();
38 }
39 if (to->GetErrno()) {
40 LOG(ERROR) << label << ": Error writing: " << to->StrError();
41 }
42 }
43 to->Shutdown(SHUT_WR);
44 LOG(DEBUG) << label << " completed";
45 }
46
SetupProxying(SharedFD client,SharedFD target)47 void SetupProxying(SharedFD client, SharedFD target) {
48 std::thread([client, target]() {
49 std::thread client2target(Forward, "client2target", client, target);
50 Forward("target2client", target, client);
51 client2target.join();
52 // The actual proxying is handled in a detached thread so that this function
53 // returns immediately
54 }).detach();
55 }
56
57 } // namespace
58
Proxy(SharedFD server,std::function<SharedFD ()> conn_factory)59 void Proxy(SharedFD server, std::function<SharedFD()> conn_factory) {
60 while (server->IsOpen()) {
61 auto client = SharedFD::Accept(*server);
62 if (!client->IsOpen()) {
63 LOG(ERROR) << "Failed to accept connection in server: "
64 << client->StrError();
65 continue;
66 }
67 auto target = conn_factory();
68 if (target->IsOpen()) {
69 SetupProxying(client, target);
70 }
71 // The client will close when it goes out of scope here if the target didn't
72 // open.
73 }
74 LOG(INFO) << "Server closed: " << server->StrError();
75 }
76
77 } // namespace cuttlefish
78