Add port-generic options to SharedFD vsockets

This allows creating vsocket servers at arbitrary open ports, and
retrieving the automatically assigned port numbers.

Bug: 145247175
Test: Builds
Change-Id: I5051645b7eccfd2bda4d861ca749aa1e6db946d7
diff --git a/common/libs/fs/shared_fd.cpp b/common/libs/fs/shared_fd.cpp
index 82baad3..2f6d100 100644
--- a/common/libs/fs/shared_fd.cpp
+++ b/common/libs/fs/shared_fd.cpp
@@ -421,6 +421,10 @@
   return vsock;
 }
 
+SharedFD SharedFD::VsockServer(int type) {
+  return VsockServer(VMADDR_PORT_ANY, type);
+}
+
 SharedFD SharedFD::VsockClient(unsigned int cid, unsigned int port, int type) {
   auto vsock = cvd::SharedFD::Socket(AF_VSOCK, type, 0);
   if (!vsock->IsOpen()) {
diff --git a/common/libs/fs/shared_fd.h b/common/libs/fs/shared_fd.h
index 99deef1..eec17b1 100644
--- a/common/libs/fs/shared_fd.h
+++ b/common/libs/fs/shared_fd.h
@@ -157,6 +157,7 @@
   static SharedFD SocketSeqPacketServer(const char* name, mode_t mode);
   static SharedFD SocketSeqPacketClient(const char* name);
   static SharedFD VsockServer(unsigned int port, int type);
+  static SharedFD VsockServer(int type);
   static SharedFD VsockClient(unsigned int cid, unsigned int port, int type);
   static SharedFD TimerFD(int clock, int flags);
 
@@ -292,6 +293,22 @@
     return rval;
   }
 
+  int GetSockName(struct sockaddr* addr, socklen_t* addrlen) {
+    errno = 0;
+    int rval = TEMP_FAILURE_RETRY(getsockname(fd_, addr, addrlen));
+    if (rval == -1) {
+      errno_ = errno;
+    }
+    return rval;
+  }
+
+  unsigned int VsockServerPort() {
+    struct sockaddr_vm vm_socket;
+    socklen_t length = sizeof(vm_socket);
+    GetSockName(reinterpret_cast<struct sockaddr*>(&vm_socket), &length);
+    return vm_socket.svm_port;
+  }
+
   void Identify(const char* identity);
 
   int Ioctl(int request, void* val = nullptr) {