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