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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright (C) 2013 gitblit.com
  3. * Copyright (C) 2008-2009, Google Inc.
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package com.gitblit.git;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.io.InterruptedIOException;
  49. import java.io.OutputStream;
  50. import java.net.InetSocketAddress;
  51. import java.net.ServerSocket;
  52. import java.net.Socket;
  53. import java.net.SocketAddress;
  54. import java.text.MessageFormat;
  55. import java.util.concurrent.atomic.AtomicBoolean;
  56. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.transport.ReceivePack;
  60. import org.eclipse.jgit.transport.ServiceMayNotContinueException;
  61. import org.eclipse.jgit.transport.UploadPack;
  62. import org.eclipse.jgit.transport.resolver.ReceivePackFactory;
  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. import org.slf4j.Logger;
  67. import org.slf4j.LoggerFactory;
  68. import com.gitblit.utils.StringUtils;
  69. /**
  70. * Gitblit's Git Daemon ignores any and all per-repository daemon settings and
  71. * integrates into Gitblit's security model.
  72. *
  73. * @author James Moger
  74. *
  75. */
  76. public class GitDaemon {
  77. private final Logger logger = LoggerFactory.getLogger(GitDaemon.class);
  78. /** 9418: IANA assigned port number for Git. */
  79. public static final int DEFAULT_PORT = 9418;
  80. private static final int BACKLOG = 5;
  81. private InetSocketAddress myAddress;
  82. private final GitDaemonService[] services;
  83. private final ThreadGroup processors;
  84. private AtomicBoolean run;
  85. private ServerSocket acceptSocket;
  86. private Thread acceptThread;
  87. private int timeout;
  88. private RepositoryResolver<GitDaemonClient> repositoryResolver;
  89. private UploadPackFactory<GitDaemonClient> uploadPackFactory;
  90. private ReceivePackFactory<GitDaemonClient> receivePackFactory;
  91. /** Configure a daemon to listen on any available network port. */
  92. public GitDaemon() {
  93. this(null);
  94. }
  95. /**
  96. * Construct the Gitblit Git daemon.
  97. *
  98. * @param bindInterface
  99. * the ip address of the interface to bind
  100. * @param port
  101. * the port to serve on
  102. * @param folder
  103. * the folder to serve from
  104. */
  105. public GitDaemon(String bindInterface, int port, File folder) {
  106. this(StringUtils.isEmpty(bindInterface) ? new InetSocketAddress(port)
  107. : new InetSocketAddress(bindInterface, port));
  108. // set the repository resolver and pack factories
  109. repositoryResolver = new RepositoryResolver<GitDaemonClient>(folder);
  110. }
  111. /**
  112. * Configure a new daemon for the specified network address.
  113. *
  114. * @param addr
  115. * address to listen for connections on. If null, any available
  116. * port will be chosen on all network interfaces.
  117. */
  118. public GitDaemon(final InetSocketAddress addr) {
  119. myAddress = addr;
  120. processors = new ThreadGroup("Git-Daemon");
  121. run = new AtomicBoolean(false);
  122. repositoryResolver = null;
  123. uploadPackFactory = new GitblitUploadPackFactory<GitDaemonClient>();
  124. receivePackFactory = new GitblitReceivePackFactory<GitDaemonClient>();
  125. services = new GitDaemonService[] { new GitDaemonService("upload-pack", "uploadpack") {
  126. {
  127. setEnabled(true);
  128. setOverridable(false);
  129. }
  130. @Override
  131. protected void execute(final GitDaemonClient dc, final Repository db)
  132. throws IOException, ServiceNotEnabledException,
  133. ServiceNotAuthorizedException {
  134. UploadPack up = uploadPackFactory.create(dc, db);
  135. InputStream in = dc.getInputStream();
  136. OutputStream out = dc.getOutputStream();
  137. up.upload(in, out, null);
  138. }
  139. }, new GitDaemonService("receive-pack", "receivepack") {
  140. {
  141. setEnabled(true);
  142. setOverridable(false);
  143. }
  144. @Override
  145. protected void execute(final GitDaemonClient dc, final Repository db)
  146. throws IOException, ServiceNotEnabledException,
  147. ServiceNotAuthorizedException {
  148. ReceivePack rp = receivePackFactory.create(dc, db);
  149. InputStream in = dc.getInputStream();
  150. OutputStream out = dc.getOutputStream();
  151. rp.receive(in, out, null);
  152. }
  153. } };
  154. }
  155. /** @return timeout (in seconds) before aborting an IO operation. */
  156. public int getTimeout() {
  157. return timeout;
  158. }
  159. /**
  160. * Set the timeout before willing to abort an IO call.
  161. *
  162. * @param seconds
  163. * number of seconds to wait (with no data transfer occurring)
  164. * before aborting an IO read or write operation with the
  165. * connected client.
  166. */
  167. public void setTimeout(final int seconds) {
  168. timeout = seconds;
  169. }
  170. /**
  171. * Start this daemon on a background thread.
  172. *
  173. * @throws IOException
  174. * the server socket could not be opened.
  175. * @throws IllegalStateException
  176. * the daemon is already running.
  177. */
  178. public synchronized void start() throws IOException {
  179. if (acceptThread != null)
  180. throw new IllegalStateException(JGitText.get().daemonAlreadyRunning);
  181. final ServerSocket listenSock = new ServerSocket(myAddress != null ? myAddress.getPort()
  182. : 0, BACKLOG, myAddress != null ? myAddress.getAddress() : null);
  183. myAddress = (InetSocketAddress) listenSock.getLocalSocketAddress();
  184. run.set(true);
  185. acceptSocket = listenSock;
  186. acceptThread = new Thread(processors, "Git-Daemon-Accept") {
  187. public void run() {
  188. while (isRunning()) {
  189. try {
  190. startClient(listenSock.accept());
  191. } catch (InterruptedIOException e) {
  192. // Test again to see if we should keep accepting.
  193. } catch (IOException e) {
  194. break;
  195. }
  196. }
  197. try {
  198. listenSock.close();
  199. } catch (IOException err) {
  200. //
  201. } finally {
  202. acceptSocket = null;
  203. acceptThread = null;
  204. }
  205. }
  206. };
  207. acceptThread.start();
  208. logger.info(MessageFormat.format("Git Daemon is listening on {0}:{1,number,0}", myAddress.getAddress().getHostAddress(), myAddress.getPort()));
  209. }
  210. /** @return true if this daemon is receiving connections. */
  211. public boolean isRunning() {
  212. return run.get();
  213. }
  214. /** Stop this daemon. */
  215. public synchronized void stop() {
  216. if (acceptThread != null) {
  217. logger.info("Git Daemon stopping...");
  218. run.set(false);
  219. try {
  220. // close the accept socket
  221. // this throws a SocketException in the accept thread
  222. acceptSocket.close();
  223. } catch (IOException e1) {
  224. }
  225. try {
  226. // join the accept thread
  227. acceptThread.join();
  228. logger.info("Git Daemon stopped.");
  229. } catch (InterruptedException e) {
  230. logger.error("Accept thread join interrupted", e);
  231. }
  232. }
  233. }
  234. private void startClient(final Socket s) {
  235. final GitDaemonClient dc = new GitDaemonClient(this);
  236. final SocketAddress peer = s.getRemoteSocketAddress();
  237. if (peer instanceof InetSocketAddress)
  238. dc.setRemoteAddress(((InetSocketAddress) peer).getAddress());
  239. new Thread(processors, "Git-Daemon-Client " + peer.toString()) {
  240. public void run() {
  241. try {
  242. dc.execute(s);
  243. } catch (ServiceNotEnabledException e) {
  244. // Ignored. Client cannot use this repository.
  245. } catch (ServiceNotAuthorizedException e) {
  246. // Ignored. Client cannot use this repository.
  247. } catch (IOException e) {
  248. // Ignore unexpected IO exceptions from clients
  249. } finally {
  250. try {
  251. s.getInputStream().close();
  252. } catch (IOException e) {
  253. // Ignore close exceptions
  254. }
  255. try {
  256. s.getOutputStream().close();
  257. } catch (IOException e) {
  258. // Ignore close exceptions
  259. }
  260. }
  261. }
  262. }.start();
  263. }
  264. synchronized GitDaemonService matchService(final String cmd) {
  265. for (final GitDaemonService d : services) {
  266. if (d.handles(cmd))
  267. return d;
  268. }
  269. return null;
  270. }
  271. Repository openRepository(GitDaemonClient client, String name)
  272. throws ServiceMayNotContinueException {
  273. // Assume any attempt to use \ was by a Windows client
  274. // and correct to the more typical / used in Git URIs.
  275. //
  276. name = name.replace('\\', '/');
  277. // git://thishost/path should always be name="/path" here
  278. //
  279. if (!name.startsWith("/")) //$NON-NLS-1$
  280. return null;
  281. try {
  282. return repositoryResolver.open(client, name.substring(1));
  283. } catch (RepositoryNotFoundException e) {
  284. // null signals it "wasn't found", which is all that is suitable
  285. // for the remote client to know.
  286. return null;
  287. } catch (ServiceNotEnabledException e) {
  288. // null signals it "wasn't found", which is all that is suitable
  289. // for the remote client to know.
  290. return null;
  291. }
  292. }
  293. }