aboutsummaryrefslogtreecommitdiffstats
path: root/ncomp-sirius-manager-server/src/main/java/org/openecomp/ncomp/sirius/manager/Jetty8Server.java
blob: 45e3c6856cc3d73f3c1baf94bdf761cd821af22f (plain)
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
377
378
379
380
/*-
 * ============LICENSE_START==========================================
 * OPENECOMP - DCAE
 * ===================================================================
 * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 */
	
package org.openecomp.ncomp.sirius.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import org.openecomp.entity.EcompSubComponentInstance;
import org.openecomp.logger.EcompException;
import org.openecomp.logger.EcompMessageEnum;
import org.openecomp.logger.StatusCodeEnum;
import com.att.eelf.i18n.EELFResourceManager;
import org.openecomp.ncomp.sirius.manager.logging.ManagementServerMessageEnum;
import org.openecomp.ncomp.sirius.manager.logging.NcompLogger;
import org.openecomp.ncomp.utils.PropertyUtil;
import org.openecomp.ncomp.webservice.utils.JsonUtils;

public class Jetty8Server {
	public static final Logger logger = Logger.getLogger(Jetty8Server.class);
	static final NcompLogger ecomplogger = NcompLogger.getNcompLogger();
	Server server;
	private SelectChannelConnector conn1;
	private int actualport;
	HashMap<String, IRequestHandler> handlerMap = new HashMap<String, IRequestHandler>();
	ServerThread thread;
	private Properties props;

	class Jetty8ServerHandler extends AbstractHandler {

		private HashMap<String, String> method2action = new HashMap<String, String>();

		{
			method2action.put("POST", "CREATE");
			method2action.put("PUT", "UPDATE");
			method2action.put("GET", "LIST");
			method2action.put("DELETE", "DELETE");
		}

		@Override
		public void handle(String contextPath, Request jRequest, HttpServletRequest request,
				HttpServletResponse response) throws IOException, ServletException {
			if (request.getMethod().equals("OPTIONS")) {
				setResponseHeaders(response);
				response.setHeader("Allow", "HEAD,GET,PUT,DELETE,OPTIONS");
				response.setStatus(200);
				jRequest.setHandled(true);
				return;
			}
			String userName = checkAuth(contextPath,jRequest);
			if (userName == null) {
				setResponseHeaders(response);
				response.setStatus(403);
				jRequest.setHandled(true);
				logger.info("Authorization not valid");
				return;
			}
			if (request.getRemoteHost() != null) ecomplogger.setRemoteHost(request.getRemoteHost());
			if (userName != null) ecomplogger.setPartnerName(userName);
			ecomplogger.startUnknownAuditEvent(contextPath);
			String requestId = request.getHeader("X-ECOMP-RequestID");
			if (requestId == null) {
				ecomplogger.newRequestId();
				ecomplogger.missingRequestId(request);
			}
			else {
				ecomplogger.setRequestId(requestId);
			}
			String clientVersion = request.getHeader("X-ECOMP-Client-Version");
			if (clientVersion == null) clientVersion = "UNKNOWN";
			ecomplogger.setInstanceId(EcompSubComponentInstance.getServerName() + ":" + props.getProperty("server.port") + contextPath);
			String action = request.getHeader("action");
			if (action == null) {
				String method = request.getMethod();
				action = method2action.get(method);
			}
			logger.debug("new request:" + contextPath + " " + request.getMethod() + " " + action);
			Object res = null;
			String contextPath1 = null;
			IRequestHandler handler = null;
			for (String prefix : handlerMap.keySet()) {
				if (contextPath.equals(prefix) || contextPath.startsWith(prefix + "/")) {
					contextPath1 = contextPath.substring(prefix.length());
					handler = handlerMap.get(prefix);
				}
			}
			if (handler == null) {
				logger.warn("request with no handler: " + contextPath);
				handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_WITHOUT_HANDLER,contextPath);
				return;
			}
			try {
				if ("application/json".equals(jRequest.getContentType()) || jRequest.getContentType() == null) {
//					ByteArrayOutputStream s = new ByteArrayOutputStream();
//					FileUtils.copyStream(request.getInputStream(), s);
//					System.err.println(s); 
//					JSONObject json = new JSONObject(new String(s.toByteArray()));
					JSONObject json = JsonUtils.stream2json(request.getInputStream());
					res = handler.handleJson(userName, action, contextPath1, json, req2context(contextPath, jRequest, userName), clientVersion);
				} else {
					handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNSUPPORTED_CONTENT_TYPE,jRequest.getContentType());
					return;
				}
			} catch (EcompException e) {
				handleError(jRequest, response, e.msgEnum, e.args);
				return;
			} catch (Exception e) {
				handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNKNOWN_EXCEPTION,e.getMessage());
				return;
			}
			if (res != null) {
				setResponseHeaders(response);
				if (res instanceof JSONObject) {
					JSONObject json1 = (JSONObject) res;
					PrintWriter w = response.getWriter();
					w.append(json1.toString(2));
					w.close();
				} else if (res instanceof JSONArray) {
					JSONArray json1 = (JSONArray) res;
					PrintWriter w = response.getWriter();
					w.append(json1.toString(2));
					w.close();	
				} else {
					handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNKNOWN_RETURN_CLASS,res.getClass().getName());
					return;
				}
			}
			response.setStatus(HttpServletResponse.SC_OK);
			jRequest.setHandled(true);	
			ecomplogger.recordAuditEventEnd();
		}

		private void setResponseHeaders(HttpServletResponse response) {
			for (Object k : props.keySet()) {
				if (k instanceof String) {
					String s = (String) k;
					if (! s.startsWith("server.header")) continue;
					response.setHeader(s.substring(14), props.getProperty(s));
				}
			}
		}
		
		private void handleError(Request jRequest, HttpServletResponse response, EcompMessageEnum msg, String... args) throws IOException {
			try {
				ecomplogger.warn(msg, args);
				ecomplogger.recordAuditEventEnd(StatusCodeEnum.ERROR, msg, args);
				String s = EELFResourceManager.getIdentifier(msg);
				// Assume s ends in something like 4015W
				int httpErrorCode = 501;
				try {
					String error = s.substring(s.length()-5,s.length()-2);
					httpErrorCode = Integer.parseInt(error);
				} catch (Exception e) {
				}
				response.sendError(httpErrorCode, EELFResourceManager.format(msg,args));
			} catch (Exception e) {
				ManagementServerUtils.printStackTrace(e);
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			}
			jRequest.setHandled(true);
		}

		private JSONObject req2context(String contextPath, Request jRequest, String user) {
			JSONObject c = new JSONObject();
			c.put("remoteIp", jRequest.getRemoteAddr());
			c.put("user", user);
			JSONObject p = new JSONObject();
			for (Object k : jRequest.getParameterMap().keySet()) {
				if (k instanceof String) {
					String kk = (String) k;
					p.put(kk, jRequest.getParameter(kk));
				}
			}
			c.put("parameters", p);
			c.put("path", contextPath);
			return c;
		}
	}

	public Jetty8Server(String propertyFileName) {
		try {
			props = PropertyUtil.getPropertiesFromClasspath(propertyFileName);
			String portString = props.getProperty("server.port");
			if (portString == null)
				return;
			int port = Integer.parseInt(portString);
			server = new Server();
			if (props.containsKey("server.keyStore")) {
				@SuppressWarnings("deprecation")
				SslContextFactory f = new SslContextFactory(props.getProperty("server.keyStore"));
				f.setKeyStorePassword(props.getProperty("server.keyStorePassword"));
				f.setKeyManagerPassword(props.getProperty("server.keyManagerPassword"));
				f.setTrustStore(props.getProperty("server.trustStore"));
				f.setTrustStorePassword(props.getProperty("server.trustStorePassword"));
				logger.info("HTTPS excluded protocols: " + Arrays.asList(f.getExcludeProtocols()));
				f.addExcludeProtocols("SSLv1", "SSLv2", "SSLv3");
				logger.info("HTTPS excluded protocols after fix: " + Arrays.asList(f.getExcludeProtocols()));
				SslSelectChannelConnector c = new SslSelectChannelConnector(f);
				c.setPort(port);
				c.setMaxIdleTime(30000);
				server.addConnector(c);
				conn1 = c;
				logger.info("Adding HTTPS on port: " + port);
			} else {
				SelectChannelConnector c = new SelectChannelConnector();
				c.setPort(port);
				server.addConnector(c);
				conn1 = c;
				logger.info("Adding HTTP on port: " + port);
			}
			server.setHandler(new Jetty8ServerHandler());
			// secondary port (assume HTTP)
			portString = props.getProperty("server.port2");
			if (portString != null) {
				port = Integer.parseInt(portString);
				SelectChannelConnector c = new SelectChannelConnector();
				c.setPort(port);
				server.addConnector(c);
				logger.info("Adding HTTP on secondary port: " + port);
			}
		} catch (Exception e) {
			ManagementServerUtils.printStackTrace(e);
		}
	}

	/**
	 * In unit testing, we want to start on an operating system selected port
	 * number, so we configure a port number of 0, and then use this to find out
	 * the real port number
	 */
	public int getPort() {
		return (actualport);
	}

	/**
	 * In unit testing, we want to shut down the server
	 */
	public void stop() {
		try {
			server.stop();
		} catch (Exception e) {
		}
	}

	public void start() {
		thread = new ServerThread();
	}

	public void join() {
		try {
			if (server == null) {
				logger.warn("Ignore Join: server is NULL");
				return;
			}
			server.start();
			actualport = conn1.getLocalPort();
			server.join();
		} catch (Exception e) {
			ManagementServerUtils.printStackTrace(e);
		}
	}

	public static void main(String[] args) {
		new Jetty8Server("server.properties");

	}

	public void add(String prefix, IRequestHandler h) {
		handlerMap.put(prefix, h);
	}

	class DummyRequestHandler implements IRequestHandler {
		@Override
		public Object handleJson(String userName, String action, String resourcePath, JSONObject json,
				JSONObject context, String clientVersion) {
			logger.debug("handleJson: user=" + userName + " action=" + action + " path=" + resourcePath + " json="
					+ json);
			return null;
		}

		@Override
		public Object handleBinary(String userName, String action, String resourcePath, InputStream in) {
			logger.info("handleBinary: user=" + userName + " action=" + action + " path=" + resourcePath);
			return null;
		}
	}

	private class ServerThread implements Runnable {
		public ServerThread() {
			Thread t = new Thread(this, "jetty server");
			t.setDaemon(true);
			t.start();
		}

		@Override
		public void run() {
			try {
				server.start();
				actualport = conn1.getLocalPort();
				server.join();
			} catch (Exception e) {
				ManagementServerUtils.printStackTrace(e);
			}
		}
	}

	private String checkAuth(String contextPath, Request r) {
		if (props.containsKey("server.noauth."+ contextPath))
			return "none";
		String s = r.getHeader("Authorization");
		if (s == null) {
			logger.warn("Authorization failed: No header");
			return null;
		}
		String a[] = s.split(" ");
		if (a.length != 2) {
			logger.warn("Authorization failed: Bad header");
			return null;
		}
		String s1 = null;
		try {
			s1 = B64Code.decode(a[1], StringUtil.__ISO_8859_1);
		} catch (UnsupportedEncodingException e) {
			logger.warn("Authorization failed: Bad header:" + e);
			return null;
		}
		int i = s1.indexOf(":");
		if (i == -1) {
			logger.warn("Authorization failed: Bad header");
			return null;
		}
		String user = s1.substring(0, i);
		String pw = s1.substring(i + 1);
		String pw2 = props.getProperty("server.user." + user);
		boolean valid = pw.equals(JavaHttpClient.decryptPassword(pw2));
		if (!valid)
			logger.warn("Authorization: bad PW: " + user + "@" + r.getRemoteAddr() + " " + pw.substring(0, 2));
		return valid ? user : null;
	}

}