forked from eclipse-ee4j/glassfish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestrictedContentAdapter.java
376 lines (336 loc) · 14.8 KB
/
RestrictedContentAdapter.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.appclient.server.core.jws;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.servlet.http.HttpServletResponse;
import java.net.URI;
import org.glassfish.appclient.server.core.jws.servedcontent.Content;
import org.glassfish.appclient.server.core.jws.servedcontent.StaticContent;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
/**
*
* @author tjquinn
*/
public class RestrictedContentAdapter extends HttpHandler {
public final static String LAST_MODIFIED_HEADER_NAME = "Last-Modified";
public final static String DATE_HEADER_NAME = "Date";
protected final static String IF_MODIFIED_SINCE = "If-Modified-Since";
private final static String LINE_SEP = System.getProperty("line.separator");
private final static String BROKEN_PIPE = "Broken pipe";
protected final static Logger logger = Logger.getLogger(JavaWebStartInfo.APPCLIENT_SERVER_MAIN_LOGGER, JavaWebStartInfo.APPCLIENT_SERVER_LOGMESSAGE_RESOURCE);
private enum State {
RESUMED,
SUSPENDED
}
private volatile State state = State.RESUMED;
private final String contextRoot;
private final ConcurrentHashMap<String, StaticContent> content =
new ConcurrentHashMap<String, StaticContent>();
public RestrictedContentAdapter(
final String contextRoot,
final Map<String, StaticContent> content) throws IOException {
this(contextRoot);
this.content.putAll(content);
/*
* Preload the adapter's cache with the static content. This helps
* performance but is essential to the operation of the adapter.
* Normally the Grizzly logic will qualify the URI in the request
* with the root folder of the adapter. But the files this
* adapter needs to serve can come from a variety of places that
* might not share any common parent directory for the root folder.
* Preloading the cache with the known static content lets the Grizzly
* logic serve the files we want, from whereever they are.
*/
// for (Map.Entry<String, StaticContent> sc : content.entrySet()) {
// cache.put(sc.getKey(), sc.getValue().file());
// }
logger.log(Level.FINE, "{0}Initial static content loaded {1}", new Object[]{logPrefix(), dumpContent()});
}
public RestrictedContentAdapter(final String contextRoot) {
/*
* Turn off the default static resource handling. We do our own from
* our service method, rather than letting the StaticResourcesAdapter
* (superclass) logic have a try at each request first.
*/
this.contextRoot = contextRoot;
// this.userFriendlyContextRoot = userFriendlyContextRoot;
// setHandleStaticResources(false);
// setUseSendFile(false);
// commitErrorResponse = true;
}
@Override
public void service(Request gReq, Response gResp) {
try {
if (!serviceContent(gReq, gResp)) {
respondNotFound(gResp);
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public String contextRoot() {
return contextRoot;
}
// public String userFriendlyContextRoot() {
// return userFriendlyContextRoot;
// }
public synchronized void addContentIfAbsent(final String relativeURIString,
final StaticContent newContent) throws IOException {
final StaticContent existingContent = content.get(relativeURIString);
if (existingContent != null) {
if (!existingContent.equals(newContent)) {
logger.log(Level.FINE, "enterprise.deployment.appclient.jws.staticContentCollision",
new Object[]{relativeURIString, newContent.toString()});
}
return;
}
this.content.put(relativeURIString, newContent);
// this.cache.put(relativeURIString, newContent.file());
if (logger.isLoggable(Level.FINE)) {
logger.fine(logPrefix() + "adding static content "
+ relativeURIString + " " + newContent.toString());
}
}
public synchronized void addContentIfAbsent(
final Map<String, StaticContent> staticContent) throws IOException {
for (Map.Entry<String, StaticContent> entry : staticContent.entrySet()) {
addContentIfAbsent(entry.getKey(), entry.getValue());
}
}
// protected String relativizeURIString(final String uriString) {
// String result;
// if ( (result = relativizeURIString(contextRoot, uriString)) == null) {
// if ( ( result = relativizeURIString(userFriendlyContextRoot, uriString)) == null) {
// logger.log(Level.WARNING, "enterprise.deployment.appclient.jws.uriOutsideContextRoot",
// new Object[] {uriString, contextRoot, userFriendlyContextRoot});
// return null;
// }
// }
// return result;
// }
protected String relativizeURIString(final String candidateContextRoot,
final String uriString) {
if (!uriString.startsWith(candidateContextRoot)) {
return null;
}
/*
* If the user has requested the main JNLP using the user-friendly
* context root then there candidate context root is exactly the
* same as the context root. There will be no substring after
* that.
*/
if (candidateContextRoot.equals(uriString)) {
return "";
}
return uriString.substring(candidateContextRoot.length() + 1);
}
protected boolean serviceContent(Request gReq, Response gResp) throws IOException {
String relativeURIString = relativizeURIString(contextRoot, gReq.getRequestURI());
/*
* "Forbidden" seems like a more helpful response than "not found"
* if the corresponding app client has been suspended.
*/
if (state == State.SUSPENDED) {
finishErrorResponse(gResp, HttpServletResponse.SC_FORBIDDEN);
if (logger.isLoggable(Level.FINE)) {
logger.fine(logPrefix() + "is suspended; refused to serve static content requested using "
+ (relativeURIString == null ? "null" : relativeURIString));
}
return true;
}
if (relativeURIString == null) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(logPrefix() + "Could not find static content requested using full request URI = "
+ gReq.getRequestURI() + " - relativized URI was null");
}
respondNotFound(gResp);
return true;
}
/*
* The Grizzly-managed cache could contain entries for non-existent
* files that users request. If the URI indicates it's a request for
* static content make sure the requested URI is in the predefined staticContent
* before having Grizzly serve it.
*
* Alternatively, if the URI indicates the request is for dynamic content
* then handle that separately.
*
* If the request is for a URI in neither the static nor dynamic
* content this adapter should serve, then just return a 404.
*/
final StaticContent sc = content.get(relativeURIString);
final URI requestURI = Util.getCodebase(gReq);
if (sc != null && sc.isAvailable(requestURI)) {
processContent(relativeURIString, gReq, gResp);
return true;
} else {
finishErrorResponse(gResp, contentStateToResponseStatus(sc, requestURI));
final String scString = (sc == null ? "null" : sc.toString());
final String scStateString = (sc == null ? "null" : sc.state().toString());
if (logger.isLoggable(Level.FINE)) {
logger.fine(logPrefix() + "Found static content for " + gReq.getMethod()
+ ": " + relativeURIString + " -> " + scString
+ " but could not serve it; its state is " + scStateString);
}
return true;
}
}
private void processContent(final String relativeURIString,
final Request gReq, final Response gResp) {
try {
final StaticContent sc = content.get(relativeURIString);
if (sc == null) {
throw new RuntimeException(relativeURIString + "-> null");
}
/*
* No need to actually send the file if the request contains a
* If-Modified-Since date and the file is not more recent.
*/
final File fileToSend = sc.file();
if (fileToSend != null) {
if (returnIfClientCacheIsCurrent(relativeURIString,
gReq, fileToSend.lastModified())) {
return;
}
}
sc.process(relativeURIString, gReq, gResp);
// final int status = gResp.getStatus();
// if (status != HttpServletResponse.SC_OK) {
// logger.fine(logPrefix() + "Could not serve content for "
// + relativeURIString + " - status = " + status);
// } else {
// logger.fine(logPrefix() + "Served static content for " + gReq.getMethod()
// + ":" + sc.toString());
// }
// finishResponse(gResp, status);
} catch (IOException ioex) {
/*
* Broken pipe errors happen fairly regularly with Java Web Start on
* the client side. There's no need to clutter up the log with
* reports of them that we cannot really do anything about.
*/
if (isBrokenPipe(ioex)) {
logger.log(Level.FINE, "''Broken pipe'' while responding to {0}{1}", new Object[]{logPrefix(), relativeURIString});
} else {
finishErrorResponse(gResp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.log(Level.SEVERE, logPrefix() + relativeURIString, ioex);
}
} catch (Exception e) {
// gResp.getResponse().setErrorException(e);
finishErrorResponse(gResp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.log(Level.SEVERE, logPrefix() + relativeURIString, e);
}
}
private boolean isBrokenPipe(final IOException ioex) {
final Throwable cause = ioex.getCause();
return (cause != null && (cause instanceof IOException) && (cause.getMessage()).contains(BROKEN_PIPE));
}
protected boolean returnIfClientCacheIsCurrent(final String relativeURIString,
final Request gReq,
final long contentTimestamp) {
final long ifModifiedSinceTime = gReq.getDateHeader(IF_MODIFIED_SINCE);
boolean result;
if (result = (ifModifiedSinceTime != -1)
&& (ifModifiedSinceTime >= contentTimestamp)) {
finishSuccessResponse(gReq.getResponse(),
HttpServletResponse.SC_NOT_MODIFIED);
if (logger.isLoggable(Level.FINE)) {
logger.fine(logPrefix() + relativeURIString + " is already current on the client; no downloaded needed");
}
}
return result;
}
protected int contentStateToResponseStatus(Content content, final URI requestURI) throws IOException {
int status;
if (content == null) {
status = HttpServletResponse.SC_NOT_FOUND;
} else if (content.isAvailable(requestURI)) {
status = HttpServletResponse.SC_OK;
} else {
status = (content.state() == Content.State.SUSPENDED
? HttpServletResponse.SC_FORBIDDEN
: HttpServletResponse.SC_NOT_FOUND);
}
return status;
}
public void suspend() {
state = State.SUSPENDED;
}
public void resume() {
state = State.RESUMED;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(logPrefix()).append(LINE_SEP);
for (Map.Entry<String, StaticContent> entry : content.entrySet()) {
sb.append(" ").append(entry.toString()).append(LINE_SEP);
}
return sb.toString();
}
protected void finishResponse(final Response gResp, final int status) {
gResp.setStatus(status);
gResp.finish();
}
protected void respondNotFound(final Response gResp) {
finishErrorResponse(gResp, HttpServletResponse.SC_NOT_FOUND);
}
protected void finishSuccessResponse(final Response gResp, final int status) {
finishResponse(gResp, status, false);
}
private void finishResponse(final Response gResp, final int status,
final boolean treatAsError) {
if (gResp.isCommitted() || ! gResp.getRequest().getContext().getConnection().isOpen()) {
return;
}
gResp.setStatus(status);
try {
if (treatAsError /* && commitErrorResponse */) {
gResp.sendError(status);
}
gResp.finish();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void finishErrorResponse(final Response gResp, final int status) {
finishResponse(gResp, status, true);
}
protected String dumpContent() {
if (content == null) {
return " Static content: not initialized";
}
if (content.isEmpty()) {
return " Static content: empty" + LINE_SEP;
}
final StringBuilder sb = new StringBuilder(LINE_SEP).append(" Static content");
for (Map.Entry<String, StaticContent> entry : content.entrySet()) {
sb.append(" ").append(entry.getKey()).append(" : ").
append(entry.getValue().toString()).append(LINE_SEP);
}
sb.append(LINE_SEP).append(" ========");
return sb.toString();
}
protected String logPrefix() {
return "Adapter[" + contextRoot + "] ";
}
}