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