View Javadoc
1   /*
2    * Copyright (C) 2011, GitHub Inc.
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.api;
44  
45  import java.io.File;
46  import java.io.IOException;
47  import java.text.MessageFormat;
48  
49  import org.eclipse.jgit.api.errors.GitAPIException;
50  import org.eclipse.jgit.api.errors.JGitInternalException;
51  import org.eclipse.jgit.api.errors.NoFilepatternException;
52  import org.eclipse.jgit.errors.ConfigInvalidException;
53  import org.eclipse.jgit.internal.JGitText;
54  import org.eclipse.jgit.internal.submodule.SubmoduleValidator;
55  import org.eclipse.jgit.lib.ConfigConstants;
56  import org.eclipse.jgit.lib.Constants;
57  import org.eclipse.jgit.lib.NullProgressMonitor;
58  import org.eclipse.jgit.lib.ProgressMonitor;
59  import org.eclipse.jgit.lib.Repository;
60  import org.eclipse.jgit.lib.StoredConfig;
61  import org.eclipse.jgit.storage.file.FileBasedConfig;
62  import org.eclipse.jgit.submodule.SubmoduleWalk;
63  import org.eclipse.jgit.treewalk.filter.PathFilter;
64  import org.eclipse.jgit.treewalk.filter.TreeFilter;
65  
66  /**
67   * A class used to execute a submodule add command.
68   *
69   * This will clone the configured submodule, register the submodule in the
70   * .gitmodules file and the repository config file, and also add the submodule
71   * and .gitmodules file to the index.
72   *
73   * @see <a href=
74   *      "http://www.kernel.org/pub/software/scm/git/docs/git-submodule.html"
75   *      >Git documentation about submodules</a>
76   */
77  public class SubmoduleAddCommand extends
78  		TransportCommand<SubmoduleAddCommand, Repository> {
79  
80  	private String name;
81  
82  	private String path;
83  
84  	private String uri;
85  
86  	private ProgressMonitor monitor;
87  
88  	/**
89  	 * Constructor for SubmoduleAddCommand.
90  	 *
91  	 * @param repo
92  	 *            a {@link org.eclipse.jgit.lib.Repository} object.
93  	 */
94  	public SubmoduleAddCommand(Repository repo) {
95  		super(repo);
96  	}
97  
98  	/**
99  	 * Set the submodule name
100 	 *
101 	 * @param name
102 	 * @return this command
103 	 * @since 5.1
104 	 */
105 	public SubmoduleAddCommand setName(String name) {
106 		this.name = name;
107 		return this;
108 	}
109 
110 	/**
111 	 * Set repository-relative path of submodule
112 	 *
113 	 * @param path
114 	 *            (with <code>/</code> as separator)
115 	 * @return this command
116 	 */
117 	public SubmoduleAddCommand setPath(String path) {
118 		this.path = path;
119 		return this;
120 	}
121 
122 	/**
123 	 * Set URI to clone submodule from
124 	 *
125 	 * @param uri
126 	 *            a {@link java.lang.String} object.
127 	 * @return this command
128 	 */
129 	public SubmoduleAddCommand setURI(String uri) {
130 		this.uri = uri;
131 		return this;
132 	}
133 
134 	/**
135 	 * The progress monitor associated with the clone operation. By default,
136 	 * this is set to <code>NullProgressMonitor</code>
137 	 *
138 	 * @see NullProgressMonitor
139 	 * @param monitor
140 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor} object.
141 	 * @return this command
142 	 */
143 	public SubmoduleAddCommand setProgressMonitor(ProgressMonitor monitor) {
144 		this.monitor = monitor;
145 		return this;
146 	}
147 
148 	/**
149 	 * Is the configured already a submodule in the index?
150 	 *
151 	 * @return true if submodule exists in index, false otherwise
152 	 * @throws java.io.IOException
153 	 */
154 	protected boolean submoduleExists() throws IOException {
155 		TreeFilter filter = PathFilter.create(path);
156 		try (SubmoduleWalk w = SubmoduleWalk.forIndex(repo)) {
157 			return w.setFilter(filter).next();
158 		}
159 	}
160 
161 	/**
162 	 * {@inheritDoc}
163 	 * <p>
164 	 * Executes the {@code SubmoduleAddCommand}
165 	 *
166 	 * The {@code Repository} instance returned by this command needs to be
167 	 * closed by the caller to free resources held by the {@code Repository}
168 	 * instance. It is recommended to call this method as soon as you don't need
169 	 * a reference to this {@code Repository} instance anymore.
170 	 */
171 	@Override
172 	public Repository call() throws GitAPIException {
173 		checkCallable();
174 		if (path == null || path.length() == 0)
175 			throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
176 		if (uri == null || uri.length() == 0)
177 			throw new IllegalArgumentException(JGitText.get().uriNotConfigured);
178 		if (name == null || name.length() == 0) {
179 			// Use the path as the default.
180 			name = path;
181 		}
182 		if (name.contains("/../") || name.contains("\\..\\") //$NON-NLS-1$ //$NON-NLS-2$
183 				|| name.startsWith("../") || name.startsWith("..\\") //$NON-NLS-1$ //$NON-NLS-2$
184 				|| name.endsWith("/..") || name.endsWith("\\..")) { //$NON-NLS-1$ //$NON-NLS-2$
185 			// Submodule names are used to store the submodule repositories
186 			// under $GIT_DIR/modules. Having ".." in submodule names makes a
187 			// vulnerability (CVE-2018-11235
188 			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=535027#c0)
189 			// Reject the names with them. The callers need to make sure the
190 			// names free from these. We don't automatically replace these
191 			// characters or canonicalize by regarding the name as a file path.
192 			// Since Path class is platform dependent, we manually check '/' and
193 			// '\\' patterns here.
194 			throw new IllegalArgumentException(MessageFormat
195 					.format(JGitText.get().invalidNameContainsDotDot, name));
196 		}
197 
198 		try {
199 			SubmoduleValidator.assertValidSubmoduleName(name);
200 			SubmoduleValidator.assertValidSubmodulePath(path);
201 			SubmoduleValidator.assertValidSubmoduleUri(uri);
202 		} catch (SubmoduleValidator.SubmoduleValidationException e) {
203 			throw new IllegalArgumentException(e.getMessage());
204 		}
205 
206 		try {
207 			if (submoduleExists())
208 				throw new JGitInternalException(MessageFormat.format(
209 						JGitText.get().submoduleExists, path));
210 		} catch (IOException e) {
211 			throw new JGitInternalException(e.getMessage(), e);
212 		}
213 
214 		final String resolvedUri;
215 		try {
216 			resolvedUri = SubmoduleWalk.getSubmoduleRemoteUrl(repo, uri);
217 		} catch (IOException e) {
218 			throw new JGitInternalException(e.getMessage(), e);
219 		}
220 		// Clone submodule repository
221 		File moduleDirectory = SubmoduleWalk.getSubmoduleDirectory(repo, path);
222 		CloneCommand clone = Git.cloneRepository();
223 		configure(clone);
224 		clone.setDirectory(moduleDirectory);
225 		clone.setGitDir(new File(new File(repo.getDirectory(),
226 				Constants.MODULES), path));
227 		clone.setURI(resolvedUri);
228 		if (monitor != null)
229 			clone.setProgressMonitor(monitor);
230 		Repository subRepo = null;
231 		try (Git git = clone.call()) {
232 			subRepo = git.getRepository();
233 			subRepo.incrementOpen();
234 		}
235 
236 		// Save submodule URL to parent repository's config
237 		StoredConfig config = repo.getConfig();
238 		config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, name,
239 				ConfigConstants.CONFIG_KEY_URL, resolvedUri);
240 		try {
241 			config.save();
242 		} catch (IOException e) {
243 			throw new JGitInternalException(e.getMessage(), e);
244 		}
245 
246 		// Save path and URL to parent repository's .gitmodules file
247 		FileBasedConfig modulesConfig = new FileBasedConfig(new File(
248 				repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
249 		try {
250 			modulesConfig.load();
251 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
252 					name, ConfigConstants.CONFIG_KEY_PATH, path);
253 			modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
254 					name, ConfigConstants.CONFIG_KEY_URL, uri);
255 			modulesConfig.save();
256 		} catch (IOException e) {
257 			throw new JGitInternalException(e.getMessage(), e);
258 		} catch (ConfigInvalidException e) {
259 			throw new JGitInternalException(e.getMessage(), e);
260 		}
261 
262 		AddCommand add = new AddCommand(repo);
263 		// Add .gitmodules file to parent repository's index
264 		add.addFilepattern(Constants.DOT_GIT_MODULES);
265 		// Add submodule directory to parent repository's index
266 		add.addFilepattern(path);
267 		try {
268 			add.call();
269 		} catch (NoFilepatternException e) {
270 			throw new JGitInternalException(e.getMessage(), e);
271 		}
272 
273 		return subRepo;
274 	}
275 }