[webrtc] React to input socket disconnecting

When crosvm exits and starts again it attempts to connect to the input
sockets. WebRTC only accepts the connection if it doesn't have a
vmm already connected. This change allows it to react immediately to
the vmm process exiting and get ready to accept the new connection
when it restarts.

Bug: 148998856
Test: locally, adb reboot, check cvd reacts to mouse events
Change-Id: Ibb5946702ac633638bf464975bba5db4c046f513
diff --git a/host/frontend/gcastv2/libsource/InputSink.cpp b/host/frontend/gcastv2/libsource/InputSink.cpp
index e673358..ce9597d 100644
--- a/host/frontend/gcastv2/libsource/InputSink.cpp
+++ b/host/frontend/gcastv2/libsource/InputSink.cpp
@@ -123,6 +123,8 @@
       makeFdNonblocking(s);
 
       mClientFd = s;
+      mRunLoop->postSocketRecv(
+        mClientFd, makeSafeCallback(this, &InputSink::onSocketRecv));
     }
   }
 
@@ -151,6 +153,27 @@
   }
 }
 
+void InputSink::onSocketRecv() {
+  if (mClientFd < 0) return;
+
+  char buff[512];
+  auto n = recv(mClientFd, buff, sizeof(buff), 0 /* flags */);
+  if (n > 0) {
+    LOG(INFO) << "Discarding " << n << " bytes received from the input device.";
+    mRunLoop->postSocketRecv(
+        mClientFd, makeSafeCallback(this, &InputSink::onSocketRecv));
+  } else {
+    // Client disconnected
+    if (n < 0) {
+      auto errno_save = errno;
+      LOG(ERROR) << "Error receiving from socket: " << strerror(errno_save);
+    }
+    mRunLoop->cancelSocket(mClientFd);
+    close(mClientFd);
+    mClientFd = -1;
+  }
+}
+
 void InputSink::onSocketSend() {
   std::lock_guard autoLock(mLock);
 
diff --git a/host/frontend/gcastv2/libsource/include/source/InputSink.h b/host/frontend/gcastv2/libsource/include/source/InputSink.h
index ba5af91..38af13b 100644
--- a/host/frontend/gcastv2/libsource/include/source/InputSink.h
+++ b/host/frontend/gcastv2/libsource/include/source/InputSink.h
@@ -54,6 +54,7 @@
   bool mWriteVirtioInput;
 
   void onServerConnection();
+  void onSocketRecv();
   void onSocketSend();
 
   void sendRawEvents(const void* evt_buffer, size_t length);