1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.transport.wagon;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.StandardCopyOption;
30 import java.util.Locale;
31 import java.util.Map;
32 import java.util.Properties;
33 import java.util.Queue;
34 import java.util.concurrent.ConcurrentLinkedQueue;
35 import java.util.concurrent.atomic.AtomicBoolean;
36
37 import org.apache.maven.wagon.ConnectionException;
38 import org.apache.maven.wagon.ResourceDoesNotExistException;
39 import org.apache.maven.wagon.StreamingWagon;
40 import org.apache.maven.wagon.Wagon;
41 import org.apache.maven.wagon.WagonException;
42 import org.apache.maven.wagon.authentication.AuthenticationInfo;
43 import org.apache.maven.wagon.proxy.ProxyInfo;
44 import org.apache.maven.wagon.proxy.ProxyInfoProvider;
45 import org.apache.maven.wagon.repository.Repository;
46 import org.apache.maven.wagon.repository.RepositoryPermissions;
47 import org.eclipse.aether.ConfigurationProperties;
48 import org.eclipse.aether.RepositorySystemSession;
49 import org.eclipse.aether.repository.AuthenticationContext;
50 import org.eclipse.aether.repository.Proxy;
51 import org.eclipse.aether.repository.RemoteRepository;
52 import org.eclipse.aether.spi.connector.transport.GetTask;
53 import org.eclipse.aether.spi.connector.transport.PeekTask;
54 import org.eclipse.aether.spi.connector.transport.PutTask;
55 import org.eclipse.aether.spi.connector.transport.TransportTask;
56 import org.eclipse.aether.spi.connector.transport.Transporter;
57 import org.eclipse.aether.spi.io.PathProcessor;
58 import org.eclipse.aether.transfer.NoTransporterException;
59 import org.eclipse.aether.util.ConfigUtils;
60 import org.eclipse.aether.util.connector.transport.http.HttpTransporterUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 import static java.util.Objects.requireNonNull;
65 import static org.eclipse.aether.transport.wagon.WagonTransporterConfigurationKeys.CONFIG_PROP_CONFIG;
66 import static org.eclipse.aether.transport.wagon.WagonTransporterConfigurationKeys.CONFIG_PROP_DIR_MODE;
67 import static org.eclipse.aether.transport.wagon.WagonTransporterConfigurationKeys.CONFIG_PROP_FILE_MODE;
68 import static org.eclipse.aether.transport.wagon.WagonTransporterConfigurationKeys.CONFIG_PROP_GROUP;
69
70
71
72
73 final class WagonTransporter implements Transporter {
74 private static final Logger LOGGER = LoggerFactory.getLogger(WagonTransporter.class);
75
76 private final RemoteRepository repository;
77
78 private final RepositorySystemSession session;
79
80 private final PathProcessor pathProcessor;
81
82 private final AuthenticationContext repoAuthContext;
83
84 private final AuthenticationContext proxyAuthContext;
85
86 private final WagonProvider wagonProvider;
87
88 private final WagonConfigurator wagonConfigurator;
89
90 private final String wagonHint;
91
92 private final Repository wagonRepo;
93
94 private final AuthenticationInfo wagonAuth;
95
96 private final ProxyInfoProvider wagonProxy;
97
98 private final Properties headers;
99
100 private final Queue<Wagon> wagons = new ConcurrentLinkedQueue<>();
101
102 private final AtomicBoolean closed = new AtomicBoolean();
103
104 WagonTransporter(
105 WagonProvider wagonProvider,
106 WagonConfigurator wagonConfigurator,
107 RemoteRepository repository,
108 RepositorySystemSession session,
109 PathProcessor pathProcessor)
110 throws NoTransporterException {
111 this.wagonProvider = wagonProvider;
112 this.wagonConfigurator = wagonConfigurator;
113 this.repository = repository;
114 this.session = session;
115 this.pathProcessor = pathProcessor;
116
117 wagonRepo = new Repository(repository.getId(), repository.getUrl());
118 wagonRepo.setPermissions(getPermissions(repository.getId(), session));
119
120 wagonHint = wagonRepo.getProtocol().toLowerCase(Locale.ENGLISH);
121 if (wagonHint.isEmpty()) {
122 throw new NoTransporterException(repository);
123 }
124
125 try {
126 wagons.add(lookupWagon());
127 } catch (Exception e) {
128 LOGGER.debug("No transport", e);
129 throw new NoTransporterException(repository, e);
130 }
131
132 repoAuthContext = AuthenticationContext.forRepository(session, repository);
133 proxyAuthContext = AuthenticationContext.forProxy(session, repository);
134
135 wagonAuth = getAuthenticationInfo(repoAuthContext);
136 wagonProxy = getProxy(repository, proxyAuthContext);
137
138 headers = new Properties();
139 headers.put("User-Agent", HttpTransporterUtils.getUserAgent(session, repository));
140 Map<String, String> headers = HttpTransporterUtils.getHttpHeaders(session, repository);
141 if (headers != null) {
142 this.headers.putAll(headers);
143 }
144 }
145
146 private static RepositoryPermissions getPermissions(String repoId, RepositorySystemSession session) {
147 RepositoryPermissions result = null;
148
149 RepositoryPermissions perms = new RepositoryPermissions();
150
151 String suffix = '.' + repoId;
152
153 String fileMode = ConfigUtils.getString(session, null, CONFIG_PROP_FILE_MODE + suffix);
154 if (fileMode != null) {
155 perms.setFileMode(fileMode);
156 result = perms;
157 }
158
159 String dirMode = ConfigUtils.getString(session, null, CONFIG_PROP_DIR_MODE + suffix);
160 if (dirMode != null) {
161 perms.setDirectoryMode(dirMode);
162 result = perms;
163 }
164
165 String group = ConfigUtils.getString(session, null, CONFIG_PROP_GROUP + suffix);
166 if (group != null) {
167 perms.setGroup(group);
168 result = perms;
169 }
170
171 return result;
172 }
173
174 private AuthenticationInfo getAuthenticationInfo(final AuthenticationContext authContext) {
175 AuthenticationInfo auth = null;
176
177 if (authContext != null) {
178 auth = new AuthenticationInfo() {
179 @Override
180 public String getUserName() {
181 return authContext.get(AuthenticationContext.USERNAME);
182 }
183
184 @Override
185 public String getPassword() {
186 return authContext.get(AuthenticationContext.PASSWORD);
187 }
188
189 @Override
190 public String getPrivateKey() {
191 return authContext.get(AuthenticationContext.PRIVATE_KEY_PATH);
192 }
193
194 @Override
195 public String getPassphrase() {
196 return authContext.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE);
197 }
198 };
199 }
200
201 return auth;
202 }
203
204 private ProxyInfoProvider getProxy(RemoteRepository repository, final AuthenticationContext authContext) {
205 ProxyInfoProvider proxy = null;
206
207 Proxy p = repository.getProxy();
208 if (p != null) {
209 final ProxyInfo prox;
210 if (authContext != null) {
211 prox = new ProxyInfo() {
212 @Override
213 public String getUserName() {
214 return authContext.get(AuthenticationContext.USERNAME);
215 }
216
217 @Override
218 public String getPassword() {
219 return authContext.get(AuthenticationContext.PASSWORD);
220 }
221
222 @Override
223 public String getNtlmDomain() {
224 return authContext.get(AuthenticationContext.NTLM_DOMAIN);
225 }
226
227 @Override
228 public String getNtlmHost() {
229 return authContext.get(AuthenticationContext.NTLM_WORKSTATION);
230 }
231 };
232 } else {
233 prox = new ProxyInfo();
234 }
235 prox.setType(p.getType());
236 prox.setHost(p.getHost());
237 prox.setPort(p.getPort());
238
239 proxy = protocol -> prox;
240 }
241
242 return proxy;
243 }
244
245 private Wagon lookupWagon() throws Exception {
246 return wagonProvider.lookup(wagonHint);
247 }
248
249 private void releaseWagon(Wagon wagon) {
250 wagonProvider.release(wagon);
251 }
252
253 private void connectWagon(Wagon wagon) throws WagonException {
254 if (!headers.isEmpty()) {
255 try {
256 Method setHttpHeaders = wagon.getClass().getMethod("setHttpHeaders", Properties.class);
257 setHttpHeaders.invoke(wagon, headers);
258 } catch (NoSuchMethodException e) {
259
260 } catch (InvocationTargetException | IllegalAccessException | RuntimeException e) {
261 LOGGER.debug(
262 "Could not set user agent for Wagon {}",
263 wagon.getClass().getName(),
264 e);
265 }
266 }
267
268 int connectTimeout = HttpTransporterUtils.getHttpConnectTimeout(session, repository);
269 int requestTimeout = HttpTransporterUtils.getHttpRequestTimeout(session, repository);
270
271 wagon.setTimeout(Math.max(Math.max(connectTimeout, requestTimeout), 0));
272 wagon.setInteractive(ConfigUtils.getBoolean(
273 session, ConfigurationProperties.DEFAULT_INTERACTIVE, ConfigurationProperties.INTERACTIVE));
274
275 Object configuration = ConfigUtils.getObject(session, null, CONFIG_PROP_CONFIG + "." + repository.getId());
276 if (configuration != null && wagonConfigurator != null) {
277 try {
278 wagonConfigurator.configure(wagon, configuration);
279 } catch (Exception e) {
280 LOGGER.warn(
281 "Could not apply configuration for {} to Wagon {}",
282 repository.getId(),
283 wagon.getClass().getName(),
284 e);
285 }
286 }
287
288 wagon.connect(wagonRepo, wagonAuth, wagonProxy);
289 }
290
291 private void disconnectWagon(Wagon wagon) {
292 try {
293 if (wagon != null) {
294 wagon.disconnect();
295 }
296 } catch (ConnectionException e) {
297 LOGGER.debug("Could not disconnect Wagon {}", wagon, e);
298 }
299 }
300
301 private Wagon pollWagon() throws Exception {
302 Wagon wagon = wagons.poll();
303
304 if (wagon == null) {
305 try {
306 wagon = lookupWagon();
307 connectWagon(wagon);
308 } catch (Exception e) {
309 releaseWagon(wagon);
310 throw e;
311 }
312 } else if (wagon.getRepository() == null) {
313 try {
314 connectWagon(wagon);
315 } catch (Exception e) {
316 releaseWagon(wagon);
317 throw e;
318 }
319 }
320
321 return wagon;
322 }
323
324 @Override
325 public int classify(Throwable error) {
326 if (error instanceof ResourceDoesNotExistException) {
327 return ERROR_NOT_FOUND;
328 }
329 return ERROR_OTHER;
330 }
331
332 @Override
333 public void peek(PeekTask task) throws Exception {
334 execute(task, new PeekTaskRunner(task));
335 }
336
337 @Override
338 public void get(GetTask task) throws Exception {
339 execute(task, new GetTaskRunner(pathProcessor, task));
340 }
341
342 @Override
343 public void put(PutTask task) throws Exception {
344 execute(task, new PutTaskRunner(pathProcessor, task));
345 }
346
347 private void execute(TransportTask task, TaskRunner runner) throws Exception {
348 requireNonNull(task, "task cannot be null");
349
350 if (closed.get()) {
351 throw new IllegalStateException("transporter closed, cannot execute task " + task);
352 }
353 try {
354 WagonTransferListener listener = new WagonTransferListener(task.getListener());
355 Wagon wagon = pollWagon();
356 try {
357 wagon.addTransferListener(listener);
358 runner.run(wagon);
359 } finally {
360 wagon.removeTransferListener(listener);
361 if (closed.get()) {
362 disconnectWagon(wagon);
363 releaseWagon(wagon);
364 } else {
365 wagons.add(wagon);
366 }
367 }
368 } catch (RuntimeException e) {
369 throw WagonCancelledException.unwrap(e);
370 }
371 }
372
373 @Override
374 public void close() {
375 if (closed.compareAndSet(false, true)) {
376 AuthenticationContext.close(repoAuthContext);
377 AuthenticationContext.close(proxyAuthContext);
378
379 for (Wagon wagon = wagons.poll(); wagon != null; wagon = wagons.poll()) {
380 disconnectWagon(wagon);
381 releaseWagon(wagon);
382 }
383 }
384 }
385
386 private interface TaskRunner {
387
388 void run(Wagon wagon) throws IOException, WagonException;
389 }
390
391 private static class PeekTaskRunner implements TaskRunner {
392
393 private final PeekTask task;
394
395 PeekTaskRunner(PeekTask task) {
396 this.task = task;
397 }
398
399 @Override
400 public void run(Wagon wagon) throws WagonException {
401 String src = task.getLocation().toString();
402 if (!wagon.resourceExists(src)) {
403 throw new ResourceDoesNotExistException(
404 "Could not find " + src + " in " + wagon.getRepository().getUrl());
405 }
406 }
407 }
408
409 private static class GetTaskRunner implements TaskRunner {
410
411 private final PathProcessor pathProcessor;
412
413 private final GetTask task;
414
415 GetTaskRunner(PathProcessor pathProcessor, GetTask task) {
416 this.pathProcessor = pathProcessor;
417 this.task = task;
418 }
419
420 @Override
421 public void run(Wagon wagon) throws IOException, WagonException {
422 final String src = task.getLocation().toString();
423 final Path dataPath = task.getDataPath();
424 final File file = dataPath != null ? dataPath.toFile() : null;
425 if (file == null && wagon instanceof StreamingWagon) {
426 try (OutputStream dst = task.newOutputStream()) {
427 ((StreamingWagon) wagon).getToStream(src, dst);
428 }
429 } else {
430
431 try (PathProcessor.TempFile tempFile =
432 file == null ? pathProcessor.newTempFile() : pathProcessor.newTempFile(file.toPath())) {
433 File dst = tempFile.getPath().toFile();
434 wagon.get(src, dst);
435
436
437
438
439
440 if (!dst.exists() && !dst.createNewFile()) {
441 throw new IOException(String.format("Failure creating file '%s'.", dst.getAbsolutePath()));
442 }
443
444 if (file != null) {
445 ((PathProcessor.CollocatedTempFile) tempFile).move();
446 } else {
447 try (OutputStream outputStream = task.newOutputStream()) {
448 Files.copy(dst.toPath(), outputStream);
449 }
450 }
451 }
452 }
453 }
454 }
455
456 private static class PutTaskRunner implements TaskRunner {
457
458 private final PathProcessor pathProcessor;
459
460 private final PutTask task;
461
462 PutTaskRunner(PathProcessor pathProcessor, PutTask task) {
463 this.pathProcessor = pathProcessor;
464 this.task = task;
465 }
466
467 @Override
468 public void run(Wagon wagon) throws WagonException, IOException {
469 final String dst = task.getLocation().toString();
470 final Path dataPath = task.getDataPath();
471 final File file = dataPath != null ? dataPath.toFile() : null;
472 if (file == null && wagon instanceof StreamingWagon) {
473 try (InputStream src = task.newInputStream()) {
474
475 ((StreamingWagon) wagon).putFromStream(src, dst, task.getDataLength(), -1);
476 }
477 } else if (file == null) {
478 try (PathProcessor.TempFile tempFile = pathProcessor.newTempFile()) {
479 try (InputStream inputStream = task.newInputStream()) {
480 Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING);
481 }
482 wagon.put(tempFile.getPath().toFile(), dst);
483 }
484 } else {
485 wagon.put(file, dst);
486 }
487 }
488 }
489 }