View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.http.server;
45  
46  import java.io.File;
47  import java.text.MessageFormat;
48  import java.util.LinkedList;
49  import java.util.List;
50  
51  import javax.servlet.Filter;
52  import javax.servlet.FilterConfig;
53  import javax.servlet.ServletException;
54  import javax.servlet.http.HttpServletRequest;
55  import javax.servlet.http.HttpServletResponse;
56  
57  import org.eclipse.jgit.http.server.glue.ErrorServlet;
58  import org.eclipse.jgit.http.server.glue.MetaFilter;
59  import org.eclipse.jgit.http.server.glue.RegexGroupFilter;
60  import org.eclipse.jgit.http.server.glue.ServletBinder;
61  import org.eclipse.jgit.http.server.resolver.AsIsFileService;
62  import org.eclipse.jgit.http.server.resolver.DefaultReceivePackFactory;
63  import org.eclipse.jgit.http.server.resolver.DefaultUploadPackFactory;
64  import org.eclipse.jgit.lib.Constants;
65  import org.eclipse.jgit.transport.resolver.FileResolver;
66  import org.eclipse.jgit.transport.resolver.ReceivePackFactory;
67  import org.eclipse.jgit.transport.resolver.RepositoryResolver;
68  import org.eclipse.jgit.transport.resolver.UploadPackFactory;
69  import org.eclipse.jgit.util.StringUtils;
70  
71  /**
72   * Handles Git repository access over HTTP.
73   * <p>
74   * Applications embedding this filter should map a directory path within the
75   * application to this filter. For a servlet version, see
76   * {@link org.eclipse.jgit.http.server.GitServlet}.
77   * <p>
78   * Applications may wish to add additional repository action URLs to this
79   * servlet by taking advantage of its extension from
80   * {@link org.eclipse.jgit.http.server.glue.MetaFilter}. Callers may register
81   * their own URL suffix translations through {@link #serve(String)}, or their
82   * regex translations through {@link #serveRegex(String)}. Each translation
83   * should contain a complete filter pipeline which ends with the HttpServlet
84   * that should handle the requested action.
85   */
86  public class GitFilter extends MetaFilter {
87  	private volatile boolean initialized;
88  
89  	private RepositoryResolver<HttpServletRequest> resolver;
90  
91  	private AsIsFileServiceolver/AsIsFileService.html#AsIsFileService">AsIsFileService asIs = new AsIsFileService();
92  
93  	private UploadPackFactory<HttpServletRequest> uploadPackFactory = new DefaultUploadPackFactory();
94  
95  	private ReceivePackFactory<HttpServletRequest> receivePackFactory = new DefaultReceivePackFactory();
96  
97  	private final List<Filter> uploadPackFilters = new LinkedList<>();
98  
99  	private final List<Filter> receivePackFilters = new LinkedList<>();
100 
101 	/**
102 	 * New servlet that will load its base directory from {@code web.xml}.
103 	 * <p>
104 	 * The required parameter {@code base-path} must be configured to point to
105 	 * the local filesystem directory where all served Git repositories reside.
106 	 */
107 	public GitFilter() {
108 		// Initialized above by field declarations.
109 	}
110 
111 	/**
112 	 * New servlet configured with a specific resolver.
113 	 *
114 	 * @param resolver
115 	 *            the resolver to use when matching URL to Git repository. If
116 	 *            null the {@code base-path} parameter will be looked for in the
117 	 *            parameter table during init, which usually comes from the
118 	 *            {@code web.xml} file of the web application.
119 	 */
120 	public void setRepositoryResolver(RepositoryResolver<HttpServletRequest> resolver) {
121 		assertNotInitialized();
122 		this.resolver = resolver;
123 	}
124 
125 	/**
126 	 * Set AsIsFileService
127 	 *
128 	 * @param f
129 	 *            the filter to validate direct access to repository files
130 	 *            through a dumb client. If {@code null} then dumb client
131 	 *            support is completely disabled.
132 	 */
133 	public void setAsIsFileService(AsIsFileService f) {
134 		assertNotInitialized();
135 		this.asIs = f != null ? f : AsIsFileService.DISABLED;
136 	}
137 
138 	/**
139 	 * Set upload-pack factory
140 	 *
141 	 * @param f
142 	 *            the factory to construct and configure an
143 	 *            {@link org.eclipse.jgit.transport.UploadPack} session when a
144 	 *            fetch or clone is requested by a client.
145 	 */
146 	@SuppressWarnings("unchecked")
147 	public void setUploadPackFactory(UploadPackFactory<HttpServletRequest> f) {
148 		assertNotInitialized();
149 		this.uploadPackFactory = f != null ? f : (UploadPackFactory<HttpServletRequest>)UploadPackFactory.DISABLED;
150 	}
151 
152 	/**
153 	 * Add upload-pack filter
154 	 *
155 	 * @param filter
156 	 *            filter to apply before any of the UploadPack operations. The
157 	 *            UploadPack instance is available in the request attribute
158 	 *            {@link org.eclipse.jgit.http.server.ServletUtils#ATTRIBUTE_HANDLER}.
159 	 */
160 	public void addUploadPackFilter(Filter filter) {
161 		assertNotInitialized();
162 		uploadPackFilters.add(filter);
163 	}
164 
165 	/**
166 	 * Set the receive-pack factory
167 	 *
168 	 * @param f
169 	 *            the factory to construct and configure a
170 	 *            {@link org.eclipse.jgit.transport.ReceivePack} session when a
171 	 *            push is requested by a client.
172 	 */
173 	@SuppressWarnings("unchecked")
174 	public void setReceivePackFactory(ReceivePackFactory<HttpServletRequest> f) {
175 		assertNotInitialized();
176 		this.receivePackFactory = f != null ? f : (ReceivePackFactory<HttpServletRequest>)ReceivePackFactory.DISABLED;
177 	}
178 
179 	/**
180 	 * Add receive-pack filter
181 	 *
182 	 * @param filter
183 	 *            filter to apply before any of the ReceivePack operations. The
184 	 *            ReceivePack instance is available in the request attribute
185 	 *            {@link org.eclipse.jgit.http.server.ServletUtils#ATTRIBUTE_HANDLER}.
186 	 */
187 	public void addReceivePackFilter(Filter filter) {
188 		assertNotInitialized();
189 		receivePackFilters.add(filter);
190 	}
191 
192 	private void assertNotInitialized() {
193 		if (initialized)
194 			throw new IllegalStateException(HttpServerText.get().alreadyInitializedByContainer);
195 	}
196 
197 	/** {@inheritDoc} */
198 	@Override
199 	public void init(FilterConfig filterConfig) throws ServletException {
200 		super.init(filterConfig);
201 
202 		if (resolver == null) {
203 			File root = getFile(filterConfig, "base-path");
204 			boolean exportAll = getBoolean(filterConfig, "export-all");
205 			setRepositoryResolver(new FileResolver<>(root, exportAll));
206 		}
207 
208 		initialized = true;
209 
210 		if (uploadPackFactory != UploadPackFactory.DISABLED) {
211 			ServletBinder b = serve("*/" + GitSmartHttpTools.UPLOAD_PACK);
212 			b = b.through(new UploadPackServlet.Factory(uploadPackFactory));
213 			for (Filter f : uploadPackFilters)
214 				b = b.through(f);
215 			b.with(new UploadPackServlet());
216 		}
217 
218 		if (receivePackFactory != ReceivePackFactory.DISABLED) {
219 			ServletBinder b = serve("*/" + GitSmartHttpTools.RECEIVE_PACK);
220 			b = b.through(new ReceivePackServlet.Factory(receivePackFactory));
221 			for (Filter f : receivePackFilters)
222 				b = b.through(f);
223 			b.with(new ReceivePackServlet());
224 		}
225 
226 		ServletBinder refs = serve("*/" + Constants.INFO_REFS);
227 		if (uploadPackFactory != UploadPackFactory.DISABLED) {
228 			refs = refs.through(new UploadPackServlet.InfoRefs(
229 					uploadPackFactory, uploadPackFilters));
230 		}
231 		if (receivePackFactory != ReceivePackFactory.DISABLED) {
232 			refs = refs.through(new ReceivePackServlet.InfoRefs(
233 					receivePackFactory, receivePackFilters));
234 		}
235 		if (asIs != AsIsFileService.DISABLED) {
236 			refs = refs.through(new IsLocalFilter());
237 			refs = refs.through(new AsIsFileFilter(asIs));
238 			refs.with(new InfoRefsServlet());
239 		} else
240 			refs.with(new ErrorServlet(HttpServletResponse.SC_NOT_ACCEPTABLE));
241 
242 		if (asIs != AsIsFileService.DISABLED) {
243 			final IsLocalFilterilter.html#IsLocalFilter">IsLocalFilter mustBeLocal = new IsLocalFilter();
244 			final AsIsFileFilterileFilter.html#AsIsFileFilter">AsIsFileFilter enabled = new AsIsFileFilter(asIs);
245 
246 			serve("*/" + Constants.HEAD)//
247 					.through(mustBeLocal)//
248 					.through(enabled)//
249 					.with(new TextFileServlet(Constants.HEAD));
250 
251 			final String info_alternates = Constants.OBJECTS + "/" + Constants.INFO_ALTERNATES;
252 			serve("*/" + info_alternates)//
253 					.through(mustBeLocal)//
254 					.through(enabled)//
255 					.with(new TextFileServlet(info_alternates));
256 
257 			final String http_alternates = Constants.OBJECTS + "/" + Constants.INFO_HTTP_ALTERNATES;
258 			serve("*/" + http_alternates)//
259 					.through(mustBeLocal)//
260 					.through(enabled)//
261 					.with(new TextFileServlet(http_alternates));
262 
263 			serve("*/objects/info/packs")//
264 					.through(mustBeLocal)//
265 					.through(enabled)//
266 					.with(new InfoPacksServlet());
267 
268 			serveRegex("^/(.*)/objects/([0-9a-f]{2}/[0-9a-f]{38})$")//
269 					.through(mustBeLocal)//
270 					.through(enabled)//
271 					.through(new RegexGroupFilter(2))//
272 					.with(new ObjectFileServlet.Loose());
273 
274 			serveRegex("^/(.*)/objects/(pack/pack-[0-9a-f]{40}\\.pack)$")//
275 					.through(mustBeLocal)//
276 					.through(enabled)//
277 					.through(new RegexGroupFilter(2))//
278 					.with(new ObjectFileServlet.Pack());
279 
280 			serveRegex("^/(.*)/objects/(pack/pack-[0-9a-f]{40}\\.idx)$")//
281 					.through(mustBeLocal)//
282 					.through(enabled)//
283 					.through(new RegexGroupFilter(2))//
284 					.with(new ObjectFileServlet.PackIdx());
285 		}
286 	}
287 
288 	private static File getFile(FilterConfig cfg, String param)
289 			throws ServletException {
290 		String n = cfg.getInitParameter(param);
291 		if (n == null || "".equals(n))
292 			throw new ServletException(MessageFormat.format(HttpServerText.get().parameterNotSet, param));
293 
294 		File path = new File(n);
295 		if (!path.exists())
296 			throw new ServletException(MessageFormat.format(HttpServerText.get().pathForParamNotFound, path, param));
297 		return path;
298 	}
299 
300 	private static boolean getBoolean(FilterConfig cfg, String param)
301 			throws ServletException {
302 		String n = cfg.getInitParameter(param);
303 		if (n == null)
304 			return false;
305 		try {
306 			return StringUtils.toBoolean(n);
307 		} catch (IllegalArgumentException err) {
308 			throw new ServletException(MessageFormat.format(HttpServerText.get().invalidBoolean, param, n));
309 		}
310 	}
311 
312 	/** {@inheritDoc} */
313 	@Override
314 	protected ServletBinder../../../org/eclipse/jgit/http/server/glue/ServletBinder.html#ServletBinder">ServletBinder register(ServletBinder binder) {
315 		if (resolver == null)
316 			throw new IllegalStateException(HttpServerText.get().noResolverAvailable);
317 		binder = binder.through(new NoCacheFilter());
318 		binder = binder.through(new RepositoryFilter(resolver));
319 		return binder;
320 	}
321 }