View Javadoc
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  
44  package org.eclipse.jgit.transport;
45  
46  import static org.eclipse.jgit.transport.WalkRemoteObjectDatabase.ROOT_DIR;
47  
48  import java.io.BufferedOutputStream;
49  import java.io.IOException;
50  import java.io.OutputStream;
51  import java.util.ArrayList;
52  import java.util.Collection;
53  import java.util.HashSet;
54  import java.util.LinkedHashMap;
55  import java.util.List;
56  import java.util.Map;
57  import java.util.Set;
58  import java.util.TreeMap;
59  
60  import org.eclipse.jgit.errors.TransportException;
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.internal.storage.pack.PackWriter;
63  import org.eclipse.jgit.lib.AnyObjectId;
64  import org.eclipse.jgit.lib.Constants;
65  import org.eclipse.jgit.lib.ObjectId;
66  import org.eclipse.jgit.lib.ObjectIdRef;
67  import org.eclipse.jgit.lib.ProgressMonitor;
68  import org.eclipse.jgit.lib.Ref;
69  import org.eclipse.jgit.lib.Ref.Storage;
70  import org.eclipse.jgit.lib.RefWriter;
71  import org.eclipse.jgit.lib.Repository;
72  import org.eclipse.jgit.transport.RemoteRefUpdate.Status;
73  
74  /**
75   * Generic push support for dumb transport protocols.
76   * <p>
77   * Since there are no Git-specific smarts on the remote side of the connection
78   * the client side must handle everything on its own. The generic push support
79   * requires being able to delete, create and overwrite files on the remote side,
80   * as well as create any missing directories (if necessary). Typically this can
81   * be handled through an FTP style protocol.
82   * <p>
83   * Objects not on the remote side are uploaded as pack files, using one pack
84   * file per invocation. This simplifies the implementation as only two data
85   * files need to be written to the remote repository.
86   * <p>
87   * Push support supplied by this class is not multiuser safe. Concurrent pushes
88   * to the same repository may yield an inconsistent reference database which may
89   * confuse fetch clients.
90   * <p>
91   * A single push is concurrently safe with multiple fetch requests, due to the
92   * careful order of operations used to update the repository. Clients fetching
93   * may receive transient failures due to short reads on certain files if the
94   * protocol does not support atomic file replacement.
95   *
96   * @see WalkRemoteObjectDatabase
97   */
98  class WalkPushConnection extends BaseConnection implements PushConnection {
99  	/** The repository this transport pushes out of. */
100 	private final Repository local;
101 
102 	/** Location of the remote repository we are writing to. */
103 	private final URIish uri;
104 
105 	/** Database connection to the remote repository. */
106 	final WalkRemoteObjectDatabase dest;
107 
108 	/** The configured transport we were constructed by. */
109 	private final Transport transport;
110 
111 	/**
112 	 * Packs already known to reside in the remote repository.
113 	 * <p>
114 	 * This is a LinkedHashMap to maintain the original order.
115 	 */
116 	private LinkedHashMap<String, String> packNames;
117 
118 	/** Complete listing of refs the remote will have after our push. */
119 	private Map<String, Ref> newRefs;
120 
121 	/**
122 	 * Updates which require altering the packed-refs file to complete.
123 	 * <p>
124 	 * If this collection is non-empty then any refs listed in {@link #newRefs}
125 	 * with a storage class of {@link Storage#PACKED} will be written.
126 	 */
127 	private Collection<RemoteRefUpdate> packedRefUpdates;
128 
129 	WalkPushConnection(final WalkTransport walkTransport,
130 			final WalkRemoteObjectDatabase w) {
131 		transport = (Transport) walkTransport;
132 		local = transport.local;
133 		uri = transport.getURI();
134 		dest = w;
135 	}
136 
137 	@Override
138 	public void push(final ProgressMonitor monitor,
139 			final Map<String, RemoteRefUpdate> refUpdates)
140 			throws TransportException {
141 		push(monitor, refUpdates, null);
142 	}
143 
144 	@Override
145 	public void push(final ProgressMonitor monitor,
146 			final Map<String, RemoteRefUpdate> refUpdates, OutputStream out)
147 			throws TransportException {
148 		markStartedOperation();
149 		packNames = null;
150 		newRefs = new TreeMap<>(getRefsMap());
151 		packedRefUpdates = new ArrayList<>(refUpdates.size());
152 
153 		// Filter the commands and issue all deletes first. This way we
154 		// can correctly handle a directory being cleared out and a new
155 		// ref using the directory name being created.
156 		//
157 		final List<RemoteRefUpdate> updates = new ArrayList<>();
158 		for (final RemoteRefUpdate u : refUpdates.values()) {
159 			final String n = u.getRemoteName();
160 			if (!n.startsWith("refs/") || !Repository.isValidRefName(n)) { //$NON-NLS-1$
161 				u.setStatus(Status.REJECTED_OTHER_REASON);
162 				u.setMessage(JGitText.get().funnyRefname);
163 				continue;
164 			}
165 
166 			if (AnyObjectId.equals(ObjectId.zeroId(), u.getNewObjectId()))
167 				deleteCommand(u);
168 			else
169 				updates.add(u);
170 		}
171 
172 		// If we have any updates we need to upload the objects first, to
173 		// prevent creating refs pointing at non-existent data. Then we
174 		// can update the refs, and the info-refs file for dumb transports.
175 		//
176 		if (!updates.isEmpty())
177 			sendpack(updates, monitor);
178 		for (final RemoteRefUpdate u : updates)
179 			updateCommand(u);
180 
181 		// Is this a new repository? If so we should create additional
182 		// metadata files so it is properly initialized during the push.
183 		//
184 		if (!updates.isEmpty() && isNewRepository())
185 			createNewRepository(updates);
186 
187 		RefWriter refWriter = new RefWriter(newRefs.values()) {
188 			@Override
189 			protected void writeFile(String file, byte[] content)
190 					throws IOException {
191 				dest.writeFile(ROOT_DIR + file, content);
192 			}
193 		};
194 		if (!packedRefUpdates.isEmpty()) {
195 			try {
196 				refWriter.writePackedRefs();
197 				for (final RemoteRefUpdate u : packedRefUpdates)
198 					u.setStatus(Status.OK);
199 			} catch (IOException err) {
200 				for (final RemoteRefUpdate u : packedRefUpdates) {
201 					u.setStatus(Status.REJECTED_OTHER_REASON);
202 					u.setMessage(err.getMessage());
203 				}
204 				throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
205 			}
206 		}
207 
208 		try {
209 			refWriter.writeInfoRefs();
210 		} catch (IOException err) {
211 			throw new TransportException(uri, JGitText.get().failedUpdatingRefs, err);
212 		}
213 	}
214 
215 	@Override
216 	public void close() {
217 		dest.close();
218 	}
219 
220 	private void sendpack(final List<RemoteRefUpdate> updates,
221 			final ProgressMonitor monitor) throws TransportException {
222 		String pathPack = null;
223 		String pathIdx = null;
224 
225 		try (final PackWriter writer = new PackWriter(transport.getPackConfig(),
226 				local.newObjectReader())) {
227 
228 			final Set<ObjectId> need = new HashSet<>();
229 			final Set<ObjectId> have = new HashSet<>();
230 			for (final RemoteRefUpdate r : updates)
231 				need.add(r.getNewObjectId());
232 			for (final Ref r : getRefs()) {
233 				have.add(r.getObjectId());
234 				if (r.getPeeledObjectId() != null)
235 					have.add(r.getPeeledObjectId());
236 			}
237 			writer.preparePack(monitor, need, have);
238 
239 			// We don't have to continue further if the pack will
240 			// be an empty pack, as the remote has all objects it
241 			// needs to complete this change.
242 			//
243 			if (writer.getObjectCount() == 0)
244 				return;
245 
246 			packNames = new LinkedHashMap<>();
247 			for (final String n : dest.getPackNames())
248 				packNames.put(n, n);
249 
250 			final String base = "pack-" + writer.computeName().name(); //$NON-NLS-1$
251 			final String packName = base + ".pack"; //$NON-NLS-1$
252 			pathPack = "pack/" + packName; //$NON-NLS-1$
253 			pathIdx = "pack/" + base + ".idx"; //$NON-NLS-1$ //$NON-NLS-2$
254 
255 			if (packNames.remove(packName) != null) {
256 				// The remote already contains this pack. We should
257 				// remove the index before overwriting to prevent bad
258 				// offsets from appearing to clients.
259 				//
260 				dest.writeInfoPacks(packNames.keySet());
261 				dest.deleteFile(pathIdx);
262 			}
263 
264 			// Write the pack file, then the index, as readers look the
265 			// other direction (index, then pack file).
266 			//
267 			String wt = "Put " + base.substring(0, 12); //$NON-NLS-1$
268 			try (OutputStream os = new BufferedOutputStream(
269 					dest.writeFile(pathPack, monitor, wt + "..pack"))) { //$NON-NLS-1$
270 				writer.writePack(monitor, monitor, os);
271 			}
272 
273 			try (OutputStream os = new BufferedOutputStream(
274 					dest.writeFile(pathIdx, monitor, wt + "..idx"))) { //$NON-NLS-1$
275 				writer.writeIndex(os);
276 			}
277 
278 			// Record the pack at the start of the pack info list. This
279 			// way clients are likely to consult the newest pack first,
280 			// and discover the most recent objects there.
281 			//
282 			final ArrayList<String> infoPacks = new ArrayList<>();
283 			infoPacks.add(packName);
284 			infoPacks.addAll(packNames.keySet());
285 			dest.writeInfoPacks(infoPacks);
286 
287 		} catch (IOException err) {
288 			safeDelete(pathIdx);
289 			safeDelete(pathPack);
290 
291 			throw new TransportException(uri, JGitText.get().cannotStoreObjects, err);
292 		}
293 	}
294 
295 	private void safeDelete(final String path) {
296 		if (path != null) {
297 			try {
298 				dest.deleteFile(path);
299 			} catch (IOException cleanupFailure) {
300 				// Ignore the deletion failure. We probably are
301 				// already failing and were just trying to pick
302 				// up after ourselves.
303 			}
304 		}
305 	}
306 
307 	private void deleteCommand(final RemoteRefUpdate u) {
308 		final Ref r = newRefs.remove(u.getRemoteName());
309 		if (r == null) {
310 			// Already gone.
311 			//
312 			u.setStatus(Status.OK);
313 			return;
314 		}
315 
316 		if (r.getStorage().isPacked())
317 			packedRefUpdates.add(u);
318 
319 		if (r.getStorage().isLoose()) {
320 			try {
321 				dest.deleteRef(u.getRemoteName());
322 				u.setStatus(Status.OK);
323 			} catch (IOException e) {
324 				u.setStatus(Status.REJECTED_OTHER_REASON);
325 				u.setMessage(e.getMessage());
326 			}
327 		}
328 
329 		try {
330 			dest.deleteRefLog(u.getRemoteName());
331 		} catch (IOException e) {
332 			u.setStatus(Status.REJECTED_OTHER_REASON);
333 			u.setMessage(e.getMessage());
334 		}
335 	}
336 
337 	private void updateCommand(final RemoteRefUpdate u) {
338 		try {
339 			dest.writeRef(u.getRemoteName(), u.getNewObjectId());
340 			newRefs.put(u.getRemoteName(), new ObjectIdRef.Unpeeled(
341 					Storage.LOOSE, u.getRemoteName(), u.getNewObjectId()));
342 			u.setStatus(Status.OK);
343 		} catch (IOException e) {
344 			u.setStatus(Status.REJECTED_OTHER_REASON);
345 			u.setMessage(e.getMessage());
346 		}
347 	}
348 
349 	private boolean isNewRepository() {
350 		return getRefsMap().isEmpty() && packNames != null
351 				&& packNames.isEmpty();
352 	}
353 
354 	private void createNewRepository(final List<RemoteRefUpdate> updates)
355 			throws TransportException {
356 		try {
357 			final String ref = "ref: " + pickHEAD(updates) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
358 			final byte[] bytes = Constants.encode(ref);
359 			dest.writeFile(ROOT_DIR + Constants.HEAD, bytes);
360 		} catch (IOException e) {
361 			throw new TransportException(uri, JGitText.get().cannotCreateHEAD, e);
362 		}
363 
364 		try {
365 			final String config = "[core]\n" //$NON-NLS-1$
366 					+ "\trepositoryformatversion = 0\n"; //$NON-NLS-1$
367 			final byte[] bytes = Constants.encode(config);
368 			dest.writeFile(ROOT_DIR + Constants.CONFIG, bytes);
369 		} catch (IOException e) {
370 			throw new TransportException(uri, JGitText.get().cannotCreateConfig, e);
371 		}
372 	}
373 
374 	private static String pickHEAD(final List<RemoteRefUpdate> updates) {
375 		// Try to use master if the user is pushing that, it is the
376 		// default branch and is likely what they want to remain as
377 		// the default on the new remote.
378 		//
379 		for (final RemoteRefUpdate u : updates) {
380 			final String n = u.getRemoteName();
381 			if (n.equals(Constants.R_HEADS + Constants.MASTER))
382 				return n;
383 		}
384 
385 		// Pick any branch, under the assumption the user pushed only
386 		// one to the remote side.
387 		//
388 		for (final RemoteRefUpdate u : updates) {
389 			final String n = u.getRemoteName();
390 			if (n.startsWith(Constants.R_HEADS))
391 				return n;
392 		}
393 		return updates.get(0).getRemoteName();
394 	}
395 }