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.transport.resolver;
45  
46  import java.io.File;
47  import java.io.IOException;
48  import java.util.Collection;
49  import java.util.Map;
50  import java.util.concurrent.ConcurrentHashMap;
51  import java.util.concurrent.CopyOnWriteArrayList;
52  
53  import org.eclipse.jgit.errors.RepositoryNotFoundException;
54  import org.eclipse.jgit.lib.Constants;
55  import org.eclipse.jgit.lib.Repository;
56  import org.eclipse.jgit.lib.RepositoryCache;
57  import org.eclipse.jgit.lib.RepositoryCache.FileKey;
58  import org.eclipse.jgit.util.FS;
59  
60  /**
61   * Default resolver serving from the local filesystem.
62   *
63   * @param <C>
64   *            type of connection
65   */
66  public class FileResolver<C> implements RepositoryResolver<C> {
67  	private volatile boolean exportAll;
68  
69  	private final Map<String, Repository> exports;
70  
71  	private final Collection<File> exportBase;
72  
73  	/**
74  	 * Initialize an empty file based resolver.
75  	 */
76  	public FileResolver() {
77  		exports = new ConcurrentHashMap<>();
78  		exportBase = new CopyOnWriteArrayList<>();
79  	}
80  
81  	/**
82  	 * Create a new resolver for the given path.
83  	 *
84  	 * @param basePath
85  	 *            the base path all repositories are rooted under.
86  	 * @param exportAll
87  	 *            if true, exports all repositories, ignoring the check for the
88  	 *            {@code git-daemon-export-ok} files.
89  	 */
90  	public FileResolver(File basePath, boolean exportAll) {
91  		this();
92  		exportDirectory(basePath);
93  		setExportAll(exportAll);
94  	}
95  
96  	/** {@inheritDoc} */
97  	@Override
98  	public Repository open(C req, String name)
99  			throws RepositoryNotFoundException, ServiceNotEnabledException {
100 		if (isUnreasonableName(name))
101 			throw new RepositoryNotFoundException(name);
102 
103 		Repository db = exports.get(nameWithDotGit(name));
104 		if (db != null) {
105 			db.incrementOpen();
106 			return db;
107 		}
108 
109 		for (File base : exportBase) {
110 			File dir = FileKey.resolve(new File(base, name), FS.DETECTED);
111 			if (dir == null)
112 				continue;
113 
114 			try {
115 				FileKey key = FileKey.exact(dir, FS.DETECTED);
116 				db = RepositoryCache.open(key, true);
117 			} catch (IOException e) {
118 				throw new RepositoryNotFoundException(name, e);
119 			}
120 
121 			try {
122 				if (isExportOk(req, name, db)) {
123 					// We have to leak the open count to the caller, they
124 					// are responsible for closing the repository if we
125 					// complete successfully.
126 					return db;
127 				} else
128 					throw new ServiceNotEnabledException();
129 
130 			} catch (RuntimeException e) {
131 				db.close();
132 				throw new RepositoryNotFoundException(name, e);
133 
134 			} catch (IOException e) {
135 				db.close();
136 				throw new RepositoryNotFoundException(name, e);
137 
138 			} catch (ServiceNotEnabledException e) {
139 				db.close();
140 				throw e;
141 			}
142 		}
143 
144 		if (exportBase.size() == 1) {
145 			File dir = new File(exportBase.iterator().next(), name);
146 			throw new RepositoryNotFoundException(name,
147 					new RepositoryNotFoundException(dir));
148 		}
149 
150 		throw new RepositoryNotFoundException(name);
151 	}
152 
153 	/**
154 	 * Whether <code>git-daemon-export-ok</code> is required to export a
155 	 * repository
156 	 *
157 	 * @return false if <code>git-daemon-export-ok</code> is required to export
158 	 *         a repository; true if <code>git-daemon-export-ok</code> is
159 	 *         ignored.
160 	 * @see #setExportAll(boolean)
161 	 */
162 	public boolean isExportAll() {
163 		return exportAll;
164 	}
165 
166 	/**
167 	 * Set whether or not to export all repositories.
168 	 * <p>
169 	 * If false (the default), repositories must have a
170 	 * <code>git-daemon-export-ok</code> file to be accessed through this
171 	 * daemon.
172 	 * <p>
173 	 * If true, all repositories are available through the daemon, whether or
174 	 * not <code>git-daemon-export-ok</code> exists.
175 	 *
176 	 * @param export a boolean.
177 	 */
178 	public void setExportAll(boolean export) {
179 		exportAll = export;
180 	}
181 
182 	/**
183 	 * Add a single repository to the set that is exported by this daemon.
184 	 * <p>
185 	 * The existence (or lack-thereof) of <code>git-daemon-export-ok</code> is
186 	 * ignored by this method. The repository is always published.
187 	 *
188 	 * @param name
189 	 *            name the repository will be published under.
190 	 * @param db
191 	 *            the repository instance.
192 	 */
193 	public void exportRepository(String name, Repository db) {
194 		exports.put(nameWithDotGit(name), db);
195 	}
196 
197 	/**
198 	 * Recursively export all Git repositories within a directory.
199 	 *
200 	 * @param dir
201 	 *            the directory to export. This directory must not itself be a
202 	 *            git repository, but any directory below it which has a file
203 	 *            named <code>git-daemon-export-ok</code> will be published.
204 	 */
205 	public void exportDirectory(File dir) {
206 		exportBase.add(dir);
207 	}
208 
209 	/**
210 	 * Check if this repository can be served.
211 	 * <p>
212 	 * The default implementation of this method returns true only if either
213 	 * {@link #isExportAll()} is true, or the {@code git-daemon-export-ok} file
214 	 * is present in the repository's directory.
215 	 *
216 	 * @param req
217 	 *            the current HTTP request.
218 	 * @param repositoryName
219 	 *            name of the repository, as present in the URL.
220 	 * @param db
221 	 *            the opened repository instance.
222 	 * @return true if the repository is accessible; false if not.
223 	 * @throws java.io.IOException
224 	 *             the repository could not be accessed, the caller will claim
225 	 *             the repository does not exist.
226 	 */
227 	protected boolean isExportOk(C req, String repositoryName, Repository db)
228 			throws IOException {
229 		if (isExportAll())
230 			return true;
231 		else if (db.getDirectory() != null)
232 			return new File(db.getDirectory(), "git-daemon-export-ok").exists(); //$NON-NLS-1$
233 		else
234 			return false;
235 	}
236 
237 	private static String nameWithDotGit(String name) {
238 		if (name.endsWith(Constants.DOT_GIT_EXT))
239 			return name;
240 		return name + Constants.DOT_GIT_EXT;
241 	}
242 
243 	private static boolean isUnreasonableName(String name) {
244 		if (name.length() == 0)
245 			return true; // no empty paths
246 
247 		if (name.indexOf('\\') >= 0)
248 			return true; // no windows/dos style paths
249 		if (new File(name).isAbsolute())
250 			return true; // no absolute paths
251 
252 		if (name.startsWith("../")) //$NON-NLS-1$
253 			return true; // no "l../etc/passwd"
254 		if (name.contains("/../")) //$NON-NLS-1$
255 			return true; // no "foo/../etc/passwd"
256 		if (name.contains("/./")) //$NON-NLS-1$
257 			return true; // "foo/./foo" is insane to ask
258 		if (name.contains("//")) //$NON-NLS-1$
259 			return true; // double slashes is sloppy, don't use it
260 
261 		return false; // is a reasonable name
262 	}
263 }