-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalServerSocket.java
More file actions
303 lines (244 loc) · 12.5 KB
/
Copy pathLocalServerSocket.java
File metadata and controls
303 lines (244 loc) · 12.5 KB
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
package com.termux.shared.net.socket.local;
import androidx.annotation.NonNull;
import com.termux.shared.errors.Error;
import com.termux.shared.file.FileUtils;
import com.termux.shared.jni.models.JniResult;
import com.termux.shared.logger.Logger;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/** The server socket for {@link LocalSocketManager}. */
public class LocalServerSocket implements Closeable {
public static final String LOG_TAG = "LocalServerSocket";
/** The {@link LocalSocketManager} instance for the local socket. */
@NonNull protected final LocalSocketManager mLocalSocketManager;
/** The {@link LocalSocketRunConfig} containing run config for the {@link LocalServerSocket}. */
@NonNull protected final LocalSocketRunConfig mLocalSocketRunConfig;
/** The {@link ILocalSocketManager} client for the {@link LocalSocketManager}. */
@NonNull protected final ILocalSocketManager mLocalSocketManagerClient;
/** The {@link ClientSocketListener} {@link Thread} for the {@link LocalServerSocket}. */
@NonNull protected final Thread mClientSocketListener;
/**
* The required permissions for server socket file parent directory.
* Creation of a new socket will fail if the server starter app process does not have
* write and search (execute) permission on the directory in which the socket is created.
*/
public static final String SERVER_SOCKET_PARENT_DIRECTORY_PERMISSIONS = "rwx"; // Default: "rwx"
/**
* Create an new instance of {@link LocalServerSocket}.
*
* @param localSocketManager The {@link #mLocalSocketManager} value.
*/
protected LocalServerSocket(@NonNull LocalSocketManager localSocketManager) {
mLocalSocketManager = localSocketManager;
mLocalSocketRunConfig = localSocketManager.getLocalSocketRunConfig();
mLocalSocketManagerClient = mLocalSocketRunConfig.getLocalSocketManagerClient();
mClientSocketListener = new Thread(new ClientSocketListener());
}
/** Start server by creating server socket. */
public synchronized Error start() {
Logger.logDebug(LOG_TAG, "start");
String path = mLocalSocketRunConfig.getPath();
if (path == null || path.isEmpty()) {
return LocalSocketErrno.ERRNO_SERVER_SOCKET_PATH_NULL_OR_EMPTY.getError(mLocalSocketRunConfig.getTitle());
}
if (!mLocalSocketRunConfig.isAbstractNamespaceSocket()) {
path = FileUtils.getCanonicalPath(path, null);
}
// On Linux, sun_path is 108 bytes (UNIX_PATH_MAX) in size, so do an early check here to
// prevent useless parent directory creation since createServerSocket() call will fail since
// there is a native check as well.
if (path.getBytes(StandardCharsets.UTF_8).length > 108) {
return LocalSocketErrno.ERRNO_SERVER_SOCKET_PATH_TOO_LONG.getError(mLocalSocketRunConfig.getTitle(), path);
}
int backlog = mLocalSocketRunConfig.getBacklog();
if (backlog <= 0) {
return LocalSocketErrno.ERRNO_SERVER_SOCKET_BACKLOG_INVALID.getError(mLocalSocketRunConfig.getTitle(), backlog);
}
Error error;
// If server socket is not in abstract namespace
if (!mLocalSocketRunConfig.isAbstractNamespaceSocket()) {
if (!path.startsWith("/"))
return LocalSocketErrno.ERRNO_SERVER_SOCKET_PATH_NOT_ABSOLUTE.getError(mLocalSocketRunConfig.getTitle(), path);
// Create the server socket file parent directory and set SERVER_SOCKET_PARENT_DIRECTORY_PERMISSIONS if missing
String socketParentPath = new File(path).getParent();
error = FileUtils.validateDirectoryFileExistenceAndPermissions(mLocalSocketRunConfig.getTitle() + " server socket file parent",
socketParentPath,
null, true,
SERVER_SOCKET_PARENT_DIRECTORY_PERMISSIONS, true, true,
false, false);
if (error != null)
return error;
// Delete the server socket file to stop any existing servers and for bind() to succeed
error = deleteServerSocketFile();
if (error != null)
return error;
}
// Create the server socket
JniResult result = LocalSocketManager.createServerSocket(mLocalSocketRunConfig.getLogTitle() + " (server)",
path.getBytes(StandardCharsets.UTF_8), backlog);
if (result == null || result.retval != 0) {
return LocalSocketErrno.ERRNO_CREATE_SERVER_SOCKET_FAILED.getError(mLocalSocketRunConfig.getTitle(), JniResult.getErrorString(result));
}
int fd = result.intData;
if (fd < 0) {
return LocalSocketErrno.ERRNO_SERVER_SOCKET_FD_INVALID.getError(fd, mLocalSocketRunConfig.getTitle());
}
// Update fd to signify that server socket has been created successfully
mLocalSocketRunConfig.setFD(fd);
mClientSocketListener.setUncaughtExceptionHandler(mLocalSocketManager.getLocalSocketManagerClientThreadUEH());
try {
// Start listening to server clients
mClientSocketListener.start();
} catch (Exception e) {
Logger.logStackTraceWithMessage(LOG_TAG, "mClientSocketListener start failed", e);
}
return null;
}
/** Stop server. */
public synchronized Error stop() {
Logger.logDebug(LOG_TAG, "stop");
try {
// Stop the LocalClientSocket listener.
mClientSocketListener.interrupt();
} catch (Exception ignored) {}
Error error = closeServerSocket(false);
if (error != null)
return error;
return deleteServerSocketFile();
}
/** Close server socket. */
public synchronized Error closeServerSocket(boolean logErrorMessage) {
Logger.logDebug(LOG_TAG, "closeServerSocket");
try {
close();
} catch (IOException e) {
Error error = LocalSocketErrno.ERRNO_CLOSE_SERVER_SOCKET_FAILED_WITH_EXCEPTION.getError(e, mLocalSocketRunConfig.getTitle(), e.getMessage());
if (logErrorMessage)
Logger.logErrorExtended(LOG_TAG, error.getErrorLogString());
return error;
}
return null;
}
/** Implementation for {@link Closeable#close()} to close server socket. */
@Override
public synchronized void close() throws IOException {
Logger.logDebug(LOG_TAG, "close");
int fd = mLocalSocketRunConfig.getFD();
if (fd >= 0) {
JniResult result = LocalSocketManager.closeSocket(mLocalSocketRunConfig.getLogTitle() + " (server)", fd);
if (result == null || result.retval != 0) {
throw new IOException(JniResult.getErrorString(result));
}
// Update fd to signify that server socket has been closed
mLocalSocketRunConfig.setFD(-1);
}
}
/**
* Delete server socket file if not an abstract namespace socket. This will cause any existing
* running server to stop.
*/
private Error deleteServerSocketFile() {
if (!mLocalSocketRunConfig.isAbstractNamespaceSocket())
return FileUtils.deleteSocketFile(mLocalSocketRunConfig.getTitle() + " server socket file", mLocalSocketRunConfig.getPath(), true);
else
return null;
}
/** Listen and accept new {@link LocalClientSocket}. */
public LocalClientSocket accept() {
Logger.logVerbose(LOG_TAG, "accept");
int clientFD;
while (true) {
// If server socket closed
int fd = mLocalSocketRunConfig.getFD();
if (fd < 0) {
return null;
}
JniResult result = LocalSocketManager.accept(mLocalSocketRunConfig.getLogTitle() + " (client)", fd);
if (result == null || result.retval != 0) {
mLocalSocketManager.onError(
LocalSocketErrno.ERRNO_ACCEPT_CLIENT_SOCKET_FAILED.getError(mLocalSocketRunConfig.getTitle(), JniResult.getErrorString(result)));
continue;
}
clientFD = result.intData;
if (clientFD < 0) {
mLocalSocketManager.onError(
LocalSocketErrno.ERRNO_CLIENT_SOCKET_FD_INVALID.getError(clientFD, mLocalSocketRunConfig.getTitle()));
continue;
}
PeerCred peerCred = new PeerCred();
result = LocalSocketManager.getPeerCred(mLocalSocketRunConfig.getLogTitle() + " (client)", clientFD, peerCred);
if (result == null || result.retval != 0) {
mLocalSocketManager.onError(
LocalSocketErrno.ERRNO_GET_CLIENT_SOCKET_PEER_UID_FAILED.getError(mLocalSocketRunConfig.getTitle(), JniResult.getErrorString(result)));
LocalClientSocket.closeClientSocket(mLocalSocketManager, clientFD);
continue;
}
int peerUid = peerCred.uid;
if (peerUid < 0) {
mLocalSocketManager.onError(
LocalSocketErrno.ERRNO_CLIENT_SOCKET_PEER_UID_INVALID.getError(peerUid, mLocalSocketRunConfig.getTitle()));
LocalClientSocket.closeClientSocket(mLocalSocketManager, clientFD);
continue;
}
LocalClientSocket clientSocket = new LocalClientSocket(mLocalSocketManager, clientFD, peerCred);
Logger.logVerbose(LOG_TAG, "Client socket accept for \"" + mLocalSocketRunConfig.getTitle() + "\" server\n" + clientSocket.getLogString());
// Only allow connection if the peer has the same uid as server app's user id or root user id
if (peerUid != mLocalSocketManager.getContext().getApplicationInfo().uid && peerUid != 0) {
mLocalSocketManager.onDisallowedClientConnected(clientSocket,
LocalSocketErrno.ERRNO_CLIENT_SOCKET_PEER_UID_DISALLOWED.getError(clientSocket.getPeerCred().getMinimalString(),
mLocalSocketManager.getLocalSocketRunConfig().getTitle()));
clientSocket.closeClientSocket(true);
continue;
}
return clientSocket;
}
}
/** The {@link LocalClientSocket} listener {@link java.lang.Runnable} for {@link LocalServerSocket}. */
protected class ClientSocketListener implements Runnable {
@Override
public void run() {
try {
Logger.logVerbose(LOG_TAG, "ClientSocketListener start");
while (!Thread.currentThread().isInterrupted()) {
LocalClientSocket clientSocket = null;
try {
// Listen for new client socket connections
clientSocket = null;
clientSocket = accept();
// If server socket is closed, then stop listener thread.
if (clientSocket == null)
break;
Error error;
error = clientSocket.setReadTimeout();
if (error != null) {
mLocalSocketManager.onError(clientSocket, error);
clientSocket.closeClientSocket(true);
continue;
}
error = clientSocket.setWriteTimeout();
if (error != null) {
mLocalSocketManager.onError(clientSocket, error);
clientSocket.closeClientSocket(true);
continue;
}
// Start new thread for client logic and pass control to ILocalSocketManager implementation
mLocalSocketManager.onClientAccepted(clientSocket);
} catch (Throwable t) {
mLocalSocketManager.onError(clientSocket,
LocalSocketErrno.ERRNO_CLIENT_SOCKET_LISTENER_FAILED_WITH_EXCEPTION.getError(t, mLocalSocketRunConfig.getTitle(), t.getMessage()));
if (clientSocket != null)
clientSocket.closeClientSocket(true);
}
}
} catch (Exception ignored) {
} finally {
try {
close();
} catch (Exception ignored) {}
}
Logger.logVerbose(LOG_TAG, "ClientSocketListener end");
}
}
}