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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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.IOException;
  45. import java.io.InputStream;
  46. import java.io.OutputStream;
  47. import java.net.InetAddress;
  48. import java.net.InetSocketAddress;
  49. import java.net.ServerSocket;
  50. import java.net.Socket;
  51. import java.net.SocketAddress;
  52. import java.net.SocketException;
  53. import java.util.concurrent.atomic.AtomicBoolean;
  54. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  55. import org.eclipse.jgit.internal.JGitText;
  56. import org.eclipse.jgit.lib.PersonIdent;
  57. import org.eclipse.jgit.lib.Repository;
  58. import org.eclipse.jgit.storage.pack.PackConfig;
  59. import org.eclipse.jgit.transport.resolver.ReceivePackFactory;
  60. import org.eclipse.jgit.transport.resolver.RepositoryResolver;
  61. import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
  62. import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;
  63. import org.eclipse.jgit.transport.resolver.UploadPackFactory;
  64. /**
  65. * Basic daemon for the anonymous <code>git://</code> transport protocol.
  66. */
  67. public class Daemon {
  68. /** 9418: IANA assigned port number for Git. */
  69. public static final int DEFAULT_PORT = 9418;
  70. private static final int BACKLOG = 5;
  71. private InetSocketAddress myAddress;
  72. private final DaemonService[] services;
  73. private final ThreadGroup processors;
  74. private Acceptor acceptThread;
  75. private int timeout;
  76. private PackConfig packConfig;
  77. private volatile RepositoryResolver<DaemonClient> repositoryResolver;
  78. volatile UploadPackFactory<DaemonClient> uploadPackFactory;
  79. volatile ReceivePackFactory<DaemonClient> receivePackFactory;
  80. /**
  81. * Configure a daemon to listen on any available network port.
  82. */
  83. public Daemon() {
  84. this(null);
  85. }
  86. /**
  87. * Configure a new daemon for the specified network address.
  88. *
  89. * @param addr
  90. * address to listen for connections on. If null, any available
  91. * port will be chosen on all network interfaces.
  92. */
  93. @SuppressWarnings("unchecked")
  94. public Daemon(final InetSocketAddress addr) {
  95. myAddress = addr;
  96. processors = new ThreadGroup("Git-Daemon"); //$NON-NLS-1$
  97. repositoryResolver = (RepositoryResolver<DaemonClient>) RepositoryResolver.NONE;
  98. uploadPackFactory = new UploadPackFactory<DaemonClient>() {
  99. @Override
  100. public UploadPack create(DaemonClient req, Repository db)
  101. throws ServiceNotEnabledException,
  102. ServiceNotAuthorizedException {
  103. UploadPack up = new UploadPack(db);
  104. up.setTimeout(getTimeout());
  105. up.setPackConfig(getPackConfig());
  106. return up;
  107. }
  108. };
  109. receivePackFactory = new ReceivePackFactory<DaemonClient>() {
  110. @Override
  111. public ReceivePack create(DaemonClient req, Repository db)
  112. throws ServiceNotEnabledException,
  113. ServiceNotAuthorizedException {
  114. ReceivePack rp = new ReceivePack(db);
  115. InetAddress peer = req.getRemoteAddress();
  116. String host = peer.getCanonicalHostName();
  117. if (host == null)
  118. host = peer.getHostAddress();
  119. String name = "anonymous"; //$NON-NLS-1$
  120. String email = name + "@" + host; //$NON-NLS-1$
  121. rp.setRefLogIdent(new PersonIdent(name, email));
  122. rp.setTimeout(getTimeout());
  123. return rp;
  124. }
  125. };
  126. services = new DaemonService[] {
  127. new DaemonService("upload-pack", "uploadpack") { //$NON-NLS-1$ //$NON-NLS-2$
  128. {
  129. setEnabled(true);
  130. }
  131. @Override
  132. protected void execute(final DaemonClient dc,
  133. final Repository db) throws IOException,
  134. ServiceNotEnabledException,
  135. ServiceNotAuthorizedException {
  136. UploadPack up = uploadPackFactory.create(dc, db);
  137. InputStream in = dc.getInputStream();
  138. OutputStream out = dc.getOutputStream();
  139. up.upload(in, out, null);
  140. }
  141. }, new DaemonService("receive-pack", "receivepack") { //$NON-NLS-1$ //$NON-NLS-2$
  142. {
  143. setEnabled(false);
  144. }
  145. @Override
  146. protected void execute(final DaemonClient dc,
  147. final Repository db) throws IOException,
  148. ServiceNotEnabledException,
  149. ServiceNotAuthorizedException {
  150. ReceivePack rp = receivePackFactory.create(dc, db);
  151. InputStream in = dc.getInputStream();
  152. OutputStream out = dc.getOutputStream();
  153. rp.receive(in, out, null);
  154. }
  155. } };
  156. }
  157. /**
  158. * Get the address connections are received on.
  159. *
  160. * @return the address connections are received on.
  161. */
  162. public synchronized InetSocketAddress getAddress() {
  163. return myAddress;
  164. }
  165. /**
  166. * Lookup a supported service so it can be reconfigured.
  167. *
  168. * @param name
  169. * name of the service; e.g. "receive-pack"/"git-receive-pack" or
  170. * "upload-pack"/"git-upload-pack".
  171. * @return the service; null if this daemon implementation doesn't support
  172. * the requested service type.
  173. */
  174. public synchronized DaemonService getService(String name) {
  175. if (!name.startsWith("git-")) //$NON-NLS-1$
  176. name = "git-" + name; //$NON-NLS-1$
  177. for (final DaemonService s : services) {
  178. if (s.getCommandName().equals(name))
  179. return s;
  180. }
  181. return null;
  182. }
  183. /**
  184. * Get timeout (in seconds) before aborting an IO operation.
  185. *
  186. * @return timeout (in seconds) before aborting an IO operation.
  187. */
  188. public int getTimeout() {
  189. return timeout;
  190. }
  191. /**
  192. * Set the timeout before willing to abort an IO call.
  193. *
  194. * @param seconds
  195. * number of seconds to wait (with no data transfer occurring)
  196. * before aborting an IO read or write operation with the
  197. * connected client.
  198. */
  199. public void setTimeout(final int seconds) {
  200. timeout = seconds;
  201. }
  202. /**
  203. * Get configuration controlling packing, may be null.
  204. *
  205. * @return configuration controlling packing, may be null.
  206. */
  207. public PackConfig getPackConfig() {
  208. return packConfig;
  209. }
  210. /**
  211. * Set the configuration used by the pack generator.
  212. *
  213. * @param pc
  214. * configuration controlling packing parameters. If null the
  215. * source repository's settings will be used.
  216. */
  217. public void setPackConfig(PackConfig pc) {
  218. this.packConfig = pc;
  219. }
  220. /**
  221. * Set the resolver used to locate a repository by name.
  222. *
  223. * @param resolver
  224. * the resolver instance.
  225. */
  226. public void setRepositoryResolver(RepositoryResolver<DaemonClient> resolver) {
  227. repositoryResolver = resolver;
  228. }
  229. /**
  230. * Set the factory to construct and configure per-request UploadPack.
  231. *
  232. * @param factory
  233. * the factory. If null upload-pack is disabled.
  234. */
  235. @SuppressWarnings("unchecked")
  236. public void setUploadPackFactory(UploadPackFactory<DaemonClient> factory) {
  237. if (factory != null)
  238. uploadPackFactory = factory;
  239. else
  240. uploadPackFactory = (UploadPackFactory<DaemonClient>) UploadPackFactory.DISABLED;
  241. }
  242. /**
  243. * Get the factory used to construct per-request ReceivePack.
  244. *
  245. * @return the factory.
  246. * @since 4.3
  247. */
  248. public ReceivePackFactory<DaemonClient> getReceivePackFactory() {
  249. return receivePackFactory;
  250. }
  251. /**
  252. * Set the factory to construct and configure per-request ReceivePack.
  253. *
  254. * @param factory
  255. * the factory. If null receive-pack is disabled.
  256. */
  257. @SuppressWarnings("unchecked")
  258. public void setReceivePackFactory(ReceivePackFactory<DaemonClient> factory) {
  259. if (factory != null)
  260. receivePackFactory = factory;
  261. else
  262. receivePackFactory = (ReceivePackFactory<DaemonClient>) ReceivePackFactory.DISABLED;
  263. }
  264. private class Acceptor extends Thread {
  265. private final ServerSocket listenSocket;
  266. private final AtomicBoolean running = new AtomicBoolean(true);
  267. public Acceptor(ThreadGroup group, String name, ServerSocket socket) {
  268. super(group, name);
  269. this.listenSocket = socket;
  270. }
  271. @Override
  272. public void run() {
  273. setUncaughtExceptionHandler((thread, throwable) -> terminate());
  274. while (isRunning()) {
  275. try {
  276. startClient(listenSocket.accept());
  277. } catch (SocketException e) {
  278. // Test again to see if we should keep accepting.
  279. } catch (IOException e) {
  280. break;
  281. }
  282. }
  283. terminate();
  284. }
  285. private void terminate() {
  286. try {
  287. shutDown();
  288. } finally {
  289. clearThread();
  290. }
  291. }
  292. public boolean isRunning() {
  293. return running.get();
  294. }
  295. public void shutDown() {
  296. running.set(false);
  297. try {
  298. listenSocket.close();
  299. } catch (IOException err) {
  300. //
  301. }
  302. }
  303. }
  304. /**
  305. * Start this daemon on a background thread.
  306. *
  307. * @throws java.io.IOException
  308. * the server socket could not be opened.
  309. * @throws java.lang.IllegalStateException
  310. * the daemon is already running.
  311. */
  312. public synchronized void start() throws IOException {
  313. if (acceptThread != null) {
  314. throw new IllegalStateException(JGitText.get().daemonAlreadyRunning);
  315. }
  316. ServerSocket socket = new ServerSocket();
  317. socket.setReuseAddress(true);
  318. if (myAddress != null) {
  319. socket.bind(myAddress, BACKLOG);
  320. } else {
  321. socket.bind(new InetSocketAddress((InetAddress) null, 0), BACKLOG);
  322. }
  323. myAddress = (InetSocketAddress) socket.getLocalSocketAddress();
  324. acceptThread = new Acceptor(processors, "Git-Daemon-Accept", socket); //$NON-NLS-1$
  325. acceptThread.start();
  326. }
  327. private synchronized void clearThread() {
  328. acceptThread = null;
  329. }
  330. /**
  331. * Whether this daemon is receiving connections.
  332. *
  333. * @return {@code true} if this daemon is receiving connections.
  334. */
  335. public synchronized boolean isRunning() {
  336. return acceptThread != null && acceptThread.isRunning();
  337. }
  338. /**
  339. * Stop this daemon.
  340. */
  341. public synchronized void stop() {
  342. if (acceptThread != null) {
  343. acceptThread.shutDown();
  344. }
  345. }
  346. /**
  347. * Stops this daemon and waits until it's acceptor thread has finished.
  348. *
  349. * @throws java.lang.InterruptedException
  350. * if waiting for the acceptor thread is interrupted
  351. * @since 4.9
  352. */
  353. public void stopAndWait() throws InterruptedException {
  354. Thread acceptor = null;
  355. synchronized (this) {
  356. acceptor = acceptThread;
  357. stop();
  358. }
  359. if (acceptor != null) {
  360. acceptor.join();
  361. }
  362. }
  363. void startClient(final Socket s) {
  364. final DaemonClient dc = new DaemonClient(this);
  365. final SocketAddress peer = s.getRemoteSocketAddress();
  366. if (peer instanceof InetSocketAddress)
  367. dc.setRemoteAddress(((InetSocketAddress) peer).getAddress());
  368. new Thread(processors, "Git-Daemon-Client " + peer.toString()) { //$NON-NLS-1$
  369. @Override
  370. public void run() {
  371. try {
  372. dc.execute(s);
  373. } catch (ServiceNotEnabledException e) {
  374. // Ignored. Client cannot use this repository.
  375. } catch (ServiceNotAuthorizedException e) {
  376. // Ignored. Client cannot use this repository.
  377. } catch (IOException e) {
  378. // Ignore unexpected IO exceptions from clients
  379. } finally {
  380. try {
  381. s.getInputStream().close();
  382. } catch (IOException e) {
  383. // Ignore close exceptions
  384. }
  385. try {
  386. s.getOutputStream().close();
  387. } catch (IOException e) {
  388. // Ignore close exceptions
  389. }
  390. }
  391. }
  392. }.start();
  393. }
  394. synchronized DaemonService matchService(final String cmd) {
  395. for (final DaemonService d : services) {
  396. if (d.handles(cmd))
  397. return d;
  398. }
  399. return null;
  400. }
  401. Repository openRepository(DaemonClient client, String name)
  402. throws ServiceMayNotContinueException {
  403. // Assume any attempt to use \ was by a Windows client
  404. // and correct to the more typical / used in Git URIs.
  405. //
  406. name = name.replace('\\', '/');
  407. // git://thishost/path should always be name="/path" here
  408. //
  409. if (!name.startsWith("/")) //$NON-NLS-1$
  410. return null;
  411. try {
  412. return repositoryResolver.open(client, name.substring(1));
  413. } catch (RepositoryNotFoundException e) {
  414. // null signals it "wasn't found", which is all that is suitable
  415. // for the remote client to know.
  416. return null;
  417. } catch (ServiceNotAuthorizedException e) {
  418. // null signals it "wasn't found", which is all that is suitable
  419. // for the remote client to know.
  420. return null;
  421. } catch (ServiceNotEnabledException e) {
  422. // null signals it "wasn't found", which is all that is suitable
  423. // for the remote client to know.
  424. return null;
  425. }
  426. }
  427. }