View Javadoc
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.demo.client;
19  
20  import java.io.FileDescriptor;
21  import java.io.FileInputStream;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.net.Socket;
25  
26  import org.newsclub.net.unix.AFUNIXSocket;
27  
28  import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
29  
30  /**
31   * A client that reads the contents of file descriptors that are sent as ancillary messages.
32   *
33   * The actual in-band data that is received is silently ignored.
34   */
35  public class ReadFileHandleClient extends DemoClientBase {
36    @Override
37    protected void handleSocket(Socket socket) throws IOException {
38      if (!(socket instanceof AFUNIXSocket)) {
39        throw new UnsupportedOperationException("File handles can only be sent via UNIX sockets");
40      }
41      handleSocket((AFUNIXSocket) socket);
42    }
43  
44    @SuppressFBWarnings("NCR_NOT_PROPERLY_CHECKED_READ")
45    protected void handleSocket(AFUNIXSocket socket) throws IOException {
46      // set to a reasonable size
47      socket.setAncillaryReceiveBufferSize(1024);
48  
49      try (InputStream in = socket.getInputStream()) {
50        byte[] buf = new byte[socket.getReceiveBufferSize()];
51  
52        while (in.read(buf) != -1) {
53          FileDescriptor[] descriptors = socket.getReceivedFileDescriptors();
54          if (descriptors != null) {
55            for (FileDescriptor fd : descriptors) {
56              handleFileDescriptor(fd);
57            }
58          }
59        }
60      }
61    }
62  
63    private void handleFileDescriptor(FileDescriptor fd) throws IOException {
64      try (FileInputStream fin = new FileInputStream(fd)) {
65        byte[] buf = new byte[4096];
66        int read;
67        while ((read = fin.read(buf)) != -1) {
68          System.out.write(buf, 0, read);
69        }
70        System.out.flush();
71      }
72    }
73  }