View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2024 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.demo.server;
19  
20  import java.io.File;
21  import java.io.FileInputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.OutputStream;
25  import java.net.Socket;
26  import java.net.SocketAddress;
27  import java.nio.charset.StandardCharsets;
28  
29  import org.newsclub.net.unix.AFUNIXSocket;
30  
31  /**
32   * A multi-threaded unix socket server that simply reads all input, byte per byte, not doing
33   * anything else with it.
34   *
35   * @author Christian Kohlschütter
36   */
37  @SuppressWarnings("CatchAndPrintStackTrace" /* errorprone */)
38  public final class SendFileHandleServer extends DemoServerBase {
39    private final File file;
40  
41    public SendFileHandleServer(SocketAddress listenAddress, File file) {
42      super(listenAddress);
43      this.file = file;
44    }
45  
46    @Override
47    protected void doServeSocket(Socket socket) throws IOException {
48      if (!(socket instanceof AFUNIXSocket)) {
49        throw new UnsupportedOperationException("File handles can only be sent via UNIX sockets");
50      }
51      doServeSocket((AFUNIXSocket) socket);
52    }
53  
54    private void doServeSocket(AFUNIXSocket socket) throws IOException {
55      try (InputStream is = socket.getInputStream();
56          OutputStream os = socket.getOutputStream();
57          FileInputStream fin = new FileInputStream(file)) {
58        socket.setOutboundFileDescriptors(fin.getFD());
59        os.write("FD sent via ancillary message.".getBytes(StandardCharsets.UTF_8));
60      }
61    }
62  }