1 /*
2  *
3  * Copyright (C) 2023 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include <fstream>
20 #include <iostream>
21 #include <memory>
22 #include <regex>
23 #include <string>
24 
25 #include <android-base/strings.h>
26 #include <gflags/gflags.h>
27 #include <grpcpp/ext/proto_server_reflection_plugin.h>
28 #include <grpcpp/grpcpp.h>
29 #include <grpcpp/health_check_service_interface.h>
30 
31 #include "common/libs/utils/files.h"
32 #include "common/libs/utils/json.h"
33 #include "common/libs/utils/result.h"
34 #include "host/libs/web/http_client/http_client.h"
35 #include "openwrt_control.grpc.pb.h"
36 
37 using android::base::StartsWith;
38 using google::protobuf::Empty;
39 using google::protobuf::RepeatedPtrField;
40 using grpc::Server;
41 using grpc::ServerBuilder;
42 using grpc::ServerContext;
43 using grpc::Status;
44 using grpc::StatusCode;
45 using openwrtcontrolserver::LuciRpcReply;
46 using openwrtcontrolserver::LuciRpcRequest;
47 using openwrtcontrolserver::OpenwrtControlService;
48 using openwrtcontrolserver::OpenwrtIpaddrReply;
49 
50 DEFINE_string(grpc_uds_path, "", "grpc_uds_path");
51 DEFINE_bool(bridged_wifi_tap, false,
52             "True for using cvd-wtap-XX, false for using cvd-wifiap-XX");
53 DEFINE_string(webrtc_device_id, "", "The device ID in WebRTC like cvd-1");
54 DEFINE_string(launcher_log_path, "", "File path for launcher.log");
55 DEFINE_string(openwrt_log_path, "", "File path for crosvm_openwrt.log");
56 
57 constexpr char kErrorMessageRpc[] = "Luci RPC request failed";
58 constexpr char kErrorMessageRpcAuth[] = "Luci authentication request failed";
59 
60 namespace cuttlefish {
61 
62 class OpenwrtControlServiceImpl final : public OpenwrtControlService::Service {
63  public:
OpenwrtControlServiceImpl(HttpClient & http_client)64   OpenwrtControlServiceImpl(HttpClient& http_client)
65       : http_client_(http_client) {}
66 
LuciRpc(ServerContext * context,const LuciRpcRequest * request,LuciRpcReply * response)67   Status LuciRpc(ServerContext* context, const LuciRpcRequest* request,
68                  LuciRpcReply* response) override {
69     // Update authentication key when it's empty.
70     if (auth_key_.empty()) {
71       if (!TypeIsSuccess(UpdateLuciRpcAuthKey())) {
72         return Status(StatusCode::UNAVAILABLE, kErrorMessageRpcAuth);
73       }
74     }
75 
76     auto reply = RequestLuciRpc(request->subpath(), request->method(),
77                                 ToVector(request->params()));
78 
79     // When RPC request fails, update authentication key and retry once.
80     if (!TypeIsSuccess(reply)) {
81       if (!TypeIsSuccess(UpdateLuciRpcAuthKey())) {
82         return Status(StatusCode::UNAVAILABLE, kErrorMessageRpcAuth);
83       }
84       reply = RequestLuciRpc(request->subpath(), request->method(),
85                              ToVector(request->params()));
86       if (!TypeIsSuccess(reply)) {
87         return Status(StatusCode::UNAVAILABLE, kErrorMessageRpc);
88       }
89     }
90 
91     Json::FastWriter writer;
92     response->set_id((*reply)["id"].asInt());
93     response->set_error((*reply)["error"].asString());
94     response->set_result(writer.write((*reply)["result"]));
95 
96     return Status::OK;
97   }
98 
OpenwrtIpaddr(ServerContext * context,const Empty * request,OpenwrtIpaddrReply * response)99   Status OpenwrtIpaddr(ServerContext* context, const Empty* request,
100                        OpenwrtIpaddrReply* response) override {
101     // TODO(seungjaeyoo) : Find IP address from crosvm_openwrt.log when using
102     // cvd-wtap-XX after disabling DHCP inside OpenWRT in bridged_wifi_tap mode.
103     auto ipaddr = FindIpaddrLauncherLog();
104     if (!TypeIsSuccess(ipaddr)) {
105       return Status(StatusCode::FAILED_PRECONDITION,
106                     "Failed to get Openwrt IP address");
107     }
108     response->set_ipaddr(*ipaddr);
109     return Status::OK;
110   }
111 
112  private:
113   template <typename T>
ToVector(const RepeatedPtrField<T> & repeated_field)114   std::vector<T> ToVector(const RepeatedPtrField<T>& repeated_field) {
115     std::vector<T> vec;
116     for (const auto& value : repeated_field) {
117       vec.push_back(value);
118     }
119     return vec;
120   }
121 
LuciRpcAddress(const std::string & subpath)122   Result<std::string> LuciRpcAddress(const std::string& subpath) {
123     auto ipaddr = CF_EXPECT(FindIpaddrLauncherLog());
124     return "http://" + ipaddr + "/devices/" + FLAGS_webrtc_device_id +
125            "/openwrt/cgi-bin/luci/rpc/" + subpath;
126   }
127 
LuciRpcAddress(const std::string & subpath,const std::string & auth_key)128   Result<std::string> LuciRpcAddress(const std::string& subpath,
129                                      const std::string& auth_key) {
130     auto addr_without_auth = CF_EXPECT(LuciRpcAddress(subpath));
131     return addr_without_auth + "?auth=" + auth_key;
132   }
133 
LuciRpcData(const std::string & method,const std::vector<std::string> & params)134   Json::Value LuciRpcData(const std::string& method,
135                           const std::vector<std::string>& params) {
136     Json::Value data;
137     data["method"] = method;
138     Json::Value params_json_obj(Json::arrayValue);
139     for (const auto& param : params) {
140       params_json_obj.append(param);
141     }
142     data["params"] = params_json_obj;
143     return data;
144   }
145 
LuciRpcData(int id,const std::string & method,const std::vector<std::string> & params)146   Json::Value LuciRpcData(int id, const std::string& method,
147                           const std::vector<std::string>& params) {
148     Json::Value data = LuciRpcData(method, params);
149     data["id"] = id;
150     return data;
151   }
152 
UpdateLuciRpcAuthKey()153   Result<void> UpdateLuciRpcAuthKey() {
154     auto auth_url = CF_EXPECT(LuciRpcAddress("auth"));
155     auto auth_data = LuciRpcData(1, "login", {"root", "password"});
156     auto auth_reply =
157         CF_EXPECT(http_client_.PostToJson(auth_url, auth_data, header_));
158     if (auth_reply.data["error"].isString()) {
159       CF_EXPECT(!StartsWith(auth_reply.data["error"].asString(),
160                             "Failed to parse json:"),
161                 kErrorMessageRpcAuth);
162     }
163     CF_EXPECT(auth_reply.data["result"].isString(),
164               "Reply doesn't contain result");
165     auth_key_ = auth_reply.data["result"].asString();
166 
167     return {};
168   }
169 
RequestLuciRpc(const std::string & subpath,const std::string & method,const std::vector<std::string> & params)170   Result<Json::Value> RequestLuciRpc(const std::string& subpath,
171                                      const std::string& method,
172                                      const std::vector<std::string>& params) {
173     auto url = CF_EXPECT(LuciRpcAddress(subpath, auth_key_));
174     auto data = LuciRpcData(method, params);
175     auto reply = CF_EXPECT(http_client_.PostToJson(url, data, header_));
176     if (reply.data["error"].isString()) {
177       CF_EXPECT(
178           !StartsWith(reply.data["error"].asString(), "Failed to parse json:"),
179           kErrorMessageRpc);
180     }
181     return reply.data;
182   }
183 
FindIpaddrLauncherLog()184   Result<std::string> FindIpaddrLauncherLog() {
185     if (!FileExists(FLAGS_launcher_log_path)) {
186       return CF_ERR("launcher.log doesn't exist");
187     }
188 
189     std::regex re("wan_ipaddr=[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+");
190     std::smatch matches;
191     std::ifstream ifs(FLAGS_launcher_log_path);
192     std::string line, last_match;
193     while (std::getline(ifs, line)) {
194       if (std::regex_search(line, matches, re)) {
195         last_match = matches[0];
196       }
197     }
198 
199     if (last_match.empty()) {
200       return CF_ERR("IP address is not found from launcher.log");
201     } else {
202       return last_match.substr(last_match.find('=') + 1);
203     }
204   }
205 
206   HttpClient& http_client_;
207   const std::vector<std::string> header_{"Content-Type: application/json"};
208   std::string auth_key_;
209 };
210 
211 }  // namespace cuttlefish
212 
RunServer()213 void RunServer() {
214   std::string server_address("unix:" + FLAGS_grpc_uds_path);
215   auto http_client = cuttlefish::HttpClient::CurlClient();
216   cuttlefish::OpenwrtControlServiceImpl service(*http_client);
217 
218   grpc::EnableDefaultHealthCheckService(true);
219   grpc::reflection::InitProtoReflectionServerBuilderPlugin();
220   ServerBuilder builder;
221   // Listen on the given address without any authentication mechanism.
222   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
223   // Register "service" as the instance through which we'll communicate with
224   // clients. In this case it corresponds to an *synchronous* service.
225   builder.RegisterService(&service);
226   // Finally assemble the server.
227   std::unique_ptr<Server> server(builder.BuildAndStart());
228   std::cout << "Server listening on " << server_address << std::endl;
229 
230   // Wait for the server to shutdown. Note that some other thread must be
231   // responsible for shutting down the server for this call to ever return.
232   server->Wait();
233 }
234 
main(int argc,char ** argv)235 int main(int argc, char** argv) {
236   ::gflags::ParseCommandLineFlags(&argc, &argv, true);
237   RunServer();
238 
239   return 0;
240 }