Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TransportGitSsh.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * Copyright (C) 2008-2010, Google Inc.
  3. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  4. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.transport;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.OutputStream;
  50. import java.io.PipedInputStream;
  51. import java.io.PipedOutputStream;
  52. import java.text.MessageFormat;
  53. import java.util.ArrayList;
  54. import java.util.List;
  55. import org.eclipse.jgit.JGitText;
  56. import org.eclipse.jgit.errors.NoRemoteRepositoryException;
  57. import org.eclipse.jgit.errors.TransportException;
  58. import org.eclipse.jgit.lib.Constants;
  59. import org.eclipse.jgit.lib.Repository;
  60. import org.eclipse.jgit.util.QuotedString;
  61. import org.eclipse.jgit.util.SystemReader;
  62. import org.eclipse.jgit.util.io.MessageWriter;
  63. import org.eclipse.jgit.util.io.StreamCopyThread;
  64. import com.jcraft.jsch.ChannelExec;
  65. import com.jcraft.jsch.JSchException;
  66. /**
  67. * Transport through an SSH tunnel.
  68. * <p>
  69. * The SSH transport requires the remote side to have Git installed, as the
  70. * transport logs into the remote system and executes a Git helper program on
  71. * the remote side to read (or write) the remote repository's files.
  72. * <p>
  73. * This transport does not support direct SCP style of copying files, as it
  74. * assumes there are Git specific smarts on the remote side to perform object
  75. * enumeration, save file modification and hook execution.
  76. */
  77. public class TransportGitSsh extends SshTransport implements PackTransport {
  78. static boolean canHandle(final URIish uri) {
  79. if (!uri.isRemote())
  80. return false;
  81. final String scheme = uri.getScheme();
  82. if ("ssh".equals(scheme))
  83. return true;
  84. if ("ssh+git".equals(scheme))
  85. return true;
  86. if ("git+ssh".equals(scheme))
  87. return true;
  88. if (scheme == null && uri.getHost() != null && uri.getPath() != null)
  89. return true;
  90. return false;
  91. }
  92. TransportGitSsh(final Repository local, final URIish uri) {
  93. super(local, uri);
  94. }
  95. @Override
  96. public FetchConnection openFetch() throws TransportException {
  97. return new SshFetchConnection(newConnection());
  98. }
  99. @Override
  100. public PushConnection openPush() throws TransportException {
  101. return new SshPushConnection(newConnection());
  102. }
  103. private Connection newConnection() {
  104. if (useExtConnection())
  105. return new ExtConnection();
  106. return new JschConnection();
  107. }
  108. private static void sqMinimal(final StringBuilder cmd, final String val) {
  109. if (val.matches("^[a-zA-Z0-9._/-]*$")) {
  110. // If the string matches only generally safe characters
  111. // that the shell is not going to evaluate specially we
  112. // should leave the string unquoted. Not all systems
  113. // actually run a shell and over-quoting confuses them
  114. // when it comes to the command name.
  115. //
  116. cmd.append(val);
  117. } else {
  118. sq(cmd, val);
  119. }
  120. }
  121. private static void sqAlways(final StringBuilder cmd, final String val) {
  122. sq(cmd, val);
  123. }
  124. private static void sq(final StringBuilder cmd, final String val) {
  125. if (val.length() > 0)
  126. cmd.append(QuotedString.BOURNE.quote(val));
  127. }
  128. String commandFor(final String exe) {
  129. String path = uri.getPath();
  130. if (uri.getScheme() != null && uri.getPath().startsWith("/~"))
  131. path = (uri.getPath().substring(1));
  132. final StringBuilder cmd = new StringBuilder();
  133. final int gitspace = exe.indexOf("git ");
  134. if (gitspace >= 0) {
  135. sqMinimal(cmd, exe.substring(0, gitspace + 3));
  136. cmd.append(' ');
  137. sqMinimal(cmd, exe.substring(gitspace + 4));
  138. } else
  139. sqMinimal(cmd, exe);
  140. cmd.append(' ');
  141. sqAlways(cmd, path);
  142. return cmd.toString();
  143. }
  144. void checkExecFailure(int status, String exe, String why)
  145. throws TransportException {
  146. if (status == 127) {
  147. IOException cause = null;
  148. if (why != null && why.length() > 0)
  149. cause = new IOException(why);
  150. throw new TransportException(uri, MessageFormat.format(
  151. JGitText.get().cannotExecute, commandFor(exe)), cause);
  152. }
  153. }
  154. NoRemoteRepositoryException cleanNotFound(NoRemoteRepositoryException nf,
  155. String why) {
  156. if (why == null || why.length() == 0)
  157. return nf;
  158. String path = uri.getPath();
  159. if (uri.getScheme() != null && uri.getPath().startsWith("/~"))
  160. path = uri.getPath().substring(1);
  161. final StringBuilder pfx = new StringBuilder();
  162. pfx.append("fatal: ");
  163. sqAlways(pfx, path);
  164. pfx.append(": ");
  165. if (why.startsWith(pfx.toString()))
  166. why = why.substring(pfx.length());
  167. return new NoRemoteRepositoryException(uri, why);
  168. }
  169. private abstract class Connection {
  170. abstract void exec(String commandName) throws TransportException;
  171. abstract void connect() throws TransportException;
  172. abstract InputStream getInputStream() throws IOException;
  173. abstract OutputStream getOutputStream() throws IOException;
  174. abstract InputStream getErrorStream() throws IOException;
  175. abstract int getExitStatus();
  176. abstract void close();
  177. }
  178. private class JschConnection extends Connection {
  179. private ChannelExec channel;
  180. private int exitStatus;
  181. @Override
  182. void exec(String commandName) throws TransportException {
  183. initSession();
  184. try {
  185. channel = (ChannelExec) sock.openChannel("exec");
  186. channel.setCommand(commandFor(commandName));
  187. } catch (JSchException je) {
  188. throw new TransportException(uri, je.getMessage(), je);
  189. }
  190. }
  191. @Override
  192. void connect() throws TransportException {
  193. try {
  194. channel.connect(getTimeout() > 0 ? getTimeout() * 1000 : 0);
  195. if (!channel.isConnected())
  196. throw new TransportException(uri, "connection failed");
  197. } catch (JSchException e) {
  198. throw new TransportException(uri, e.getMessage(), e);
  199. }
  200. }
  201. @Override
  202. InputStream getInputStream() throws IOException {
  203. return channel.getInputStream();
  204. }
  205. @Override
  206. OutputStream getOutputStream() throws IOException {
  207. // JSch won't let us interrupt writes when we use our InterruptTimer
  208. // to break out of a long-running write operation. To work around
  209. // that we spawn a background thread to shuttle data through a pipe,
  210. // as we can issue an interrupted write out of that. Its slower, so
  211. // we only use this route if there is a timeout.
  212. //
  213. final OutputStream out = channel.getOutputStream();
  214. if (getTimeout() <= 0)
  215. return out;
  216. final PipedInputStream pipeIn = new PipedInputStream();
  217. final StreamCopyThread copier = new StreamCopyThread(pipeIn, out);
  218. final PipedOutputStream pipeOut = new PipedOutputStream(pipeIn) {
  219. @Override
  220. public void flush() throws IOException {
  221. super.flush();
  222. copier.flush();
  223. }
  224. @Override
  225. public void close() throws IOException {
  226. super.close();
  227. try {
  228. copier.join(getTimeout() * 1000);
  229. } catch (InterruptedException e) {
  230. // Just wake early, the thread will terminate anyway.
  231. }
  232. }
  233. };
  234. copier.start();
  235. return pipeOut;
  236. }
  237. @Override
  238. InputStream getErrorStream() throws IOException {
  239. return channel.getErrStream();
  240. }
  241. @Override
  242. int getExitStatus() {
  243. return exitStatus;
  244. }
  245. @Override
  246. void close() {
  247. if (channel != null) {
  248. try {
  249. exitStatus = channel.getExitStatus();
  250. if (channel.isConnected())
  251. channel.disconnect();
  252. } finally {
  253. channel = null;
  254. }
  255. }
  256. }
  257. }
  258. private static boolean useExtConnection() {
  259. return SystemReader.getInstance().getenv("GIT_SSH") != null;
  260. }
  261. private class ExtConnection extends Connection {
  262. private Process proc;
  263. private int exitStatus;
  264. @Override
  265. void exec(String commandName) throws TransportException {
  266. String ssh = SystemReader.getInstance().getenv("GIT_SSH");
  267. boolean putty = ssh.toLowerCase().contains("plink");
  268. List<String> args = new ArrayList<String>();
  269. args.add(ssh);
  270. if (putty && !ssh.toLowerCase().contains("tortoiseplink"))
  271. args.add("-batch");
  272. if (0 < getURI().getPort()) {
  273. args.add(putty ? "-P" : "-p");
  274. args.add(String.valueOf(getURI().getPort()));
  275. }
  276. if (getURI().getUser() != null)
  277. args.add(getURI().getUser() + "@" + getURI().getHost());
  278. else
  279. args.add(getURI().getHost());
  280. args.add(commandFor(commandName));
  281. ProcessBuilder pb = new ProcessBuilder();
  282. pb.command(args);
  283. if (local.getDirectory() != null)
  284. pb.environment().put(Constants.GIT_DIR_KEY,
  285. local.getDirectory().getPath());
  286. try {
  287. proc = pb.start();
  288. } catch (IOException err) {
  289. throw new TransportException(uri, err.getMessage(), err);
  290. }
  291. }
  292. @Override
  293. void connect() throws TransportException {
  294. // Nothing to do, the process was already opened.
  295. }
  296. @Override
  297. InputStream getInputStream() throws IOException {
  298. return proc.getInputStream();
  299. }
  300. @Override
  301. OutputStream getOutputStream() throws IOException {
  302. return proc.getOutputStream();
  303. }
  304. @Override
  305. InputStream getErrorStream() throws IOException {
  306. return proc.getErrorStream();
  307. }
  308. @Override
  309. int getExitStatus() {
  310. return exitStatus;
  311. }
  312. @Override
  313. void close() {
  314. if (proc != null) {
  315. try {
  316. try {
  317. exitStatus = proc.waitFor();
  318. } catch (InterruptedException e) {
  319. // Ignore the interrupt, but return immediately.
  320. }
  321. } finally {
  322. proc = null;
  323. }
  324. }
  325. }
  326. }
  327. class SshFetchConnection extends BasePackFetchConnection {
  328. private Connection conn;
  329. private StreamCopyThread errorThread;
  330. SshFetchConnection(Connection conn) throws TransportException {
  331. super(TransportGitSsh.this);
  332. this.conn = conn;
  333. try {
  334. final MessageWriter msg = new MessageWriter();
  335. setMessageWriter(msg);
  336. conn.exec(getOptionUploadPack());
  337. final InputStream upErr = conn.getErrorStream();
  338. errorThread = new StreamCopyThread(upErr, msg.getRawStream());
  339. errorThread.start();
  340. init(conn.getInputStream(), conn.getOutputStream());
  341. conn.connect();
  342. } catch (TransportException err) {
  343. close();
  344. throw err;
  345. } catch (IOException err) {
  346. close();
  347. throw new TransportException(uri,
  348. JGitText.get().remoteHungUpUnexpectedly, err);
  349. }
  350. try {
  351. readAdvertisedRefs();
  352. } catch (NoRemoteRepositoryException notFound) {
  353. final String msgs = getMessages();
  354. checkExecFailure(conn.getExitStatus(), getOptionUploadPack(),
  355. msgs);
  356. throw cleanNotFound(notFound, msgs);
  357. }
  358. }
  359. @Override
  360. public void close() {
  361. endOut();
  362. if (errorThread != null) {
  363. try {
  364. errorThread.halt();
  365. } catch (InterruptedException e) {
  366. // Stop waiting and return anyway.
  367. } finally {
  368. errorThread = null;
  369. }
  370. }
  371. super.close();
  372. conn.close();
  373. }
  374. }
  375. class SshPushConnection extends BasePackPushConnection {
  376. private Connection conn;
  377. private StreamCopyThread errorThread;
  378. SshPushConnection(Connection conn) throws TransportException {
  379. super(TransportGitSsh.this);
  380. this.conn = conn;
  381. try {
  382. final MessageWriter msg = new MessageWriter();
  383. setMessageWriter(msg);
  384. conn.exec(getOptionReceivePack());
  385. final InputStream rpErr = conn.getErrorStream();
  386. errorThread = new StreamCopyThread(rpErr, msg.getRawStream());
  387. errorThread.start();
  388. init(conn.getInputStream(), conn.getOutputStream());
  389. conn.connect();
  390. } catch (TransportException err) {
  391. close();
  392. throw err;
  393. } catch (IOException err) {
  394. close();
  395. throw new TransportException(uri,
  396. JGitText.get().remoteHungUpUnexpectedly, err);
  397. }
  398. try {
  399. readAdvertisedRefs();
  400. } catch (NoRemoteRepositoryException notFound) {
  401. final String msgs = getMessages();
  402. checkExecFailure(conn.getExitStatus(), getOptionReceivePack(),
  403. msgs);
  404. throw cleanNotFound(notFound, msgs);
  405. }
  406. }
  407. @Override
  408. public void close() {
  409. endOut();
  410. if (errorThread != null) {
  411. try {
  412. errorThread.halt();
  413. } catch (InterruptedException e) {
  414. // Stop waiting and return anyway.
  415. } finally {
  416. errorThread = null;
  417. }
  418. }
  419. super.close();
  420. conn.close();
  421. }
  422. }
  423. }