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

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