package org.argeo.cms.internal.kernel;
-import static org.argeo.cms.KernelHeader.ACCESS_CONTROL_CONTEXT;
-
import java.io.IOException;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.security.cert.X509Certificate;
-import java.util.Enumeration;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Properties;
-import java.util.StringTokenizer;
import javax.jcr.Repository;
-import javax.security.auth.Subject;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-import javax.servlet.FilterChain;
-import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.jackrabbit.server.SessionProvider;
+import org.apache.jackrabbit.server.remoting.davex.JcrRemotingServlet;
+import org.apache.jackrabbit.webdav.simple.SimpleWebdavServlet;
import org.argeo.cms.CmsException;
-import org.argeo.cms.KernelHeader;
-import org.argeo.jackrabbit.servlet.OpenInViewSessionProvider;
-import org.argeo.jackrabbit.servlet.RemotingServlet;
-import org.argeo.jackrabbit.servlet.WebdavServlet;
-import org.argeo.jcr.ArgeoJcrConstants;
-import org.eclipse.equinox.http.servlet.ExtendedHttpService;
+import org.argeo.cms.internal.http.CmsSessionProvider;
+import org.argeo.cms.internal.http.DataHttpContext;
+import org.argeo.cms.internal.http.HtmlServlet;
+import org.argeo.cms.internal.http.HttpUtils;
+import org.argeo.cms.internal.http.LinkServlet;
+import org.argeo.cms.internal.http.PrivateHttpContext;
+import org.argeo.cms.internal.http.RobotServlet;
+import org.argeo.node.NodeConstants;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
+import org.osgi.util.tracker.ServiceTracker;
/**
* Intercepts and enriches http access, mainly focusing on security and
* transactionality.
*/
-class NodeHttp implements KernelConstants, ArgeoJcrConstants {
+public class NodeHttp implements KernelConstants {
private final static Log log = LogFactory.getLog(NodeHttp.class);
- private final static String ATTR_AUTH = "auth";
- private final static String HEADER_AUTHORIZATION = "Authorization";
- private final static String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
-
- // private final AuthenticationManager authenticationManager;
- private final ExtendedHttpService httpService;
-
- // FIXME Make it more unique
- private String httpAuthRealm = "Argeo";
-
- // Filters
- private final RootFilter rootFilter;
- // private final DoSFilter dosFilter;
- // private final QoSFilter qosFilter;
+ public final static String DEFAULT_SERVICE = "HTTP";
- // WebDav / JCR remoting
- private OpenInViewSessionProvider sessionProvider;
+ private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
- NodeHttp(ExtendedHttpService httpService, JackrabbitNode node) {
- // this.bundleContext = bundleContext;
- // this.authenticationManager = authenticationManager;
+ private ServiceTracker<Repository, Repository> repositories;
+ private final ServiceTracker<HttpService, HttpService> httpServiceTracker;
- this.httpService = httpService;
+ private String httpRealm = "Argeo";
+ private String webDavConfig = HttpUtils.WEBDAV_CONFIG;
+ private final boolean cleanState;
- // Filters
- rootFilter = new RootFilter();
- // dosFilter = new CustomDosFilter();
- // qosFilter = new QoSFilter();
+ public NodeHttp(boolean cleanState) {
+ this.cleanState = cleanState;
+ httpServiceTracker = new PrepareHttpStc();
+ // httpServiceTracker.open();
+ KernelUtils.asyncOpen(httpServiceTracker);
+ }
- // DAV
- sessionProvider = new OpenInViewSessionProvider();
+ public void destroy() {
+ if (repositories != null)
+ repositories.close();
+ }
- registerRepositoryServlets(ALIAS_NODE, node);
+ public void registerRepositoryServlets(HttpService httpService, String alias, Repository repository) {
+ if (httpService == null)
+ throw new CmsException("No HTTP service available");
try {
- httpService.registerFilter("/", rootFilter, null, null);
+ registerWebdavServlet(httpService, alias, repository);
+ registerRemotingServlet(httpService, alias, repository);
+ if (NodeConstants.HOME.equals(alias))
+ registerFilesServlet(httpService, alias, repository);
+ if (log.isTraceEnabled())
+ log.trace("Registered servlets for repository '" + alias + "'");
} catch (Exception e) {
- throw new CmsException("Could not register root filter", e);
+ throw new CmsException("Could not register servlets for repository '" + alias + "'", e);
}
}
- public void destroy() {
- sessionProvider.destroy();
- unregisterRepositoryServlets(ALIAS_NODE);
- }
-
- void registerRepositoryServlets(String alias, Repository repository) {
+ public static void unregisterRepositoryServlets(HttpService httpService, String alias) {
+ if (httpService == null)
+ return;
try {
- registerWebdavServlet(alias, repository, true);
- registerWebdavServlet(alias, repository, false);
- registerRemotingServlet(alias, repository, true);
- registerRemotingServlet(alias, repository, false);
+ httpService.unregister(webdavPath(alias));
+ httpService.unregister(remotingPath(alias));
+ if (NodeConstants.HOME.equals(alias))
+ httpService.unregister(filesPath(alias));
+ if (log.isTraceEnabled())
+ log.trace("Unregistered servlets for repository '" + alias + "'");
} catch (Exception e) {
- throw new CmsException(
- "Could not register servlets for repository " + alias, e);
+ log.error("Could not unregister servlets for repository '" + alias + "'", e);
}
}
- void unregisterRepositoryServlets(String alias) {
- // FIXME unregister servlets
+ void registerWebdavServlet(HttpService httpService, String alias, Repository repository)
+ throws NamespaceException, ServletException {
+ // WebdavServlet webdavServlet = new WebdavServlet(repository, new
+ // OpenInViewSessionProvider(alias));
+ WebdavServlet webdavServlet = new WebdavServlet(repository, new CmsSessionProvider(alias));
+ String path = webdavPath(alias);
+ Properties ip = new Properties();
+ ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, webDavConfig);
+ ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+ httpService.registerServlet(path, webdavServlet, ip, new DataHttpContext(httpRealm));
}
- void registerWebdavServlet(String alias, Repository repository,
- boolean anonymous) throws NamespaceException, ServletException {
- WebdavServlet webdavServlet = new WebdavServlet(repository,
- sessionProvider);
- String pathPrefix = anonymous ? WEBDAV_PUBLIC : WEBDAV_PRIVATE;
- String path = pathPrefix + "/" + alias;
+ void registerFilesServlet(HttpService httpService, String alias, Repository repository)
+ throws NamespaceException, ServletException {
+ WebdavServlet filesServlet = new WebdavServlet(repository, new CmsSessionProvider(alias));
+ String path = filesPath(alias);
Properties ip = new Properties();
- ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, WEBDAV_CONFIG);
+ ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, webDavConfig);
ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
- httpService.registerFilter(path, anonymous ? new AnonymousFilter()
- : new DavFilter(), null, null);
- // Cast to servlet because of a weird behaviour in Eclipse
- httpService.registerServlet(path, (Servlet) webdavServlet, ip, null);
+ httpService.registerServlet(path, filesServlet, ip, new PrivateHttpContext(httpRealm, true));
}
- void registerRemotingServlet(String alias, Repository repository,
- boolean anonymous) throws NamespaceException, ServletException {
- String pathPrefix = anonymous ? REMOTING_PUBLIC : REMOTING_PRIVATE;
- RemotingServlet remotingServlet = new RemotingServlet(repository,
- sessionProvider);
- String path = pathPrefix + "/" + alias;
+ void registerRemotingServlet(HttpService httpService, String alias, Repository repository)
+ throws NamespaceException, ServletException {
+ RemotingServlet remotingServlet = new RemotingServlet(repository, new CmsSessionProvider(alias));
+ String path = remotingPath(alias);
Properties ip = new Properties();
- ip.setProperty(RemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+ ip.setProperty(JcrRemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+ ip.setProperty(JcrRemotingServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Negotiate");
// Looks like a bug in Jackrabbit remoting init
- ip.setProperty(RemotingServlet.INIT_PARAM_HOME,
- KernelUtils.getOsgiInstanceDir() + "/tmp/jackrabbit");
- ip.setProperty(RemotingServlet.INIT_PARAM_TMP_DIRECTORY, "remoting");
- // Cast to servlet because of a weird behaviour in Eclipse
- httpService.registerFilter(path, anonymous ? new AnonymousFilter()
- : new DavFilter(), null, null);
- httpService.registerServlet(path, (Servlet) remotingServlet, ip, null);
+ Path tmpDir;
+ try {
+ tmpDir = Files.createTempDirectory("remoting_" + alias);
+ } catch (IOException e) {
+ throw new CmsException("Cannot create temp directory for remoting servlet", e);
+ }
+ ip.setProperty(RemotingServlet.INIT_PARAM_HOME, tmpDir.toString());
+ ip.setProperty(RemotingServlet.INIT_PARAM_TMP_DIRECTORY, "remoting_" + alias);
+ ip.setProperty(RemotingServlet.INIT_PARAM_PROTECTED_HANDLERS_CONFIG, HttpUtils.DEFAULT_PROTECTED_HANDLERS);
+ ip.setProperty(RemotingServlet.INIT_PARAM_CREATE_ABSOLUTE_URI, "false");
+ httpService.registerServlet(path, remotingServlet, ip, new PrivateHttpContext(httpRealm));
}
- // private Boolean isSessionAuthenticated(HttpSession httpSession) {
- // SecurityContext contextFromSession = (SecurityContext) httpSession
- // .getAttribute(SPRING_SECURITY_CONTEXT_KEY);
- // return contextFromSession != null;
- // }
-
- private void requestBasicAuth(HttpSession httpSession,
- HttpServletResponse response) {
- response.setStatus(401);
- response.setHeader(HEADER_WWW_AUTHENTICATE, "basic realm=\""
- + httpAuthRealm + "\"");
- httpSession.setAttribute(ATTR_AUTH, Boolean.TRUE);
+ static String webdavPath(String alias) {
+ return NodeConstants.PATH_DATA + "/" + alias;
}
- private CallbackHandler basicAuth(String authHeader) {
- if (authHeader != null) {
- StringTokenizer st = new StringTokenizer(authHeader);
- if (st.hasMoreTokens()) {
- String basic = st.nextToken();
- if (basic.equalsIgnoreCase("Basic")) {
- try {
- // TODO manipulate char[]
- String credentials = new String(Base64.decodeBase64(st
- .nextToken()), "UTF-8");
- // log.debug("Credentials: " + credentials);
- int p = credentials.indexOf(":");
- if (p != -1) {
- final String login = credentials.substring(0, p)
- .trim();
- final char[] password = credentials
- .substring(p + 1).trim().toCharArray();
-
- return new CallbackHandler() {
- public void handle(Callback[] callbacks) {
- for (Callback cb : callbacks) {
- if (cb instanceof NameCallback)
- ((NameCallback) cb).setName(login);
- else if (cb instanceof PasswordCallback)
- ((PasswordCallback) cb)
- .setPassword(password);
- }
- }
- };
- } else {
- throw new CmsException(
- "Invalid authentication token");
- }
- } catch (Exception e) {
- throw new CmsException(
- "Couldn't retrieve authentication", e);
- }
- }
- }
- }
- throw new CmsException("Couldn't retrieve authentication");
+ static String remotingPath(String alias) {
+ return NodeConstants.PATH_JCR + "/" + alias;
+ }
+
+ static String filesPath(String alias) {
+ return NodeConstants.PATH_FILES;
}
- /** Intercepts all requests. Authenticates. */
- class RootFilter extends HttpFilter {
+ class RepositoriesStc extends ServiceTracker<Repository, Repository> {
+ private final HttpService httpService;
+
+ private final BundleContext bc;
+
+ public RepositoriesStc(BundleContext bc, HttpService httpService) {
+ super(bc, Repository.class, null);
+ this.httpService = httpService;
+ this.bc = bc;
+ }
@Override
- public void doFilter(HttpSession httpSession,
- HttpServletRequest request, HttpServletResponse response,
- FilterChain filterChain) throws IOException, ServletException {
- if (log.isTraceEnabled()) {
- log.trace(request.getRequestURL().append(
- request.getQueryString() != null ? "?"
- + request.getQueryString() : ""));
- logRequest(request);
+ public Repository addingService(ServiceReference<Repository> reference) {
+ Repository repository = bc.getService(reference);
+ Object jcrRepoAlias = reference.getProperty(NodeConstants.CN);
+ if (jcrRepoAlias != null) {
+ String alias = jcrRepoAlias.toString();
+ registerRepositoryServlets(httpService, alias, repository);
}
+ return repository;
+ }
- String servletPath = request.getServletPath();
+ @Override
+ public void modifiedService(ServiceReference<Repository> reference, Repository service) {
+ }
- // client certificate
- X509Certificate clientCert = extractCertificate(request);
- if (clientCert != null) {
- // TODO authenticate
- // if (log.isDebugEnabled())
- // log.debug(clientCert.getSubjectX500Principal().getName());
+ @Override
+ public void removedService(ServiceReference<Repository> reference, Repository service) {
+ Object jcrRepoAlias = reference.getProperty(NodeConstants.CN);
+ if (jcrRepoAlias != null) {
+ String alias = jcrRepoAlias.toString();
+ unregisterRepositoryServlets(httpService, alias);
}
+ }
+ }
- // skip data
- if (servletPath.startsWith(PATH_DATA)) {
- filterChain.doFilter(request, response);
- return;
- }
+ private class PrepareHttpStc extends ServiceTracker<HttpService, HttpService> {
+ public PrepareHttpStc() {
+ super(bc, HttpService.class, null);
+ }
- // skip /ui (workbench) for the time being
- if (servletPath.startsWith(PATH_WORKBENCH)) {
- filterChain.doFilter(request, response);
- return;
- }
+ @Override
+ public HttpService addingService(ServiceReference<HttpService> reference) {
+ long begin = System.currentTimeMillis();
+ if (log.isTraceEnabled())
+ log.trace("HTTP prepare starts...");
+ HttpService httpService = addHttpService(reference);
+ if (log.isTraceEnabled())
+ log.trace("HTTP prepare duration: " + (System.currentTimeMillis() - begin) + "ms");
+ return httpService;
+ }
+
+ @Override
+ public void removedService(ServiceReference<HttpService> reference, HttpService service) {
+ repositories.close();
+ repositories = null;
+ }
- // redirect long RWT paths to anchor
- String path = request.getRequestURI().substring(
- servletPath.length());
- int pathLength = path.length();
- if (pathLength != 0 && (path.charAt(0) == '/')
- && !servletPath.endsWith("rwt-resources")
- && path.lastIndexOf('/') != 0) {
- String newLocation = request.getServletPath() + "#" + path;
- response.setHeader("Location", newLocation);
- response.setStatus(HttpServletResponse.SC_FOUND);
- return;
+ private HttpService addHttpService(ServiceReference<HttpService> sr) {
+ HttpService httpService = bc.getService(sr);
+ // TODO find constants
+ Object httpPort = sr.getProperty("http.port");
+ Object httpsPort = sr.getProperty("https.port");
+
+ try {
+ httpService.registerServlet("/!", new LinkServlet(), null, null);
+ httpService.registerServlet("/robots.txt", new RobotServlet(), null, null);
+ httpService.registerServlet("/html", new HtmlServlet(), null, null);
+ } catch (Exception e) {
+ throw new CmsException("Cannot register filters", e);
}
+ // track repositories
+ if (repositories != null)
+ throw new CmsException("An http service is already configured");
+ repositories = new RepositoriesStc(bc, httpService);
+ // repositories.open();
+ if (cleanState)
+ KernelUtils.asyncOpen(repositories);
+ log.info(httpPortsMsg(httpPort, httpsPort));
+ // httpAvailable = true;
+ // checkReadiness();
+
+ bc.registerService(NodeHttp.class, NodeHttp.this, null);
+ return httpService;
+ }
- // process normally
- filterChain.doFilter(request, response);
+ private String httpPortsMsg(Object httpPort, Object httpsPort) {
+ return "HTTP " + httpPort + (httpsPort != null ? " - HTTPS " + httpsPort : "");
}
}
- private void logRequest(HttpServletRequest request) {
- log.debug("contextPath=" + request.getContextPath());
- log.debug("servletPath=" + request.getServletPath());
- log.debug("requestURI=" + request.getRequestURI());
- log.debug("queryString=" + request.getQueryString());
- StringBuilder buf = new StringBuilder();
- // headers
- Enumeration<String> en = request.getHeaderNames();
- while (en.hasMoreElements()) {
- String header = en.nextElement();
- Enumeration<String> values = request.getHeaders(header);
- while (values.hasMoreElements())
- buf.append(" " + header + ": " + values.nextElement());
- buf.append('\n');
- }
+ private static class WebdavServlet extends SimpleWebdavServlet {
+ private static final long serialVersionUID = -4687354117811443881L;
+ private final Repository repository;
- // attributed
- Enumeration<String> an = request.getAttributeNames();
- while (an.hasMoreElements()) {
- String attr = an.nextElement();
- Object value = request.getAttribute(attr);
- buf.append(" " + attr + ": " + value);
- buf.append('\n');
+ public WebdavServlet(Repository repository, SessionProvider sessionProvider) {
+ this.repository = repository;
+ setSessionProvider(sessionProvider);
}
- log.debug("\n" + buf);
- }
- private X509Certificate extractCertificate(HttpServletRequest req) {
- X509Certificate[] certs = (X509Certificate[]) req
- .getAttribute("javax.servlet.request.X509Certificate");
- if (null != certs && certs.length > 0) {
- return certs[0];
+ public Repository getRepository() {
+ return repository;
}
- return null;
- }
- /** Intercepts all requests. Authenticates. */
- private class AnonymousFilter extends HttpFilter {
@Override
- public void doFilter(HttpSession httpSession,
- final HttpServletRequest request,
- final HttpServletResponse response,
- final FilterChain filterChain) throws IOException,
- ServletException {
-
- // Authenticate from session
- // if (isSessionAuthenticated(httpSession)) {
- // filterChain.doFilter(request, response);
- // return;
+ protected void service(final HttpServletRequest request, final HttpServletResponse response)
+ throws ServletException, IOException {
+ WebdavServlet.super.service(request, response);
+ // try {
+ // Subject subject = subjectFromRequest(request);
+ // // TODO make it stronger, with eTags.
+ // // if (CurrentUser.isAnonymous(subject) &&
+ // // request.getMethod().equals("GET")) {
+ // // response.setHeader("Cache-Control", "no-transform, public,
+ // // max-age=300, s-maxage=900");
+ // // }
+ //
+ // Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
+ // @Override
+ // public Void run() throws Exception {
+ // WebdavServlet.super.service(request, response);
+ // return null;
+ // }
+ // });
+ // } catch (PrivilegedActionException e) {
+ // throw new CmsException("Cannot process webdav request",
+ // e.getException());
// }
-
- Subject subject = KernelUtils.anonymousLogin();
- try {
- Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
- public Void run() throws IOException, ServletException {
- filterChain.doFilter(request, response);
- return null;
- }
- });
- } catch (PrivilegedActionException e) {
- if (e.getCause() instanceof ServletException)
- throw (ServletException) e.getCause();
- else if (e.getCause() instanceof IOException)
- throw (IOException) e.getCause();
- else
- throw new CmsException("Unexpected exception", e.getCause());
- }
}
+
}
- /** Intercepts all requests. Authenticates. */
- private class DavFilter extends HttpFilter {
+ private static class RemotingServlet extends JcrRemotingServlet {
+ private final Log log = LogFactory.getLog(RemotingServlet.class);
+ private static final long serialVersionUID = 4605238259548058883L;
+ private final Repository repository;
+ private final SessionProvider sessionProvider;
+
+ public RemotingServlet(Repository repository, SessionProvider sessionProvider) {
+ this.repository = repository;
+ this.sessionProvider = sessionProvider;
+ }
@Override
- public void doFilter(final HttpSession httpSession,
- final HttpServletRequest request,
- final HttpServletResponse response,
- final FilterChain filterChain) throws IOException,
- ServletException {
-
- AccessControlContext acc = (AccessControlContext) httpSession
- .getAttribute(KernelHeader.ACCESS_CONTROL_CONTEXT);
- final Subject subject;
- if (acc != null) {
- subject = Subject.getSubject(acc);
- } else {
- // Process basic auth
- String basicAuth = request.getHeader(HEADER_AUTHORIZATION);
- if (basicAuth != null) {
- CallbackHandler token = basicAuth(basicAuth);
- try {
- LoginContext lc = new LoginContext(
- KernelHeader.LOGIN_CONTEXT_USER, token);
- lc.login();
- subject = lc.getSubject();
- } catch (LoginException e) {
- throw new CmsException("Could not login", e);
- }
- } else {
- requestBasicAuth(httpSession, response);
- return;
- }
- }
- // do filter as subject
- try {
- Subject.doAs(subject,
- new PrivilegedExceptionAction<Void>() {
- public Void run() throws IOException,
- ServletException {
- // add security context to session
- httpSession.setAttribute(
- ACCESS_CONTROL_CONTEXT,
- AccessController.getContext());
- filterChain.doFilter(request, response);
- return null;
- }
- });
- } catch (PrivilegedActionException e) {
- if (e.getCause() instanceof ServletException)
- throw (ServletException) e.getCause();
- else if (e.getCause() instanceof IOException)
- throw (IOException) e.getCause();
- else
- throw new CmsException("Unexpected exception",
- e.getCause());
- }
+ protected Repository getRepository() {
+ return repository;
+ }
+ @Override
+ protected SessionProvider getSessionProvider() {
+ return sessionProvider;
+ }
+
+ @Override
+ protected void service(final HttpServletRequest request, final HttpServletResponse response)
+ throws ServletException, IOException {
+ if (log.isTraceEnabled())
+ HttpUtils.logRequest(log, request);
+ RemotingServlet.super.service(request, response);
}
}
- // class CustomDosFilter extends DoSFilter {
- // @Override
- // protected String extractUserId(ServletRequest request) {
- // HttpSession httpSession = ((HttpServletRequest) request)
- // .getSession();
- // if (isSessionAuthenticated(httpSession)) {
- // String userId = ((SecurityContext) httpSession
- // .getAttribute(SPRING_SECURITY_CONTEXT_KEY))
- // .getAuthentication().getName();
- // return userId;
- // }
- // return super.extractUserId(request);
- //
- // }
- // }
}