blob: ef71b72aec01f1fe19294fb87340856e8dc06923 [file] [log] [blame]
Greg Hartman92045f62017-10-31 17:12:24 -07001/*
2 * Copyright (C) 2017 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
Jorge E. Moreirad8430662018-07-22 23:52:33 -070017#include "host/commands/virtual_usb_manager/usbip/server.h"
Greg Hartman92045f62017-10-31 17:12:24 -070018
19#include <glog/logging.h>
20#include <netinet/in.h>
21#include "common/libs/fs/shared_select.h"
22
Greg Hartman153b1062017-11-11 12:09:21 -080023using cvd::SharedFD;
Greg Hartman92045f62017-10-31 17:12:24 -070024
25namespace vadb {
26namespace usbip {
27Server::Server(const std::string& name, const DevicePool& devices)
28 : name_{name}, device_pool_{devices} {}
29
30bool Server::Init() { return CreateServerSocket(); }
31
32// Open new listening server socket.
33// Returns false, if listening socket could not be created.
34bool Server::CreateServerSocket() {
35 LOG(INFO) << "Starting server socket: " << name_;
36
37 server_ = SharedFD::SocketLocalServer(name_.c_str(), true, SOCK_STREAM, 0700);
38 if (!server_->IsOpen()) {
39 LOG(ERROR) << "Could not create socket: " << server_->StrError();
40 return false;
41 }
42 return true;
43}
44
Greg Hartman153b1062017-11-11 12:09:21 -080045void Server::BeforeSelect(cvd::SharedFDSet* fd_read) const {
Greg Hartman92045f62017-10-31 17:12:24 -070046 fd_read->Set(server_);
47 for (const auto& client : clients_) client.BeforeSelect(fd_read);
48}
49
Greg Hartman153b1062017-11-11 12:09:21 -080050void Server::AfterSelect(const cvd::SharedFDSet& fd_read) {
Greg Hartman92045f62017-10-31 17:12:24 -070051 if (fd_read.IsSet(server_)) HandleIncomingConnection();
52
53 for (auto iter = clients_.begin(); iter != clients_.end();) {
54 if (!iter->AfterSelect(fd_read)) {
55 // If client conversation failed, hang up.
56 iter = clients_.erase(iter);
57 continue;
58 }
59 ++iter;
60 }
61}
62
63// Accept new USB/IP connection. Add it to client pool.
64void Server::HandleIncomingConnection() {
65 SharedFD client = SharedFD::Accept(*server_, nullptr, nullptr);
66 if (!client->IsOpen()) {
67 LOG(ERROR) << "Client connection failed: " << client->StrError();
68 return;
69 }
70
71 clients_.emplace_back(device_pool_, client);
72}
73} // namespace usbip
74} // namespace vadb