You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Daemon.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*
  2. * Copyright (C) 2008-2009, 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. package org.eclipse.jgit.transport;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.io.InputStream;
  47. import java.io.InterruptedIOException;
  48. import java.net.InetAddress;
  49. import java.net.InetSocketAddress;
  50. import java.net.ServerSocket;
  51. import java.net.Socket;
  52. import java.net.SocketAddress;
  53. import java.util.Collection;
  54. import java.util.Map;
  55. import java.util.concurrent.ConcurrentHashMap;
  56. import java.util.concurrent.CopyOnWriteArrayList;
  57. import org.eclipse.jgit.JGitText;
  58. import org.eclipse.jgit.lib.Constants;
  59. import org.eclipse.jgit.lib.PersonIdent;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.lib.RepositoryCache;
  62. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  63. import org.eclipse.jgit.storage.pack.PackConfig;
  64. import org.eclipse.jgit.util.FS;
  65. /** Basic daemon for the anonymous <code>git://</code> transport protocol. */
  66. public class Daemon {
  67. /** 9418: IANA assigned port number for Git. */
  68. public static final int DEFAULT_PORT = 9418;
  69. private static final int BACKLOG = 5;
  70. private InetSocketAddress myAddress;
  71. private final DaemonService[] services;
  72. private final ThreadGroup processors;
  73. private volatile boolean exportAll;
  74. private Map<String, Repository> exports;
  75. private Collection<File> exportBase;
  76. private boolean run;
  77. private Thread acceptThread;
  78. private int timeout;
  79. private PackConfig packConfig;
  80. /** Configure a daemon to listen on any available network port. */
  81. public Daemon() {
  82. this(null);
  83. }
  84. /**
  85. * Configure a new daemon for the specified network address.
  86. *
  87. * @param addr
  88. * address to listen for connections on. If null, any available
  89. * port will be chosen on all network interfaces.
  90. */
  91. public Daemon(final InetSocketAddress addr) {
  92. myAddress = addr;
  93. exports = new ConcurrentHashMap<String, Repository>();
  94. exportBase = new CopyOnWriteArrayList<File>();
  95. processors = new ThreadGroup("Git-Daemon");
  96. services = new DaemonService[] {
  97. new DaemonService("upload-pack", "uploadpack") {
  98. {
  99. setEnabled(true);
  100. }
  101. @Override
  102. protected void execute(final DaemonClient dc,
  103. final Repository db) throws IOException {
  104. final UploadPack rp = new UploadPack(db);
  105. final InputStream in = dc.getInputStream();
  106. rp.setTimeout(Daemon.this.getTimeout());
  107. rp.setPackConfig(Daemon.this.packConfig);
  108. rp.upload(in, dc.getOutputStream(), null);
  109. }
  110. }, new DaemonService("receive-pack", "receivepack") {
  111. {
  112. setEnabled(false);
  113. }
  114. @Override
  115. protected void execute(final DaemonClient dc,
  116. final Repository db) throws IOException {
  117. final InetAddress peer = dc.getRemoteAddress();
  118. String host = peer.getCanonicalHostName();
  119. if (host == null)
  120. host = peer.getHostAddress();
  121. final ReceivePack rp = new ReceivePack(db);
  122. final InputStream in = dc.getInputStream();
  123. final String name = "anonymous";
  124. final String email = name + "@" + host;
  125. rp.setRefLogIdent(new PersonIdent(name, email));
  126. rp.setTimeout(Daemon.this.getTimeout());
  127. rp.receive(in, dc.getOutputStream(), null);
  128. }
  129. } };
  130. }
  131. /** @return the address connections are received on. */
  132. public synchronized InetSocketAddress getAddress() {
  133. return myAddress;
  134. }
  135. /**
  136. * Lookup a supported service so it can be reconfigured.
  137. *
  138. * @param name
  139. * name of the service; e.g. "receive-pack"/"git-receive-pack" or
  140. * "upload-pack"/"git-upload-pack".
  141. * @return the service; null if this daemon implementation doesn't support
  142. * the requested service type.
  143. */
  144. public synchronized DaemonService getService(String name) {
  145. if (!name.startsWith("git-"))
  146. name = "git-" + name;
  147. for (final DaemonService s : services) {
  148. if (s.getCommandName().equals(name))
  149. return s;
  150. }
  151. return null;
  152. }
  153. /**
  154. * @return false if <code>git-daemon-export-ok</code> is required to export
  155. * a repository; true if <code>git-daemon-export-ok</code> is
  156. * ignored.
  157. * @see #setExportAll(boolean)
  158. */
  159. public boolean isExportAll() {
  160. return exportAll;
  161. }
  162. /**
  163. * Set whether or not to export all repositories.
  164. * <p>
  165. * If false (the default), repositories must have a
  166. * <code>git-daemon-export-ok</code> file to be accessed through this
  167. * daemon.
  168. * <p>
  169. * If true, all repositories are available through the daemon, whether or
  170. * not <code>git-daemon-export-ok</code> exists.
  171. *
  172. * @param export
  173. */
  174. public void setExportAll(final boolean export) {
  175. exportAll = export;
  176. }
  177. /**
  178. * Add a single repository to the set that is exported by this daemon.
  179. * <p>
  180. * The existence (or lack-thereof) of <code>git-daemon-export-ok</code> is
  181. * ignored by this method. The repository is always published.
  182. *
  183. * @param name
  184. * name the repository will be published under.
  185. * @param db
  186. * the repository instance.
  187. */
  188. public void exportRepository(String name, final Repository db) {
  189. if (!name.endsWith(Constants.DOT_GIT_EXT))
  190. name = name + Constants.DOT_GIT_EXT;
  191. exports.put(name, db);
  192. RepositoryCache.register(db);
  193. }
  194. /**
  195. * Recursively export all Git repositories within a directory.
  196. *
  197. * @param dir
  198. * the directory to export. This directory must not itself be a
  199. * git repository, but any directory below it which has a file
  200. * named <code>git-daemon-export-ok</code> will be published.
  201. */
  202. public void exportDirectory(final File dir) {
  203. exportBase.add(dir);
  204. }
  205. /** @return timeout (in seconds) before aborting an IO operation. */
  206. public int getTimeout() {
  207. return timeout;
  208. }
  209. /**
  210. * Set the timeout before willing to abort an IO call.
  211. *
  212. * @param seconds
  213. * number of seconds to wait (with no data transfer occurring)
  214. * before aborting an IO read or write operation with the
  215. * connected client.
  216. */
  217. public void setTimeout(final int seconds) {
  218. timeout = seconds;
  219. }
  220. /**
  221. * Set the configuration used by the pack generator.
  222. *
  223. * @param pc
  224. * configuration controlling packing parameters. If null the
  225. * source repository's settings will be used.
  226. */
  227. public void setPackConfig(PackConfig pc) {
  228. this.packConfig = pc;
  229. }
  230. /**
  231. * Start this daemon on a background thread.
  232. *
  233. * @throws IOException
  234. * the server socket could not be opened.
  235. * @throws IllegalStateException
  236. * the daemon is already running.
  237. */
  238. public synchronized void start() throws IOException {
  239. if (acceptThread != null)
  240. throw new IllegalStateException(JGitText.get().daemonAlreadyRunning);
  241. final ServerSocket listenSock = new ServerSocket(
  242. myAddress != null ? myAddress.getPort() : 0, BACKLOG,
  243. myAddress != null ? myAddress.getAddress() : null);
  244. myAddress = (InetSocketAddress) listenSock.getLocalSocketAddress();
  245. run = true;
  246. acceptThread = new Thread(processors, "Git-Daemon-Accept") {
  247. public void run() {
  248. while (isRunning()) {
  249. try {
  250. startClient(listenSock.accept());
  251. } catch (InterruptedIOException e) {
  252. // Test again to see if we should keep accepting.
  253. } catch (IOException e) {
  254. break;
  255. }
  256. }
  257. try {
  258. listenSock.close();
  259. } catch (IOException err) {
  260. //
  261. } finally {
  262. synchronized (Daemon.this) {
  263. acceptThread = null;
  264. }
  265. }
  266. }
  267. };
  268. acceptThread.start();
  269. }
  270. /** @return true if this daemon is receiving connections. */
  271. public synchronized boolean isRunning() {
  272. return run;
  273. }
  274. /** Stop this daemon. */
  275. public synchronized void stop() {
  276. if (acceptThread != null) {
  277. run = false;
  278. acceptThread.interrupt();
  279. }
  280. }
  281. private void startClient(final Socket s) {
  282. final DaemonClient dc = new DaemonClient(this);
  283. final SocketAddress peer = s.getRemoteSocketAddress();
  284. if (peer instanceof InetSocketAddress)
  285. dc.setRemoteAddress(((InetSocketAddress) peer).getAddress());
  286. new Thread(processors, "Git-Daemon-Client " + peer.toString()) {
  287. public void run() {
  288. try {
  289. dc.execute(s);
  290. } catch (IOException e) {
  291. // Ignore unexpected IO exceptions from clients
  292. e.printStackTrace();
  293. } finally {
  294. try {
  295. s.getInputStream().close();
  296. } catch (IOException e) {
  297. // Ignore close exceptions
  298. }
  299. try {
  300. s.getOutputStream().close();
  301. } catch (IOException e) {
  302. // Ignore close exceptions
  303. }
  304. }
  305. }
  306. }.start();
  307. }
  308. synchronized DaemonService matchService(final String cmd) {
  309. for (final DaemonService d : services) {
  310. if (d.handles(cmd))
  311. return d;
  312. }
  313. return null;
  314. }
  315. Repository openRepository(String name) {
  316. // Assume any attempt to use \ was by a Windows client
  317. // and correct to the more typical / used in Git URIs.
  318. //
  319. name = name.replace('\\', '/');
  320. // git://thishost/path should always be name="/path" here
  321. //
  322. if (!name.startsWith("/"))
  323. return null;
  324. // Forbid Windows UNC paths as they might escape the base
  325. //
  326. if (name.startsWith("//"))
  327. return null;
  328. // Forbid funny paths which contain an up-reference, they
  329. // might be trying to escape and read /../etc/password.
  330. //
  331. if (name.contains("/../"))
  332. return null;
  333. name = name.substring(1);
  334. Repository db;
  335. db = exports.get(name.endsWith(Constants.DOT_GIT_EXT) ? name : name
  336. + Constants.DOT_GIT_EXT);
  337. if (db != null) {
  338. db.incrementOpen();
  339. return db;
  340. }
  341. for (final File baseDir : exportBase) {
  342. final File gitdir = FileKey.resolve(new File(baseDir, name), FS.DETECTED);
  343. if (gitdir != null && canExport(gitdir))
  344. return openRepository(gitdir);
  345. }
  346. return null;
  347. }
  348. private static Repository openRepository(final File gitdir) {
  349. try {
  350. return RepositoryCache.open(FileKey.exact(gitdir, FS.DETECTED));
  351. } catch (IOException err) {
  352. // null signals it "wasn't found", which is all that is suitable
  353. // for the remote client to know.
  354. return null;
  355. }
  356. }
  357. private boolean canExport(final File d) {
  358. if (isExportAll()) {
  359. return true;
  360. }
  361. return new File(d, "git-daemon-export-ok").exists();
  362. }
  363. }