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

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