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.

TransportSftp.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  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.BufferedReader;
  45. import java.io.FileNotFoundException;
  46. import java.io.IOException;
  47. import java.io.OutputStream;
  48. import java.text.MessageFormat;
  49. import java.util.ArrayList;
  50. import java.util.Collection;
  51. import java.util.Collections;
  52. import java.util.Comparator;
  53. import java.util.EnumSet;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Set;
  58. import java.util.TreeMap;
  59. import org.eclipse.jgit.errors.NotSupportedException;
  60. import org.eclipse.jgit.errors.TransportException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ObjectIdRef;
  65. import org.eclipse.jgit.lib.ProgressMonitor;
  66. import org.eclipse.jgit.lib.Ref;
  67. import org.eclipse.jgit.lib.Ref.Storage;
  68. import org.eclipse.jgit.lib.Repository;
  69. import org.eclipse.jgit.lib.SymbolicRef;
  70. import com.jcraft.jsch.Channel;
  71. import com.jcraft.jsch.ChannelSftp;
  72. import com.jcraft.jsch.JSchException;
  73. import com.jcraft.jsch.SftpATTRS;
  74. import com.jcraft.jsch.SftpException;
  75. /**
  76. * Transport over the non-Git aware SFTP (SSH based FTP) protocol.
  77. * <p>
  78. * The SFTP transport does not require any specialized Git support on the remote
  79. * (server side) repository. Object files are retrieved directly through secure
  80. * shell's FTP protocol, making it possible to copy objects from a remote
  81. * repository that is available over SSH, but whose remote host does not have
  82. * Git installed.
  83. * <p>
  84. * Unlike the HTTP variant (see {@link TransportHttp}) we rely upon being able
  85. * to list files in directories, as the SFTP protocol supports this function. By
  86. * listing files through SFTP we can avoid needing to have current
  87. * <code>objects/info/packs</code> or <code>info/refs</code> files on the
  88. * remote repository and access the data directly, much as Git itself would.
  89. * <p>
  90. * Concurrent pushing over this transport is not supported. Multiple concurrent
  91. * push operations may cause confusion in the repository state.
  92. *
  93. * @see WalkFetchConnection
  94. */
  95. public class TransportSftp extends SshTransport implements WalkTransport {
  96. static final TransportProtocol PROTO_SFTP = new TransportProtocol() {
  97. public String getName() {
  98. return JGitText.get().transportProtoSFTP;
  99. }
  100. public Set<String> getSchemes() {
  101. return Collections.singleton("sftp"); //$NON-NLS-1$
  102. }
  103. public Set<URIishField> getRequiredFields() {
  104. return Collections.unmodifiableSet(EnumSet.of(URIishField.HOST,
  105. URIishField.PATH));
  106. }
  107. public Set<URIishField> getOptionalFields() {
  108. return Collections.unmodifiableSet(EnumSet.of(URIishField.USER,
  109. URIishField.PASS, URIishField.PORT));
  110. }
  111. public int getDefaultPort() {
  112. return 22;
  113. }
  114. public Transport open(URIish uri, Repository local, String remoteName)
  115. throws NotSupportedException {
  116. return new TransportSftp(local, uri);
  117. }
  118. };
  119. TransportSftp(final Repository local, final URIish uri) {
  120. super(local, uri);
  121. }
  122. @Override
  123. public FetchConnection openFetch() throws TransportException {
  124. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  125. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  126. r.available(c.readAdvertisedRefs());
  127. return r;
  128. }
  129. @Override
  130. public PushConnection openPush() throws TransportException {
  131. final SftpObjectDB c = new SftpObjectDB(uri.getPath());
  132. final WalkPushConnection r = new WalkPushConnection(this, c);
  133. r.available(c.readAdvertisedRefs());
  134. return r;
  135. }
  136. ChannelSftp newSftp() throws TransportException {
  137. final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
  138. try {
  139. // @TODO: Fix so that this operation is generic and casting to
  140. // JschSession is no longer necessary.
  141. final Channel channel = ((JschSession) getSession())
  142. .getSftpChannel();
  143. channel.connect(tms);
  144. return (ChannelSftp) channel;
  145. } catch (JSchException je) {
  146. throw new TransportException(uri, je.getMessage(), je);
  147. }
  148. }
  149. class SftpObjectDB extends WalkRemoteObjectDatabase {
  150. private final String objectsPath;
  151. private ChannelSftp ftp;
  152. SftpObjectDB(String path) throws TransportException {
  153. if (path.startsWith("/~")) //$NON-NLS-1$
  154. path = path.substring(1);
  155. if (path.startsWith("~/")) //$NON-NLS-1$
  156. path = path.substring(2);
  157. try {
  158. ftp = newSftp();
  159. ftp.cd(path);
  160. ftp.cd("objects"); //$NON-NLS-1$
  161. objectsPath = ftp.pwd();
  162. } catch (TransportException err) {
  163. close();
  164. throw err;
  165. } catch (SftpException je) {
  166. throw new TransportException(MessageFormat.format(
  167. JGitText.get().cannotEnterObjectsPath, path,
  168. je.getMessage()), je);
  169. }
  170. }
  171. SftpObjectDB(final SftpObjectDB parent, final String p)
  172. throws TransportException {
  173. try {
  174. ftp = newSftp();
  175. ftp.cd(parent.objectsPath);
  176. ftp.cd(p);
  177. objectsPath = ftp.pwd();
  178. } catch (TransportException err) {
  179. close();
  180. throw err;
  181. } catch (SftpException je) {
  182. throw new TransportException(MessageFormat.format(
  183. JGitText.get().cannotEnterPathFromParent, p,
  184. parent.objectsPath, je.getMessage()), je);
  185. }
  186. }
  187. @Override
  188. URIish getURI() {
  189. return uri.setPath(objectsPath);
  190. }
  191. @Override
  192. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  193. try {
  194. return readAlternates(INFO_ALTERNATES);
  195. } catch (FileNotFoundException err) {
  196. return null;
  197. }
  198. }
  199. @Override
  200. WalkRemoteObjectDatabase openAlternate(final String location)
  201. throws IOException {
  202. return new SftpObjectDB(this, location);
  203. }
  204. @Override
  205. Collection<String> getPackNames() throws IOException {
  206. final List<String> packs = new ArrayList<String>();
  207. try {
  208. @SuppressWarnings("unchecked")
  209. final Collection<ChannelSftp.LsEntry> list = ftp.ls("pack"); //$NON-NLS-1$
  210. final HashMap<String, ChannelSftp.LsEntry> files;
  211. final HashMap<String, Integer> mtimes;
  212. files = new HashMap<String, ChannelSftp.LsEntry>();
  213. mtimes = new HashMap<String, Integer>();
  214. for (final ChannelSftp.LsEntry ent : list)
  215. files.put(ent.getFilename(), ent);
  216. for (final ChannelSftp.LsEntry ent : list) {
  217. final String n = ent.getFilename();
  218. if (!n.startsWith("pack-") || !n.endsWith(".pack")) //$NON-NLS-1$ //$NON-NLS-2$
  219. continue;
  220. final String in = n.substring(0, n.length() - 5) + ".idx"; //$NON-NLS-1$
  221. if (!files.containsKey(in))
  222. continue;
  223. mtimes.put(n, Integer.valueOf(ent.getAttrs().getMTime()));
  224. packs.add(n);
  225. }
  226. Collections.sort(packs, new Comparator<String>() {
  227. public int compare(final String o1, final String o2) {
  228. return mtimes.get(o2).intValue()
  229. - mtimes.get(o1).intValue();
  230. }
  231. });
  232. } catch (SftpException je) {
  233. throw new TransportException(
  234. MessageFormat.format(JGitText.get().cannotListPackPath,
  235. objectsPath, je.getMessage()),
  236. je);
  237. }
  238. return packs;
  239. }
  240. @Override
  241. FileStream open(final String path) throws IOException {
  242. try {
  243. final SftpATTRS a = ftp.lstat(path);
  244. return new FileStream(ftp.get(path), a.getSize());
  245. } catch (SftpException je) {
  246. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  247. throw new FileNotFoundException(path);
  248. throw new TransportException(MessageFormat.format(
  249. JGitText.get().cannotGetObjectsPath, objectsPath, path,
  250. je.getMessage()), je);
  251. }
  252. }
  253. @Override
  254. void deleteFile(final String path) throws IOException {
  255. try {
  256. ftp.rm(path);
  257. } catch (SftpException je) {
  258. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
  259. return;
  260. throw new TransportException(MessageFormat.format(
  261. JGitText.get().cannotDeleteObjectsPath, objectsPath,
  262. path, je.getMessage()), je);
  263. }
  264. // Prune any now empty directories.
  265. //
  266. String dir = path;
  267. int s = dir.lastIndexOf('/');
  268. while (s > 0) {
  269. try {
  270. dir = dir.substring(0, s);
  271. ftp.rmdir(dir);
  272. s = dir.lastIndexOf('/');
  273. } catch (SftpException je) {
  274. // If we cannot delete it, leave it alone. It may have
  275. // entries still in it, or maybe we lack write access on
  276. // the parent. Either way it isn't a fatal error.
  277. //
  278. break;
  279. }
  280. }
  281. }
  282. @Override
  283. OutputStream writeFile(final String path,
  284. final ProgressMonitor monitor, final String monitorTask)
  285. throws IOException {
  286. try {
  287. return ftp.put(path);
  288. } catch (SftpException je) {
  289. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  290. mkdir_p(path);
  291. try {
  292. return ftp.put(path);
  293. } catch (SftpException je2) {
  294. je = je2;
  295. }
  296. }
  297. throw new TransportException(MessageFormat.format(
  298. JGitText.get().cannotWriteObjectsPath, objectsPath,
  299. path, je.getMessage()), je);
  300. }
  301. }
  302. @Override
  303. void writeFile(final String path, final byte[] data) throws IOException {
  304. final String lock = path + ".lock"; //$NON-NLS-1$
  305. try {
  306. super.writeFile(lock, data);
  307. try {
  308. ftp.rename(lock, path);
  309. } catch (SftpException je) {
  310. throw new TransportException(MessageFormat.format(
  311. JGitText.get().cannotWriteObjectsPath, objectsPath,
  312. path, je.getMessage()), je);
  313. }
  314. } catch (IOException err) {
  315. try {
  316. ftp.rm(lock);
  317. } catch (SftpException e) {
  318. // Ignore deletion failure, we are already
  319. // failing anyway.
  320. }
  321. throw err;
  322. }
  323. }
  324. private void mkdir_p(String path) throws IOException {
  325. final int s = path.lastIndexOf('/');
  326. if (s <= 0)
  327. return;
  328. path = path.substring(0, s);
  329. try {
  330. ftp.mkdir(path);
  331. } catch (SftpException je) {
  332. if (je.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
  333. mkdir_p(path);
  334. try {
  335. ftp.mkdir(path);
  336. return;
  337. } catch (SftpException je2) {
  338. je = je2;
  339. }
  340. }
  341. throw new TransportException(MessageFormat.format(
  342. JGitText.get().cannotMkdirObjectPath, objectsPath, path,
  343. je.getMessage()), je);
  344. }
  345. }
  346. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  347. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  348. readPackedRefs(avail);
  349. readRef(avail, ROOT_DIR + Constants.HEAD, Constants.HEAD);
  350. readLooseRefs(avail, ROOT_DIR + "refs", "refs/"); //$NON-NLS-1$ //$NON-NLS-2$
  351. return avail;
  352. }
  353. @SuppressWarnings("unchecked")
  354. private void readLooseRefs(final TreeMap<String, Ref> avail,
  355. final String dir, final String prefix)
  356. throws TransportException {
  357. final Collection<ChannelSftp.LsEntry> list;
  358. try {
  359. list = ftp.ls(dir);
  360. } catch (SftpException je) {
  361. throw new TransportException(MessageFormat.format(
  362. JGitText.get().cannotListObjectsPath, objectsPath, dir,
  363. je.getMessage()), je);
  364. }
  365. for (final ChannelSftp.LsEntry ent : list) {
  366. final String n = ent.getFilename();
  367. if (".".equals(n) || "..".equals(n)) //$NON-NLS-1$ //$NON-NLS-2$
  368. continue;
  369. final String nPath = dir + "/" + n; //$NON-NLS-1$
  370. if (ent.getAttrs().isDir())
  371. readLooseRefs(avail, nPath, prefix + n + "/"); //$NON-NLS-1$
  372. else
  373. readRef(avail, nPath, prefix + n);
  374. }
  375. }
  376. private Ref readRef(final TreeMap<String, Ref> avail,
  377. final String path, final String name) throws TransportException {
  378. final String line;
  379. try {
  380. final BufferedReader br = openReader(path);
  381. try {
  382. line = br.readLine();
  383. } finally {
  384. br.close();
  385. }
  386. } catch (FileNotFoundException noRef) {
  387. return null;
  388. } catch (IOException err) {
  389. throw new TransportException(MessageFormat.format(
  390. JGitText.get().cannotReadObjectsPath, objectsPath, path,
  391. err.getMessage()), err);
  392. }
  393. if (line == null)
  394. throw new TransportException(
  395. MessageFormat.format(JGitText.get().emptyRef, name));
  396. if (line.startsWith("ref: ")) { //$NON-NLS-1$
  397. final String target = line.substring("ref: ".length()); //$NON-NLS-1$
  398. Ref r = avail.get(target);
  399. if (r == null)
  400. r = readRef(avail, ROOT_DIR + target, target);
  401. if (r == null)
  402. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  403. r = new SymbolicRef(name, r);
  404. avail.put(r.getName(), r);
  405. return r;
  406. }
  407. if (ObjectId.isId(line)) {
  408. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(name)),
  409. name, ObjectId.fromString(line));
  410. avail.put(r.getName(), r);
  411. return r;
  412. }
  413. throw new TransportException(
  414. MessageFormat.format(JGitText.get().badRef, name, line));
  415. }
  416. private Storage loose(final Ref r) {
  417. if (r != null && r.getStorage() == Storage.PACKED)
  418. return Storage.LOOSE_PACKED;
  419. return Storage.LOOSE;
  420. }
  421. @Override
  422. void close() {
  423. if (ftp != null) {
  424. try {
  425. if (ftp.isConnected())
  426. ftp.disconnect();
  427. } finally {
  428. ftp = null;
  429. }
  430. }
  431. }
  432. }
  433. }