1 /*
2 * junixsocket
3 *
4 * Copyright 2009-2026 Christian Kohlschütter
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.newsclub.net.unix.vsock;
19
20 import java.io.IOException;
21 import java.net.Socket;
22 import java.net.SocketException;
23
24 import org.newsclub.net.unix.AFSocketFactory;
25 import org.newsclub.net.unix.AFVSOCKSocketAddress;
26
27 /**
28 * The base for a SocketFactory that connects to VSOCK sockets.
29 */
30 public abstract class AFVSOCKSocketFactory extends AFSocketFactory<AFVSOCKSocketAddress> {
31 /**
32 * Creates a {@link AFVSOCKSocketFactory}.
33 */
34 protected AFVSOCKSocketFactory() {
35 super(AFVSOCKSocketAddress.class);
36 }
37
38 @Override
39 public final Socket createSocket() throws SocketException {
40 return configure(AFVSOCKSocket.newInstance(this));
41 }
42
43 @Override
44 protected final AFVSOCKSocket connectTo(AFVSOCKSocketAddress addr) throws IOException {
45 return configure(AFVSOCKSocket.connectTo(addr));
46 }
47
48 /**
49 * Performs some optional configuration on a newly created socket.
50 *
51 * @param sock The socket.
52 * @return The very socket.
53 * @throws SocketException on error.
54 */
55 protected AFVSOCKSocket configure(AFVSOCKSocket sock) throws SocketException {
56 return sock;
57 }
58
59 /**
60 * Always connects sockets to the given VSOCK type and instance.
61 *
62 * @author Christian Kohlschütter
63 */
64 public static final class FixedAddress extends AFVSOCKSocketFactory {
65 private final AFVSOCKSocketAddress addr;
66
67 /**
68 * Creates an {@link AFVSOCKSocketFactory} that always uses the given VSOCK address.
69 *
70 * @param port The VSOCK port.
71 * @param cid The VSOCK CID.
72 * @throws SocketException on internal error.
73 */
74 public FixedAddress(int port, int cid) throws SocketException {
75 this(AFVSOCKSocketAddress.ofPortAndCID(port, cid));
76 }
77
78 /**
79 * Creates an {@link AFVSOCKSocketFactory} that always uses the given VSOCK address.
80 *
81 * @param addr The address.
82 */
83 public FixedAddress(AFVSOCKSocketAddress addr) {
84 super();
85 this.addr = addr;
86 }
87
88 @Override
89 public AFVSOCKSocketAddress addressFromHost(String host, int javaPort) throws SocketException {
90 return addr;
91 }
92 }
93 }