VirtualADB: Drop Operations that are not required if not using usbip command

This change drops functionality that is no longer required since we
dont use usbip command line utility any more.

Change-Id: I0212fd6913389d61641989f6e358eacf898b2320
(cherry picked from commit 4970c06592e01206f0abc3dc20af837575f03319)
diff --git a/vadb/main.cpp b/vadb/main.cpp
index 15fe665..be81f73 100644
--- a/vadb/main.cpp
+++ b/vadb/main.cpp
@@ -37,7 +37,6 @@
   CHECK(vhci.Init());
 
   vadb::usbip::Server s(FLAGS_usbip_socket_name, adb.Pool());
-  s.SetClientsAttachedByDefault(true);
   CHECK(s.Init()) << "Could not start server";
   s.Serve();
 }
diff --git a/vadb/usbip/client.cpp b/vadb/usbip/client.cpp
index 295eef2..5a23500 100644
--- a/vadb/usbip/client.cpp
+++ b/vadb/usbip/client.cpp
@@ -23,228 +23,11 @@
 
 namespace vadb {
 namespace usbip {
-namespace {
-// Parse BUI ID (typically in form #-#) and extract root hub and bus.
-// We use these values as synonyms to bus and device numbers internally.
-// Returns false, if extracting BusDevNumber was unsuccessful.
-bool ParseBusID(const OpReqRepBusId& busid, DevicePool::BusDevNumber* dn) {
-  return sscanf(busid, "%hu-%hu", &dn->bus_number, &dn->dev_number) == 2;
-}
-
-// Build USBIP Device Report.
-void BuildDeviceNode(DevicePool::BusDevNumber dn, const Device& dd,
-                     OpRepDeviceInfo* node) {
-  memset(node, 0, sizeof(*node));
-
-  snprintf(node->usb_path, sizeof(node->usb_path),
-           "/sys/devices/usb/vhci/%hu-%hu", dn.bus_number, dn.dev_number);
-  snprintf(node->bus_id, sizeof(node->bus_id), "%hu-%hu", dn.bus_number,
-           dn.dev_number);
-
-  node->bus_num = dn.bus_number;
-  node->dev_num = dn.dev_number;
-
-  // TODO(ender): How is this defined?
-  node->speed = 2;
-
-  node->id_vendor = dd.vendor_id;
-  node->id_product = dd.product_id;
-  node->bcd_device = dd.dev_version;
-  node->device_class = dd.dev_class;
-  node->device_subclass = dd.dev_subclass;
-  node->device_protocol = dd.dev_protocol;
-  node->configuration_value = dd.configuration_number;
-  node->num_configurations = dd.configurations_count;
-  node->num_interfaces = dd.interfaces.size();
-}
-}  // namespace
-
-// Handle incoming USB/IP message.
-// USB/IP messages have two forms:
-// - OPs (OPERATIONs) - are executed only before remote device is attached,
-// - CMDs (COMMANDs)  - are executed only after remote device is attached.
-// The two types of commands are incompatible with one another, so it's
-// impossible to tell which is being parsed, unless you know the state of this
-// connection.
-//
-// Returns false, if connection should be dropped.
-bool Client::HandleIncomingMessage() {
-  return attached_ ? HandleCommand() : HandleOperation();
-}
-
-// Handle incoming OPERATION.
-//
-// Reads next OP from client channel.
-// Returns false, if connection should be dropped.
-bool Client::HandleOperation() {
-  OpHeader hdr;
-  if (!RecvUSBIPMsg(fd_, &hdr)) {
-    LOG(ERROR) << "Could not read operation header: " << fd_->StrError();
-    return false;
-  }
-
-  if (hdr.status != 0) {
-    // This really shouldn't happen unless we're already reading random bytes.
-    LOG(ERROR) << "Unexpected request status: " << hdr.status;
-    return false;
-  }
-
-  // USB/IP version is client-driven. Client requires server to support the
-  // version reported by client, so we need to cache it somehow.
-  if (!proto_version_) {
-    proto_version_ = hdr.version;
-    if ((proto_version_ < kMinVersion) || (proto_version_ > kMaxVersion)) {
-      LOG(ERROR) << "Unsupported USB/IP protocol version: " << proto_version_
-                 << ", want: [" << kMinVersion << "-" << kMaxVersion << "].";
-      return false;
-    }
-  } else {
-    // Now that we cache client version, we can use it to verify if we're not
-    // reading random data bytes again. Sort-of like a MAGIC word.
-    if (proto_version_ != hdr.version) {
-      LOG(ERROR) << "Inconsistent USB/IP version support reported by client; "
-                 << "I've seen " << proto_version_
-                 << ", and now i see: " << hdr.version
-                 << ". Client is not sane. Disconnecting.";
-      return false;
-    }
-  }
-
-  // Protocol itself. Behold.
-  switch (hdr.command) {
-    case kUsbIpOpReqDevList:
-      return HandleListOp();
-
-    case kUsbIpOpReqImport:
-      return HandleImportOp();
-
-    default:
-      LOG(WARNING) << "Ignoring unknown command: " << hdr.command;
-      // Drop connection at this point. Client may attempt to send some request
-      // data after header, and we risk interpreting this as another OP.
-      return false;
-  }
-}
-
-// Handle incoming DEVICE LIST OPERATION.
-//
-// Send list of (virtual) devices attached to this USB/IP server.
-// Returns false, if connection should be dropped.
-bool Client::HandleListOp() {
-  LOG(INFO) << "Client requests device list";
-  // NOTE: Device list Request is currently empty. Do not attempt to read.
-
-  // Send command header
-  OpHeader op{};
-  op.version = proto_version_;
-  op.command = kUsbIpOpRepDevList;
-  op.status = 0;
-  if (!SendUSBIPMsg(fd_, op)) {
-    LOG(ERROR) << "Could not send device list header: " << fd_->StrError();
-    return false;
-  }
-
-  // Send devlist header
-  OpRepDeviceListInfo rep{};
-  rep.num_exported_devices = pool_.Size();
-  if (!SendUSBIPMsg(fd_, rep)) {
-    LOG(ERROR) << "Could not send device list header: " << fd_->StrError();
-    return false;
-  }
-
-  // Send device reports.
-  for (const auto& pair : pool_) {
-    OpRepDeviceInfo device;
-    BuildDeviceNode(pair.first, *pair.second, &device);
-    if (!SendUSBIPMsg(fd_, device)) {
-      LOG(ERROR) << "Could not send device list node: " << fd_->StrError();
-      return false;
-    }
-
-    OpRepInterfaceInfo repif;
-    // Interfaces are ligth. Copying value is easier than dereferencing
-    // reference.
-    for (auto iface : pair.second->interfaces) {
-      repif.iface_class = iface.iface_class;
-      repif.iface_subclass = iface.iface_subclass;
-      repif.iface_protocol = iface.iface_protocol;
-      if (!SendUSBIPMsg(fd_, repif)) {
-        LOG(ERROR) << "Could not send device list interface: "
-                   << fd_->StrError();
-        return false;
-      }
-    }
-  }
-
-  LOG(INFO) << "Device list sent.";
-  return true;
-}
-
-// Handle incoming IMPORT OPERATION.
-//
-// Attach device to remote host. Flip internal state machine to start processing
-// COMMANDs.
-// Returns false, if connection should be dropped.
-bool Client::HandleImportOp() {
-  // Request contains BUS ID
-  OpReqRepBusId req;
-  if (!RecvUSBIPMsg(fd_, &req)) {
-    LOG(ERROR) << "Could not read op import data: " << fd_->StrError();
-    return false;
-  }
-  LOG(INFO) << "Client requests device import for bus" << req;
-
-  // Craft response header.
-  OpHeader op{};
-  op.version = proto_version_;
-  op.command = kUsbIpOpRepImport;
-  op.status = 0;
-
-  Device* device = nullptr;
-  DevicePool::BusDevNumber dn;
-
-  // Find requested device.
-  if (ParseBusID(req, &dn)) {
-    device = pool_.GetDevice(dn);
-    if (!device || !device->handle_attach()) {
-      op.status = 1;
-      LOG(ERROR) << "Import failed; No device registered on bus " << req;
-    }
-  } else {
-    LOG(ERROR) << "Could not parse BUS ID: " << req;
-    op.status = 1;
-  }
-
-  // Craft response data, if device was found.
-  OpRepDeviceInfo rep{};
-  if (device) {
-    BuildDeviceNode(dn, *device, &rep);
-  }
-
-  // Send response header.
-  if (!SendUSBIPMsg(fd_, op)) {
-    LOG(ERROR) << "Could not send import header: " << fd_->StrError();
-    return false;
-  }
-
-  // Send response data, if header indicates success.
-  if (!op.status) {
-    if (!SendUSBIPMsg(fd_, rep)) {
-      LOG(ERROR) << "Could not send import body: " << fd_->StrError();
-      return false;
-    }
-    attached_ = true;
-    LOG(INFO) << "Virtual USB attach successful.";
-  }
-
-  return true;
-}
-
 // Handle incoming COMMAND.
 //
 // Read next CMD from client channel.
 // Returns false, if connection should be dropped.
-bool Client::HandleCommand() {
+bool Client::HandleIncomingMessage() {
   CmdHeader hdr;
   if (!RecvUSBIPMsg(fd_, &hdr)) {
     LOG(ERROR) << "Could not read command header: " << fd_->StrError();
diff --git a/vadb/usbip/client.h b/vadb/usbip/client.h
index d212817..f361260 100644
--- a/vadb/usbip/client.h
+++ b/vadb/usbip/client.h
@@ -37,32 +37,9 @@
   // that this instance should no longer be used.
   bool HandleIncomingMessage();
 
-  // SetAttached instructs the client to skip the introduction and go
-  // directly to execution phase.
-  // This means we won't be executing USB/IP operations (that are only part of
-  // the tool) and go directly to USB/IP commands (which are sent by the
-  // kernel).
-  void SetAttached(bool is_attached) { attached_ = is_attached; }
-
   const avd::SharedFD& fd() const { return fd_; }
 
  private:
-  // Process messages that are valid only while client is detached.
-  // Returns false, if conversation was unsuccessful.
-  bool HandleOperation();
-
-  // Process messages that are valid only while client is attached.
-  // Returns false, if connection should be dropped.
-  bool HandleCommand();
-
-  // List remote USB devices.
-  // Returns false, if connection should be dropped.
-  bool HandleListOp();
-
-  // Attach virtual USB devices to remote host.
-  // Returns false, if connection should be dropped.
-  bool HandleImportOp();
-
   // Execute command on USB device.
   // Returns false, if connection should be dropped.
   bool HandleSubmitCmd(const CmdHeader& hdr);
@@ -79,10 +56,6 @@
   const DevicePool& pool_;
   avd::SharedFD fd_;
 
-  // True, if client requested USB device attach.
-  bool attached_ = false;
-  uint16_t proto_version_ = 0;
-
   Client(const Client&) = delete;
   Client& operator=(const Client&) = delete;
 };
diff --git a/vadb/usbip/messages.cpp b/vadb/usbip/messages.cpp
index 962905c..0c57023 100644
--- a/vadb/usbip/messages.cpp
+++ b/vadb/usbip/messages.cpp
@@ -63,11 +63,6 @@
 }
 
 template <>
-void NetToHost(Operation* t) {
-  *t = static_cast<Operation>(ntohs(*t));
-}
-
-template <>
 void NetToHost(CmdHeader* t) {
   NetToHost(&t->command);
   NetToHost(&t->seq_num);
@@ -87,16 +82,6 @@
 }
 
 template <>
-void NetToHost(OpHeader* t) {
-  NetToHost(&t->version);
-  NetToHost(&t->command);
-  NetToHost(&t->status);
-}
-
-template <>
-void NetToHost(OpReqRepBusId* t) {}
-
-template <>
 void NetToHost(CmdReqUnlink* t) {
   NetToHost(&t->seq_num);
 }
@@ -122,11 +107,6 @@
 }
 
 template <>
-void HostToNet(Operation* t) {
-  *t = static_cast<Operation>(htons(*t));
-}
-
-template <>
 void HostToNet(CmdHeader* t) {
   HostToNet(&t->command);
   HostToNet(&t->seq_num);
@@ -146,62 +126,12 @@
 }
 
 template <>
-void HostToNet(OpHeader* t) {
-  HostToNet(&t->version);
-  HostToNet(&t->command);
-  HostToNet(&t->status);
-}
-
-template <>
-void HostToNet(OpRepDeviceListInfo* t) {
-  HostToNet(&t->num_exported_devices);
-}
-
-template <>
-void HostToNet(OpRepDeviceInfo* t) {
-  HostToNet(&t->bus_num);
-  HostToNet(&t->dev_num);
-  HostToNet(&t->speed);
-
-  // Note: The following should not be rotated when exporting host USB devices.
-  // We only rotate these here because we are using native endian everywhere.
-  HostToNet(&t->id_vendor);
-  HostToNet(&t->id_product);
-  HostToNet(&t->bcd_device);
-}
-
-template <>
 void HostToNet(CmdRepUnlink* t) {
   HostToNet(&t->status);
 }
 
-template <>
-void HostToNet(OpRepInterfaceInfo* t) {}
-
 }  // namespace internal
 
-// Output and diagnostic functionality.
-std::ostream& operator<<(std::ostream& out, Operation op) {
-  switch (op) {
-    case kUsbIpOpReqDevList:
-      out << "OpReqDevList";
-      break;
-    case kUsbIpOpRepDevList:
-      out << "OpRepDevList";
-      break;
-    case kUsbIpOpReqImport:
-      out << "OpReqImport";
-      break;
-    case kUsbIpOpRepImport:
-      out << "OpRepImport";
-      break;
-    default:
-      out << "UNKNOWN (" << int(op) << ")";
-      break;
-  }
-  return out;
-}
-
 std::ostream& operator<<(std::ostream& out, const CmdHeader& header) {
   out << "CmdHeader\n";
   out << "\t\tcmd:\t" << header.command << '\n';
@@ -258,46 +188,5 @@
   return out;
 }
 
-std::ostream& operator<<(std::ostream& out, const OpHeader& header) {
-  out << "OpHeader\n";
-  out << "\t\tvrsn:\t" << std::hex << header.version << '\n';
-  out << "\t\tcmd:\t" << header.command << '\n';
-  out << "\t\tstatus:\t" << header.status << std::dec << '\n';
-  return out;
-}
-
-std::ostream& operator<<(std::ostream& out, const OpRepDeviceInfo& import) {
-  out << "OpRepDeviceInfo\n";
-  out << "\t\tsysfs:\t" << import.usb_path << '\n';
-  out << "\t\tbusid:\t" << import.bus_id << '\n';
-  out << "\t\tbus#:\t" << import.bus_num << '\n';
-  out << "\t\tdev#:\t" << import.dev_num << '\n';
-  out << "\t\tspeed:\t" << import.speed << '\n';
-  out << "\t\tvendor:\t" << std::hex << import.id_vendor << std::dec << '\n';
-  out << "\t\tprodct:\t" << std::hex << import.id_product << std::dec << '\n';
-  out << "\t\trel:\t" << std::hex << import.bcd_device << std::dec << '\n';
-  out << "\t\tcls:\t" << int(import.device_class) << '\n';
-  out << "\t\tsubcls:\t" << int(import.device_subclass) << '\n';
-  out << "\t\tproto:\t" << int(import.device_protocol) << '\n';
-  out << "\t\tcfg#:\t" << int(import.configuration_value) << '\n';
-  out << "\t\tcfgs#:\t" << int(import.num_configurations) << '\n';
-  out << "\t\tifs#:\t" << int(import.num_interfaces) << '\n';
-  return out;
-}
-
-std::ostream& operator<<(std::ostream& out, const OpRepDeviceListInfo& list) {
-  out << "OpRepDeviceListInfo\n";
-  out << "\t\tcount:\t" << list.num_exported_devices << '\n';
-  return out;
-}
-
-std::ostream& operator<<(std::ostream& out, const OpRepInterfaceInfo& i) {
-  out << "OpRepDevListIface\n";
-  out << "\t\tcls:\t" << int(i.iface_class) << '\n';
-  out << "\t\tsubcls:\t" << int(i.iface_subclass) << '\n';
-  out << "\t\tproto:\t" << int(i.iface_protocol) << '\n';
-  return out;
-}
-
 }  // namespace usbip
 }  // namespace vadb
diff --git a/vadb/usbip/messages.h b/vadb/usbip/messages.h
index c8e8e4a..6bf8651 100644
--- a/vadb/usbip/messages.h
+++ b/vadb/usbip/messages.h
@@ -32,14 +32,6 @@
 void NetToHost(T* data);
 }  // namespace internal
 
-// This is the range of USB/IP versions in which we should be safe to operate.
-// USB/IP expects (and the expectation is strong) that the version reported by
-// server is *same* as version reported by client, so we have to mock this for
-// every client.
-// TODO(ender): find if this is documented anywhere.
-constexpr int kMinVersion = 0x100;  // 1.0.0
-constexpr int kMaxVersion = 0x111;  // 1.1?.1?
-
 // Send message to USB/IP client.
 // Accept data by value and modify it to match net endian locally.
 // Returns true, if message was sent successfully.
@@ -62,83 +54,6 @@
 }
 
 ////////////////////////////////////////////////////////////////////////////////
-// OPERATIONS
-////////////////////////////////////////////////////////////////////////////////
-
-// Operation numbers. Operations are valid only when USB device is detached.
-enum Operation : uint16_t {
-  // Request import (~attach) USB device. Request data format:
-  // - OpReqRepBusId - describing BUS ID.
-  kUsbIpOpReqImport = 0x8003,
-
-  // Import (~attach) response. Response format:
-  // - OpRepDeviceInfo - USBIP device descriptor.
-  kUsbIpOpRepImport = 3,
-
-  // Request list available devices. No request data.
-  kUsbIpOpReqDevList = 0x8005,
-
-  // Device list response. Response format:
-  // - OpRepDeviceListInfo - specifies number of device list reports that follow
-  //   (n),
-  // - n * OpRepDeviceInfo - USBIP device descriptor, including # interfaces
-  //   (m),
-  // - m * OpRepInterfaceInfo - for every OpRepDeviceInfo, list of interfaces.
-  kUsbIpOpRepDevList = 5,
-};
-
-// Header precedes all OPERATION requests and responses.
-// Header does NOT precede COMMAND requests and responses.
-struct OpHeader {
-  uint16_t version;   // BCD. Server must obey client, not the other way around.
-  Operation command;  // Request or response type.
-  uint32_t status;    // Status; 0 = ok, 1 = error.
-};
-
-// OPERATION request/response body is essentially several structures glued
-// together. Because half of these messages are nested arrays of arbitrary
-// lengths each, we can't define a single structure explaining full request or
-// response body. Instead we will define components that, when combined,
-// constitute this body.
-//
-// OpReqRepBusId functions both as a device info field and request body.
-using OpReqRepBusId = char[32];
-
-// OpRepDeviceListInfo is a header preceding an array of OpRepDeviceInfo devices
-// offered by this server.
-struct OpRepDeviceListInfo {
-  uint32_t num_exported_devices;
-} __attribute__((packed));
-
-// OpRepDeviceInfo is used both as a partial response to OpReqDeviceList and
-// OpReqImport. Depending on operation type it may or may not be followed by an
-// array of OpRepInterfaceInfo interfaces this device exports.
-struct OpRepDeviceInfo {
-  char usb_path[256];
-  OpReqRepBusId bus_id;
-  uint32_t bus_num;
-  uint32_t dev_num;
-  uint32_t speed;
-  uint16_t id_vendor;
-  uint16_t id_product;
-  uint16_t bcd_device;
-  uint8_t device_class;
-  uint8_t device_subclass;
-  uint8_t device_protocol;
-  uint8_t configuration_value;
-  uint8_t num_configurations;
-  uint8_t num_interfaces;
-} __attribute__((packed));
-
-// OpRepInterfaceInfo lists interface details of a particular USB device.
-struct OpRepInterfaceInfo {
-  uint8_t iface_class;
-  uint8_t iface_subclass;
-  uint8_t iface_protocol;
-  uint8_t reserved;
-} __attribute__((packed));
-
-////////////////////////////////////////////////////////////////////////////////
 // COMMANDS
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -210,11 +125,6 @@
 } __attribute__((packed));
 
 // Diagnostics.
-std::ostream& operator<<(std::ostream& out, Operation op);
-std::ostream& operator<<(std::ostream& out, const OpHeader& header);
-std::ostream& operator<<(std::ostream& out, const OpRepDeviceInfo& data);
-std::ostream& operator<<(std::ostream& out, const OpRepDeviceListInfo& list);
-std::ostream& operator<<(std::ostream& out, const OpRepInterfaceInfo& i);
 std::ostream& operator<<(std::ostream& out, const CmdHeader& header);
 std::ostream& operator<<(std::ostream& out, const CmdReqSubmit& data);
 std::ostream& operator<<(std::ostream& out, const CmdRepSubmit& data);
diff --git a/vadb/usbip/server.cpp b/vadb/usbip/server.cpp
index 960925e..3c9cd00 100644
--- a/vadb/usbip/server.cpp
+++ b/vadb/usbip/server.cpp
@@ -86,7 +86,6 @@
   }
 
   clients_.emplace_back(device_pool_, client);
-  clients_.back().SetAttached(init_attached_state_);
 }
 }  // namespace usbip
 }  // namespace vadb
diff --git a/vadb/usbip/server.h b/vadb/usbip/server.h
index 83fded5..7bcb076 100644
--- a/vadb/usbip/server.h
+++ b/vadb/usbip/server.h
@@ -38,13 +38,6 @@
   // exchange.
   void Serve();
 
-  // StartAttachedByDefault tells clients to skip introduction and query phase
-  // and go directly to command execution phase. This is particularly useful if
-  // we want to make the stack automatic.
-  void SetClientsAttachedByDefault(bool is_attached) {
-    init_attached_state_ = is_attached;
-  }
-
  private:
   // Create USBIP server socket.
   // Returns true, if socket was successfully created.
@@ -54,11 +47,10 @@
   // New clients will be appended to clients_ list.
   void HandleIncomingConnection();
 
-std::string name_;
+  std::string name_;
   avd::SharedFD server_;
   std::list<Client> clients_;
   const DevicePool& device_pool_;
-  bool init_attached_state_ = false;
 
   Server(const Server&) = delete;
   Server& operator=(const Server&) = delete;