forked from mcfunley/juds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnixDomainSocket.java
358 lines (302 loc) · 10.6 KB
/
UnixDomainSocket.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package com.etsy.net;
// UnixDomainSocket.java
// Inspired by J-BUDS version 1.0
// See COPYRIGHT file for license details
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URISyntaxException;
/**
*
* This class provides a means of using Unix domain socket client/server
* connections in Java
*
* @author Klaus Trainer
*/
public abstract class UnixDomainSocket {
// system property holding the preferred folder for copying the lib file to
private static final String LIB_TARGET = "juds.folder.preferred";
private static File jarFile;
static {
// Load the Unix domain socket C library
getJarPath();
try {
loadNativeLib();
} catch (IOException ioe) {
throwLink(ioe);
}
}
private static void getJarPath() {
try {
jarFile = new File(JUDS.jarURL.toURI());
} catch(URISyntaxException e) {
throwLink(e);
}
}
private static void loadNativeLib() throws IOException {
File lib = getNativeLibTarget();
if(!lib.exists() || jarNewer(lib)) {
try {
extractNativeLib(lib);
if(!lib.exists()) {
throwLink("The native library was not extracted");
}
} catch(IOException e) {
throwLink(e);
} catch(URISyntaxException e) {
throwLink(e);
}
}
String path = "";
try {
path = lib.getCanonicalPath();
} catch(IOException e) {
throwLink(e);
}
System.load(path);
}
private static Boolean jarNewer(File lib) {
return lib.lastModified() < jarFile.lastModified();
}
private static void throwLink(Throwable e) {
throwLink(e.toString());
}
private static void throwLink(String s) {
throw new UnsatisfiedLinkError(s);
}
private static File getNativeLibTarget() throws IOException {
String p = platform();
String ext = "darwin".equals(p) ? "dylib" : "so";
File tmpdir;
String preferred = System.getProperty(LIB_TARGET);
if (preferred != null) {
tmpdir = new File(preferred);
if(!(tmpdir.isDirectory())) {
throw new IOException("The preffered path is not a folder: " + tmpdir.getAbsolutePath());
}
} else {
tmpdir = File.createTempFile("juds-temp", Long.toString(System.nanoTime()));
if(!(tmpdir.delete())) {
throw new IOException("Could not delete temp file: " + tmpdir.getAbsolutePath());
}
if(!(tmpdir.mkdir())) {
throw new IOException("Could not create temp directory: " + tmpdir.getAbsolutePath());
}
tmpdir.deleteOnExit();
}
String path = String.format("libunixdomainsocket-%s-%s.%s", p, arch(), ext);
File lib = new File(tmpdir, path);
if (preferred == null) {
lib.deleteOnExit();
}
return lib;
}
private static void extractNativeLib(File target)
throws IOException, URISyntaxException {
InputStream in;
// Hadoop extracts the jar into a directory before running the code, so
// check to see if the file is already there, since the .jar extraction
// will fail in this case.
String preExtractedLibPath = jarFile.getCanonicalPath() + "/" + target.getName();
File preExtractedLibFile = new File(preExtractedLibPath);
if (preExtractedLibFile.exists()) {
in = new FileInputStream(preExtractedLibFile);
} else {
JarFile jar = new JarFile(jarFile);
ZipEntry z = jar.getEntry(target.getName());
if(z == null) {
throwLink("Could not find library: "+target.getName());
}
in = jar.getInputStream(z);
}
try {
OutputStream out = new BufferedOutputStream(
new FileOutputStream(target));
try {
byte[] buf = new byte[2048];
for(;;) {
int n = in.read(buf);
if(n < 0) {
break;
}
out.write(buf, 0, n);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
private static String arch() {
String a = System.getProperty("os.arch");
if("amd64".equals(a) || "x86_64".equals(a)) {
return "x86_64";
}
return a;
}
private static String platform() {
String p = System.getProperty("os.name").toLowerCase();
if("mac os x".equals(p)) {
return "darwin";
}
return p;
}
protected UnixDomainSocketInputStream in;
protected UnixDomainSocketOutputStream out;
protected int nativeSocketFileHandle;
// Name of the socket file
protected String socketFile;
protected int socketType;
private int timeout;
// Native methods implemented in the Unix domain socket C library
protected native static int nativeCreate(String socketFile, int socketType);
protected native static int nativeListen(String socketFile, int socketType, int backlog);
protected native static int nativeAccept(int nativeSocketFileHandle, int socketType);
protected native static int nativeOpen(String socketFile, int socketType);
protected native static int nativeRead(int nativeSocketFileHandle,
byte[] b, int off, int len);
protected native static int nativeWrite(int nativeSocketFileHandle,
byte[] b, int off, int len);
protected native static int nativeTimeout(int nativeSocketFileHandle, int milis);
protected native static int nativeClose(int nativeSocketFileHandle);
protected native static int nativeCloseInput(int nativeSocketFileHandle);
protected native static int nativeCloseOutput(int nativeSocketFileHandle);
protected native static int nativeUnlink(String socketFile);
protected UnixDomainSocket()
{
// default constructor
}
protected UnixDomainSocket(int pSocketFileHandle, int pSocketType)
throws IOException
{
nativeSocketFileHandle = pSocketFileHandle;
socketType = pSocketType;
socketFile = null;
// Initialize the socket input and output streams
in = new UnixDomainSocketInputStream();
if (socketType == JUDS.SOCK_STREAM)
out = new UnixDomainSocketOutputStream();
}
/**
* Returns an input stream for this socket.
*
* @return An input stream for reading bytes from this socket
*/
public InputStream getInputStream() {
return (InputStream) in;
}
/**
* Returns an output stream for this socket.
*
* @return An output stream for writing bytes to this socket
*/
public OutputStream getOutputStream() {
return (OutputStream) out;
}
/**
* Sets the read timeout for the socket. If a read call blocks for the
* specified amount of time it will be cancelled, and a
* java.io.InterruptedIOException will be thrown. A <code>timeout</code>
* of zero is interpreted as an infinite timeout.
*
* @param timeout
* The specified timeout, in milliseconds.
*/
@Deprecated
public void setTimeout(int timeout) {
try {
setSoTimeout(timeout);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
@Deprecated
public int getTimeout() {
return getSoTimeout();
}
public void setSoTimeout(int timeout) throws IOException {
if(nativeTimeout(nativeSocketFileHandle, timeout) == -1)
throw new IOException("Unable to configure socket timeout");
this.timeout = timeout;
}
public int getSoTimeout() {
return timeout;
}
/**
* Closes the socket
*/
public void close() {
nativeClose(nativeSocketFileHandle);
}
/**
* Unlink socket file
*/
public void unlink() {
if (socketFile != null)
{
nativeUnlink(socketFile);
}
}
protected class UnixDomainSocketInputStream extends InputStream {
@Override
public int read() throws IOException {
byte[] b = new byte[1];
int count = nativeRead(nativeSocketFileHandle, b, 0, 1);
if (count == -1)
throw new IOException();
return count > 0 ? (int) b[0] & 0xff : -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int count = nativeRead(nativeSocketFileHandle, b, off, len);
if (count == -1)
throw new IOException();
return count > 0 ? count : -1;
}
// Closes the socket input stream
public void close() throws IOException {
nativeCloseInput(nativeSocketFileHandle);
}
}
protected class UnixDomainSocketOutputStream extends OutputStream {
@Override
public void write(int b) throws IOException {
byte[] data = new byte[1];
data[0] = (byte) b;
if (nativeWrite(nativeSocketFileHandle, data, 0, 1) != 1)
throw new IOException("Unable to write to Unix domain socket");
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0)
|| ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
if (nativeWrite(nativeSocketFileHandle, b, off, len) != len)
throw new IOException("Unable to write to Unix domain socket");
}
// Closes the socket output stream
public void close() throws IOException {
nativeCloseOutput(nativeSocketFileHandle);
}
}
}