1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.net;
15
16 import java.io.IOException;
17 import java.lang.reflect.Constructor;
18 import java.net.InetAddress;
19 import java.net.ServerSocket;
20 import java.net.Socket;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.List;
24 import java.util.concurrent.CountDownLatch;
25
26 import javax.net.ServerSocketFactory;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 import ch.qos.logback.classic.LoggerContext;
32 import ch.qos.logback.classic.joran.JoranConfigurator;
33 import ch.qos.logback.core.joran.spi.JoranException;
34 import ch.qos.logback.core.util.IpAddressMatcher;
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 public class SimpleSocketServer extends Thread {
65
66 Logger logger = LoggerFactory.getLogger(SimpleSocketServer.class);
67
68 private final int port;
69 private final LoggerContext lc;
70 private boolean closed = false;
71 private ServerSocket serverSocket;
72 private List<SocketNode> socketNodeList = new ArrayList<SocketNode>();
73
74
75
76
77
78 private final List<IpAddressMatcher> allowedClientAddresses = new ArrayList<IpAddressMatcher>();
79
80
81 private CountDownLatch latch;
82
83 public static void main(String argv[]) throws Exception {
84 doMain(SimpleSocketServer.class, argv);
85 }
86
87 protected static void doMain(Class<? extends SimpleSocketServer> serverClass, String argv[]) throws Exception {
88 if (argv.length < 3) {
89 if (argv.length == 2) {
90 usage("No allowed client IP addresses specified. Please explicitly whitelist client IPs"
91 + " or CIDR ranges on the command line (e.g. 192.168.1.0/24).", serverClass);
92 } else {
93 usage("Wrong number of arguments.", serverClass);
94 }
95 }
96
97 int port = parsePortNumber(argv[0]);
98 String configFile = argv[1];
99 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
100 configureLC(lc, configFile);
101
102 SimpleSocketServer sss = createServer(serverClass, lc, port);
103 for (int i = 2; i < argv.length; i++) {
104 try {
105 sss.addAllowedClientAddress(argv[i]);
106 } catch (IllegalArgumentException e) {
107 usage("Invalid allowed client address [" + argv[i] + "]: " + e.getMessage(), serverClass);
108 }
109 }
110
111
112
113
114 sss.start();
115 }
116
117 private static SimpleSocketServer createServer(Class<? extends SimpleSocketServer> serverClass, LoggerContext lc,
118 int port) throws Exception {
119 Constructor<? extends SimpleSocketServer> constructor = serverClass.getConstructor(LoggerContext.class,
120 int.class);
121 return constructor.newInstance(lc, port);
122 }
123
124 public SimpleSocketServer(LoggerContext lc, int port) {
125 this.lc = lc;
126 this.port = port;
127 }
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142 public void addAllowedClientAddress(String addressOrCidr) {
143 allowedClientAddresses.add(new IpAddressMatcher(addressOrCidr));
144 }
145
146
147
148
149
150
151
152
153
154
155 public void setAllowedClientAddresses(Collection<String> addresses) {
156 allowedClientAddresses.clear();
157 if (addresses == null) {
158 return;
159 }
160 for (String addressOrCidr : addresses) {
161 addAllowedClientAddress(addressOrCidr);
162 }
163 }
164
165
166
167
168
169
170
171
172
173
174
175 protected boolean isClientAllowed(InetAddress clientAddress) {
176 if (allowedClientAddresses.isEmpty() || clientAddress == null) {
177 return false;
178 }
179 for (IpAddressMatcher matcher : allowedClientAddresses) {
180 if (matcher.matches(clientAddress)) {
181 return true;
182 }
183 }
184 return false;
185 }
186
187 public void run() {
188
189 final String oldThreadName = Thread.currentThread().getName();
190
191 try {
192
193 final String newThreadName = getServerThreadName();
194 Thread.currentThread().setName(newThreadName);
195
196 logger.info("Listening on port " + port);
197 if (allowedClientAddresses.isEmpty()) {
198 logger.warn("No allowed client addresses configured; all incoming connections will be denied. "
199 + "Use addAllowedClientAddress() or pass allowed addresses on the command line.");
200 } else {
201 logger.info("Client IP whitelist in effect ({} allowed address pattern(s))",
202 allowedClientAddresses.size());
203 }
204 serverSocket = getServerSocketFactory().createServerSocket(port);
205 while (!closed) {
206 logger.info("Waiting to accept a new client.");
207 signalAlmostReadiness();
208 Socket socket = serverSocket.accept();
209 InetAddress clientAddress = socket.getInetAddress();
210 logger.info("Connected to client at " + clientAddress);
211 if (!isClientAllowed(clientAddress)) {
212 logger.warn("Denying connection from unauthorized client " + clientAddress);
213 closeSocketQuietly(socket);
214 continue;
215 }
216 logger.info("Starting new socket node.");
217 SocketNode newSocketNode = new SocketNode(this, socket, lc);
218 synchronized (socketNodeList) {
219 socketNodeList.add(newSocketNode);
220 }
221 final String clientThreadName = getClientThreadName(socket);
222 new Thread(newSocketNode, clientThreadName).start();
223 }
224 } catch (Exception e) {
225 if (closed) {
226 logger.info("Exception in run method for a closed server. This is normal.");
227 } else {
228 logger.error("Unexpected failure in run method", e);
229 }
230 }
231
232 finally {
233 Thread.currentThread().setName(oldThreadName);
234 }
235 }
236
237 private void closeSocketQuietly(Socket socket) {
238 try {
239 socket.close();
240 } catch (IOException e) {
241 logger.debug("Failed to close unauthorized client socket", e);
242 }
243 }
244
245
246
247
248 protected String getServerThreadName() {
249 return String.format("Logback %s (port %d)", getClass().getSimpleName(), port);
250 }
251
252
253
254
255 protected String getClientThreadName(Socket socket) {
256 return String.format("Logback SocketNode (client: %s)", socket.getRemoteSocketAddress());
257 }
258
259
260
261
262
263
264 protected ServerSocketFactory getServerSocketFactory() {
265 return ServerSocketFactory.getDefault();
266 }
267
268
269
270
271
272 void signalAlmostReadiness() {
273 if (latch != null && latch.getCount() != 0) {
274
275 latch.countDown();
276 }
277 }
278
279
280
281
282
283
284 void setLatch(CountDownLatch latch) {
285 this.latch = latch;
286 }
287
288
289
290
291 public CountDownLatch getLatch() {
292 return latch;
293 }
294
295 public boolean isClosed() {
296 return closed;
297 }
298
299 public void close() {
300 closed = true;
301 if (serverSocket != null) {
302 try {
303 serverSocket.close();
304 } catch (IOException e) {
305 logger.error("Failed to close serverSocket", e);
306 } finally {
307 serverSocket = null;
308 }
309 }
310
311 logger.info("closing this server");
312 synchronized (socketNodeList) {
313 for (SocketNode sn : socketNodeList) {
314 sn.close();
315 }
316 }
317 if (socketNodeList.size() != 0) {
318 logger.warn("Was expecting a 0-sized socketNodeList after server shutdown");
319 }
320
321 }
322
323 public void socketNodeClosing(SocketNode sn) {
324 logger.debug("Removing {}", sn);
325
326
327
328
329 synchronized (socketNodeList) {
330 socketNodeList.remove(sn);
331 }
332 }
333
334 static void usage(String msg) {
335 usage(msg, SimpleSocketServer.class);
336 }
337
338 static void usage(String msg, Class<? extends SimpleSocketServer> serverClass) {
339 System.err.println(msg);
340 System.err.println("Usage: java " + serverClass.getName()
341 + " port configFile allowedAddress [allowedAddress ...]");
342 System.err.println(
343 " allowedAddress: a single IP (e.g. 192.168.1.10) or CIDR range (e.g. 192.168.1.0/24)");
344 System.err.println(" At least one allowedAddress must be specified.");
345 System.exit(1);
346 }
347
348 static int parsePortNumber(String portStr) {
349 try {
350 return Integer.parseInt(portStr);
351 } catch (java.lang.NumberFormatException e) {
352 e.printStackTrace();
353 usage("Could not interpret port number [" + portStr + "].");
354
355 return -1;
356 }
357 }
358
359 static public void configureLC(LoggerContext lc, String configFile) throws JoranException {
360 JoranConfigurator configurator = new JoranConfigurator();
361 lc.reset();
362 configurator.setContext(lc);
363 configurator.doConfigure(configFile);
364 }
365 }