1 package org.apache.archiva.webdav;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.RemoteRepository;
24 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
25 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
26 import org.apache.archiva.audit.Auditable;
27 import org.apache.archiva.common.filelock.FileLockManager;
28 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
30 import org.apache.archiva.common.utils.PathUtil;
31 import org.apache.archiva.common.utils.VersionUtil;
32 import org.apache.archiva.configuration.ArchivaConfiguration;
33 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
34 import org.apache.archiva.indexer.merger.IndexMerger;
35 import org.apache.archiva.indexer.merger.IndexMergerException;
36 import org.apache.archiva.indexer.merger.IndexMergerRequest;
37 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
38 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
39 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
40 import org.apache.archiva.indexer.search.RepositorySearch;
41 import org.apache.archiva.indexer.search.RepositorySearchException;
42 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
43 import org.apache.archiva.metadata.model.facets.AuditEvent;
44 import org.apache.archiva.metadata.repository.storage.RelocationException;
45 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
46 import org.apache.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.archiva.model.ArtifactReference;
48 import org.apache.archiva.policies.ProxyDownloadException;
49 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
50 import org.apache.archiva.redback.authentication.AuthenticationException;
51 import org.apache.archiva.redback.authentication.AuthenticationResult;
52 import org.apache.archiva.redback.authorization.AuthorizationException;
53 import org.apache.archiva.redback.authorization.UnauthorizedException;
54 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
55 import org.apache.archiva.redback.policy.AccountLockedException;
56 import org.apache.archiva.redback.policy.MustChangePasswordException;
57 import org.apache.archiva.redback.system.SecuritySession;
58 import org.apache.archiva.redback.users.User;
59 import org.apache.archiva.redback.users.UserManager;
60 import org.apache.archiva.repository.LayoutException;
61 import org.apache.archiva.repository.ManagedRepository;
62 import org.apache.archiva.repository.ManagedRepositoryContent;
63 import org.apache.archiva.repository.ReleaseScheme;
64 import org.apache.archiva.repository.RepositoryContentFactory;
65 import org.apache.archiva.repository.RepositoryRegistry;
66 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
67 import org.apache.archiva.repository.events.AuditListener;
68 import org.apache.archiva.repository.features.IndexCreationFeature;
69 import org.apache.archiva.repository.metadata.MetadataTools;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
71 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
72 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
73 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
74 import org.apache.archiva.security.ServletAuthenticator;
75 import org.apache.archiva.webdav.util.MimeTypes;
76 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
77 import org.apache.archiva.webdav.util.WebdavMethodUtil;
78 import org.apache.archiva.xml.XMLException;
79 import org.apache.commons.io.FilenameUtils;
80 import org.apache.commons.lang.StringUtils;
81 import org.apache.commons.lang.SystemUtils;
82 import org.apache.jackrabbit.webdav.DavException;
83 import org.apache.jackrabbit.webdav.DavResource;
84 import org.apache.jackrabbit.webdav.DavResourceFactory;
85 import org.apache.jackrabbit.webdav.DavResourceLocator;
86 import org.apache.jackrabbit.webdav.DavServletRequest;
87 import org.apache.jackrabbit.webdav.DavServletResponse;
88 import org.apache.jackrabbit.webdav.DavSession;
89 import org.apache.jackrabbit.webdav.lock.LockManager;
90 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
91 import org.apache.maven.index.context.IndexingContext;
92 import org.codehaus.plexus.digest.ChecksumFile;
93 import org.codehaus.plexus.digest.Digester;
94 import org.codehaus.plexus.digest.DigesterException;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97 import org.slf4j.MarkerFactory;
98 import org.springframework.context.ApplicationContext;
99 import org.springframework.stereotype.Service;
101 import javax.annotation.PostConstruct;
102 import javax.inject.Inject;
103 import javax.inject.Named;
104 import javax.servlet.http.HttpServletResponse;
105 import javax.servlet.http.HttpSession;
106 import java.io.IOException;
107 import java.nio.file.Files;
108 import java.nio.file.Path;
109 import java.nio.file.Paths;
110 import java.util.ArrayList;
111 import java.util.Date;
112 import java.util.HashMap;
113 import java.util.HashSet;
114 import java.util.List;
115 import java.util.Map;
116 import java.util.Set;
121 @Service( "davResourceFactory#archiva" )
122 public class ArchivaDavResourceFactory
123 implements DavResourceFactory, Auditable
125 private static final String PROXIED_SUFFIX = " (proxied)";
127 private static final String HTTP_PUT_METHOD = "PUT";
129 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
132 private List<AuditListener> auditListeners = new ArrayList<>();
135 private RepositoryContentFactory repositoryFactory;
137 private RepositoryRequest repositoryRequest;
140 @Named( value = "repositoryProxyConnectors#default" )
141 private RepositoryProxyConnectors connectors;
144 private MetadataTools metadataTools;
147 private MimeTypes mimeTypes;
149 private ArchivaConfiguration archivaConfiguration;
152 private ServletAuthenticator servletAuth;
155 @Named( value = "httpAuthenticator#basic" )
156 private HttpAuthenticator httpAuth;
159 private RemoteRepositoryAdmin remoteRepositoryAdmin;
162 private ManagedRepositoryAdmin managedRepositoryAdmin;
165 private RepositoryRegistry repositoryRegistry;
168 private IndexMerger indexMerger;
171 private RepositorySearch repositorySearch;
174 * Lock Manager - use simple implementation from JackRabbit
176 private final LockManager lockManager = new SimpleLockManager();
178 private ChecksumFile checksum;
180 private Digester digestSha1;
182 private Digester digestMd5;
185 @Named( value = "archivaTaskScheduler#repository" )
186 private RepositoryArchivaTaskScheduler scheduler;
189 @Named( value = "fileLockManager#default" )
190 private FileLockManager fileLockManager;
192 private ApplicationContext applicationContext;
195 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
196 ArchivaConfiguration archivaConfiguration )
197 throws PlexusSisuBridgeException
199 this.archivaConfiguration = archivaConfiguration;
200 this.applicationContext = applicationContext;
201 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
203 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
204 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
206 // TODO remove this hard dependency on maven !!
207 repositoryRequest = new RepositoryRequest( );
211 public void initialize()
217 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
218 final DavServletResponse response )
221 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
223 RepositoryGroupConfiguration repoGroupConfig =
224 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
226 String activePrincipal = getActivePrincipal( request );
228 List<String> resourcesInAbsolutePath = new ArrayList<>();
230 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
231 DavResource resource;
232 if ( repoGroupConfig != null )
236 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
237 "Write method not allowed for repository groups." );
240 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
242 // handle browse requests for virtual repos
243 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
247 DavResource davResource =
248 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
251 setHeaders( response, locator, davResource, true );
256 catch ( RepositoryAdminException e )
258 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
263 // make a copy to avoid potential concurrent modifications (eg. by configuration)
264 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
266 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
267 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
268 resourcesInAbsolutePath, repoGroupConfig );
276 RemoteRepository remoteRepository =
277 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
279 if ( remoteRepository != null )
281 String logicalResource = getLogicalResource( archivaLocator, null, false );
282 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
283 Path resourceFile = StringUtils.equals( logicalResource, "/" )
284 ? Paths.get( indexingContext.getIndexDirectoryFile().getParent() )
285 : Paths.get( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
286 resource = new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), //
287 locator.getResourcePath(), //
289 request.getRemoteAddr(), //
291 request.getDavSession(), //
298 setHeaders( response, locator, resource, false );
302 catch ( RepositoryAdminException e )
304 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
305 archivaLocator.getRepositoryId(), e.getMessage() );
309 ManagedRepository repo = repositoryRegistry.getManagedRepository( archivaLocator.getRepositoryId() );
311 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
312 "Invalid repository: " + archivaLocator.getRepositoryId() );
314 ManagedRepositoryContent managedRepositoryContent = repo.getContent( );
315 if (managedRepositoryContent==null) {
316 log.error("Inconsistency detected. Repository content not found for '{}'", archivaLocator.getRepositoryId());
317 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
318 "Invalid repository: " + archivaLocator.getRepositoryId() );
321 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
323 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
326 String logicalResource = getLogicalResource( archivaLocator, null, false );
327 resourcesInAbsolutePath.add(
328 Paths.get( managedRepositoryContent.getRepoRoot(), logicalResource ).toAbsolutePath().toString() );
332 String requestedResource = request.getRequestURI();
334 // MRM-872 : merge all available metadata
335 // merge metadata only when requested via the repo group
336 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
337 requestedResource ) ) && repoGroupConfig != null )
339 // this should only be at the project level not version level!
340 if ( isProjectReference( requestedResource ) )
343 ArchivaDavResource res = (ArchivaDavResource) resource;
345 StringUtils.substringBeforeLast( res.getLocalResource().toAbsolutePath().toString().replace( '\\', '/' ),
347 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
349 // for MRM-872 handle checksums of the merged metadata files
350 if ( repositoryRequest.isSupportFile( requestedResource ) )
352 Path metadataChecksum =
353 Paths.get( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
355 if ( Files.exists(metadataChecksum) )
357 LogicalResource logicalResource =
358 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
361 new ArchivaDavResource( metadataChecksum.toAbsolutePath().toString(), logicalResource.getPath(), null,
362 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
363 archivaLocator, this, mimeTypes, auditListeners, scheduler,
369 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
371 // merge the metadata of all repos under group
372 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
373 for ( String resourceAbsPath : resourcesInAbsolutePath )
377 Path metadataFile = Paths.get( resourceAbsPath );
378 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
379 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
381 catch ( XMLException e )
383 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
384 "Error occurred while reading metadata file." );
386 catch ( RepositoryMetadataException r )
388 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
389 "Error occurred while merging metadata file." );
395 Path resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
397 LogicalResource logicalResource =
398 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
401 new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), logicalResource.getPath(), null,
402 request.getRemoteAddr(), activePrincipal,
403 request.getDavSession(), archivaLocator, this, mimeTypes,
404 auditListeners, scheduler, fileLockManager );
406 catch ( RepositoryMetadataException r )
408 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
409 "Error occurred while writing metadata file." );
411 catch ( IOException ie )
413 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
414 "Error occurred while generating checksum files." );
416 catch ( DigesterException de )
418 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
419 "Error occurred while generating checksum files."
427 setHeaders( response, locator, resource, false );
429 // compatibility with MRM-440 to ensure browsing the repository works ok
430 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
432 throw new BrowserRedirectException( resource.getHref() );
434 resource.addLockManager( lockManager );
438 private DavResource processRepositoryGroup( final DavServletRequest request,
439 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
440 String activePrincipal, List<String> resourcesInAbsolutePath,
441 RepositoryGroupConfiguration repoGroupConfig )
444 DavResource resource = null;
445 List<DavException> storedExceptions = new ArrayList<>();
447 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
449 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
451 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
453 // we are in the case of index file request
454 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
455 Path temporaryIndexDirectory =
456 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
458 Path resourceFile = temporaryIndexDirectory.resolve( requestedFileName );
459 resource = new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), requestedFileName, null,
460 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
461 archivaLocator, this, mimeTypes, auditListeners, scheduler,
467 for ( String repositoryId : repositories )
469 ManagedRepositoryContent managedRepositoryContent;
470 ManagedRepository managedRepository = repositoryRegistry.getManagedRepository( repositoryId );
471 if (managedRepository==null) {
472 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find repository with id "+repositoryId );
474 managedRepositoryContent = managedRepository.getContent();
475 if (managedRepositoryContent==null) {
476 log.error("Inconsistency detected. Repository content not found for '{}'",repositoryId);
477 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find repository content with id "+repositoryId );
481 DavResource updatedResource =
482 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
484 if ( resource == null )
486 resource = updatedResource;
489 String logicalResource = getLogicalResource( archivaLocator, null, false );
490 if ( logicalResource.endsWith( "/" ) )
492 logicalResource = logicalResource.substring( 1 );
494 resourcesInAbsolutePath.add(
495 Paths.get( managedRepositoryContent.getRepoRoot(), logicalResource ).toAbsolutePath().toString() );
497 catch ( DavException e )
499 storedExceptions.add( e );
503 if ( resource == null )
505 if ( !storedExceptions.isEmpty() )
508 for ( DavException e : storedExceptions )
510 if ( 401 == e.getErrorCode() )
516 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
520 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
526 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, org.apache.archiva.repository.ManagedRepository managedRepository,
527 boolean useOrigResourcePath )
529 // FIXME remove this hack
530 // but currently managedRepository can be null in case of group
531 String layout = managedRepository == null ? "default" : managedRepository.getLayout();
532 RepositoryStorage repositoryStorage =
533 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
534 String path = repositoryStorage.getFilePath(
535 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
537 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
538 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
543 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, //
544 ManagedRepositoryContent managedRepositoryContent, //
548 String layout = managedRepositoryContent.getRepository() == null
550 : managedRepositoryContent.getRepository().getLayout();
551 RepositoryStorage repositoryStorage =
552 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
555 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), //
556 managedRepositoryContent );
558 catch ( RelocationException e )
560 String path = e.getPath();
561 log.debug( "Relocation to {}", path );
563 throw new BrowserRedirectException( addHrefPrefix( contextPath, path ), e.getRelocationType() );
565 catch ( XMLException e )
567 log.error( e.getMessage(), e );
568 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
572 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
573 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
574 org.apache.archiva.repository.ManagedRepository managedRepository )
577 DavResource resource = null;
578 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
580 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
581 // Maven Centric part ask evaluation if -SNAPSHOT
582 // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
584 String path = readMethod
585 ? evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
586 : getLogicalResource( archivaLocator, managedRepository, false );
587 if ( path.startsWith( "/" ) )
589 path = path.substring( 1 );
591 LogicalResource logicalResource = new LogicalResource( path );
592 Path resourceFile = Paths.get( managedRepositoryContent.getRepoRoot(), path );
594 new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), path, managedRepositoryContent.getRepository(),
595 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
596 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
598 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
600 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !Files.isDirectory( resourceFile ) )
602 // force a resource not found
603 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
607 if ( !resource.isCollection() )
609 boolean previouslyExisted = Files.exists(resourceFile);
611 boolean fromProxy = fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
613 // At this point the incoming request can either be in default or
614 // legacy layout format.
617 // Perform an adjustment of the resource to the managed
618 // repository expected path.
619 String localResourcePath =
620 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
621 resourceFile = Paths.get( managedRepositoryContent.getRepoRoot(), localResourcePath );
623 new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), logicalResource.getPath(),
624 managedRepositoryContent.getRepository(),
625 request.getRemoteAddr(), activePrincipal,
626 request.getDavSession(), archivaLocator, this, mimeTypes,
627 auditListeners, scheduler, fileLockManager );
629 catch ( LayoutException e )
631 if ( !Files.exists(resourceFile) )
633 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
639 String action = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
642 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
643 resourceFile.getFileName(), managedRepositoryContent.getId(), activePrincipal );
645 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
646 logicalResource.getPath(), action, activePrincipal );
649 if ( !Files.exists(resourceFile) )
651 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
657 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
659 String resourcePath = logicalResource.getPath();
661 // check if target repo is enabled for releases
662 // we suppose that release-artifacts can be deployed only to repos enabled for releases
663 if ( managedRepositoryContent.getRepository().getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE ) && !repositoryRequest.isMetadata(
664 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
666 ArtifactReference artifact = null;
669 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
671 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
673 // check if artifact already exists and if artifact re-deployment to the repository is allowed
674 if ( managedRepositoryContent.hasContent( artifact )
675 && managedRepositoryContent.getRepository().blocksRedeployments())
677 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
678 managedRepositoryContent.getId() );
679 throw new DavException( HttpServletResponse.SC_CONFLICT,
680 "Overwriting released artifacts is not allowed." );
684 catch ( LayoutException e )
686 log.warn( "Artifact path '{}' is invalid.", resourcePath );
691 * Create parent directories that don't exist when writing a file This actually makes this
692 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
693 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
694 * create the collections themselves.
697 Path rootDirectory = Paths.get( managedRepositoryContent.getRepoRoot() );
698 Path destDir = rootDirectory.resolve( logicalResource.getPath() ).getParent();
700 if ( !Files.exists(destDir) )
704 Files.createDirectories( destDir );
706 catch ( IOException e )
708 log.error("Could not create directory {}: {}", destDir, e.getMessage(), e);
709 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create directory "+destDir );
711 String relPath = PathUtil.getRelative( rootDirectory.toAbsolutePath().toString(), destDir );
713 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getFileName(),
716 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
717 AuditEvent.CREATE_DIR, activePrincipal );
725 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
728 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
730 ManagedRepositoryContent managedRepositoryContent;
731 ManagedRepository repo = repositoryRegistry.getManagedRepository( archivaLocator.getRepositoryId( ) );
733 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
734 "Invalid repository: " + archivaLocator.getRepositoryId() );
736 managedRepositoryContent = repo.getContent();
737 if (managedRepositoryContent==null) {
738 log.error("Inconsistency detected. Repository content not found for '{}'", archivaLocator.getRepositoryId());
739 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
740 "Invalid repository: " + archivaLocator.getRepositoryId() );
743 DavResource resource = null;
744 String logicalResource = getLogicalResource( archivaLocator, repo, false );
745 if ( logicalResource.startsWith( "/" ) )
747 logicalResource = logicalResource.substring( 1 );
749 Path resourceFile = Paths.get( managedRepositoryContent.getRepoRoot(), logicalResource );
750 resource = new ArchivaDavResource( resourceFile.toAbsolutePath().toString(), logicalResource,
751 repo, davSession, archivaLocator,
752 this, mimeTypes, auditListeners, scheduler, fileLockManager );
754 resource.addLockManager( lockManager );
758 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
759 LogicalResource resource )
762 String path = resource.getPath();
763 if ( repositoryRequest.isSupportFile( path ) )
765 Path proxiedFile = connectors.fetchFromProxies( managedRepository, path );
767 return ( proxiedFile != null );
770 // Is it a Metadata resource?
771 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
773 return connectors.fetchMetadataFromProxies( managedRepository, path ).isModified();
776 // Is it an Archetype Catalog?
777 if ( repositoryRequest.isArchetypeCatalog( path ) )
779 // FIXME we must implement a merge of remote archetype catalog from remote servers.
780 Path proxiedFile = connectors.fetchFromProxies( managedRepository, path );
782 return ( proxiedFile != null );
785 // Not any of the above? Then it's gotta be an artifact reference.
788 // Get the artifact reference in a layout neutral way.
789 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
791 if ( artifact != null )
793 String repositoryLayout = managedRepository.getRepository().getLayout();
795 RepositoryStorage repositoryStorage =
796 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
797 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
799 Path proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
801 resource.setPath( managedRepository.toPath( artifact ) );
803 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
804 artifact.getVersion() );
806 return ( proxiedFile != null );
809 catch ( LayoutException e )
813 catch ( ProxyDownloadException e )
815 log.error( e.getMessage(), e );
816 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
817 "Unable to fetch artifact resource." );
824 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
827 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
828 event.setRemoteIP( remoteIP );
830 for ( AuditListener listener : auditListeners )
832 listener.auditEvent( event );
837 public void addAuditListener( AuditListener listener )
839 this.auditListeners.add( listener );
843 public void clearAuditListeners()
845 this.auditListeners.clear();
849 public void removeAuditListener( AuditListener listener )
851 this.auditListeners.remove( listener );
854 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource,
857 // [MRM-503] - Metadata file need Pragma:no-cache response
859 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
860 && ( Files.isDirectory( ArchivaDavResource.class.cast( resource ).getLocalResource()) ) ) )
862 response.setHeader( "Pragma", "no-cache" );
863 response.setHeader( "Cache-Control", "no-cache" );
864 response.setDateHeader( "Last-Modified", new Date().getTime() );
866 // if the resource is a directory don't cache it as new groupId deployed will be available
867 // without need of refreshing browser
868 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
869 resource instanceof ArchivaVirtualDavResource && ( Files.isDirectory(Paths.get(
870 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() )) ) ) )
872 response.setHeader( "Pragma", "no-cache" );
873 response.setHeader( "Cache-Control", "no-cache" );
874 response.setDateHeader( "Last-Modified", new Date().getTime() );
878 if ( resource instanceof ArchivaVirtualDavResource )
880 //MRM-1854 here we have a directory so force "Last-Modified"
881 response.setDateHeader( "Last-Modified", new Date().getTime() );
886 // We need to specify this so connecting wagons can work correctly
887 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
889 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
892 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
895 if ( !( locator instanceof ArchivaDavResourceLocator ) )
897 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
898 "Locator does not implement RepositoryLocator" );
902 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
904 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
907 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
909 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
910 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
912 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
914 return archivaLocator;
917 private String addHrefPrefix( String contextPath, String path ) {
918 String prefix = archivaConfiguration.getConfiguration().getWebapp().getUi().getApplicationUrl();
919 if (prefix == null || prefix.isEmpty()) {
920 prefix = contextPath;
922 return prefix + ( StringUtils.startsWith( path, "/" ) ? "" :
923 ( StringUtils.endsWith( prefix, "/" ) ? "" : "/" ) )
927 private static class LogicalResource
931 public LogicalResource( String path )
936 public String getPath()
941 public void setPath( String path )
947 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
952 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
953 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
955 return servletAuth.isAuthenticated( request, result ) //
956 && servletAuth.isAuthorized( request, securitySession, repositoryId, //
957 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
959 catch ( AuthenticationException e )
961 // safety check for MRM-911
962 String guest = UserManager.GUEST_USERNAME;
965 if ( servletAuth.isAuthorized( guest,
966 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
967 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
972 catch ( UnauthorizedException ae )
974 throw new UnauthorizedDavException( repositoryId,
975 "You are not authenticated and authorized to access any repository." );
978 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
980 catch ( MustChangePasswordException e )
982 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
984 catch ( AccountLockedException e )
986 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
988 catch ( AuthorizationException e )
990 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
991 "Fatal Authorization Subsystem Error." );
993 catch ( UnauthorizedException e )
995 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
999 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
1000 ArchivaDavResourceLocator locator,
1001 RepositoryGroupConfiguration repositoryGroupConfiguration )
1002 throws DavException, RepositoryAdminException
1004 if ( repositoryGroupConfiguration.getRepositories() == null
1005 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1008 Paths.get( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1010 return new ArchivaDavResource( file.toString(), "groups/" + repositoryGroupConfiguration.getId(), null,
1011 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1014 List<Path> mergedRepositoryContents = new ArrayList<>();
1015 // multiple repo types so we guess they are all the same type
1016 // so use the first one
1017 // FIXME add a method with group in the repository storage
1018 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1020 String path = getLogicalResource( locator, repositoryRegistry.getManagedRepository( firstRepoId ), false );
1021 if ( path.startsWith( "/" ) )
1023 path = path.substring( 1 );
1025 LogicalResource logicalResource = new LogicalResource( path );
1028 // if the current user logged in has permission to any of the repositories, allow user to
1029 // browse the repo group but displaying only the repositories which the user has permission to access.
1030 // otherwise, prompt for authentication.
1032 String activePrincipal = getActivePrincipal( request );
1034 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1037 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1042 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1044 Path mergedRepoDir =
1045 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1046 mergedRepositoryContents.add( mergedRepoDir );
1050 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1052 Path tmpDirectory = Paths.get( SystemUtils.getJavaIoTmpDir().toString(),
1053 repositoryGroupConfiguration.getId(),
1054 repositoryGroupConfiguration.getMergedIndexPath() );
1055 if ( !Files.exists(tmpDirectory) )
1057 synchronized ( tmpDirectory.toAbsolutePath().toString() )
1059 if ( !Files.exists(tmpDirectory) )
1063 Files.createDirectories( tmpDirectory );
1065 catch ( IOException e )
1067 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create direcotory "+tmpDirectory );
1072 mergedRepositoryContents.add( tmpDirectory.getParent() );
1074 for ( String repository : repositories )
1076 ManagedRepositoryContent managedRepository = null;
1077 ManagedRepository repo = repositoryRegistry.getManagedRepository( repository );
1079 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1080 "Invalid managed repository <" + repository + ">");
1082 managedRepository = repo.getContent();
1083 if (managedRepository==null) {
1084 log.error("Inconsistency detected. Repository content not found for '{}'",repository);
1085 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1086 "Invalid managed repository <" + repository + ">");
1088 Path resourceFile = Paths.get( managedRepository.getRepoRoot(), logicalResource.getPath() );
1089 if ( Files.exists(resourceFile) )
1091 // in case of group displaying index directory doesn't have sense !!
1092 IndexCreationFeature idf = managedRepository.getRepository().getFeature(IndexCreationFeature.class).get();
1093 String repoIndexDirectory = idf.getIndexPath().toString();
1094 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1096 if ( !Paths.get( repoIndexDirectory ).isAbsolute() )
1098 repoIndexDirectory = Paths.get( managedRepository.getRepository().getLocation() ).resolve(
1099 StringUtils.isEmpty( repoIndexDirectory )
1101 : repoIndexDirectory ).toAbsolutePath().toString();
1104 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1106 repoIndexDirectory = Paths.get( managedRepository.getRepository().getLocation() ).resolve(
1107 ".indexer" ).toAbsolutePath().toString();
1110 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1111 FilenameUtils.normalize( resourceFile.toAbsolutePath().toString() ) ) )
1113 // for prompted authentication
1114 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1118 if ( isAuthorized( request, repository ) )
1120 mergedRepositoryContents.add( resourceFile );
1121 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1124 catch ( DavException e )
1126 // TODO: review exception handling
1128 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1129 activePrincipal, e.getMessage() );
1136 // for the current user logged in
1139 if ( servletAuth.isAuthorized( activePrincipal, repository,
1140 WebdavMethodUtil.getMethodPermission(
1141 request.getMethod() ) ) )
1143 mergedRepositoryContents.add( resourceFile );
1144 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1147 catch ( UnauthorizedException e )
1149 // TODO: review exception handling
1151 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1152 activePrincipal, e.getMessage() );
1163 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1166 ArchivaVirtualDavResource resource =
1167 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1170 // compatibility with MRM-440 to ensure browsing the repository group works ok
1171 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1173 throw new BrowserRedirectException( resource.getHref() );
1179 protected String getActivePrincipal( DavServletRequest request )
1181 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1182 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1186 * Check if the current user is authorized to access any of the repos
1189 * @param repositories
1190 * @param activePrincipal
1193 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1195 // when no repositories configured it's impossible to browse nothing !
1196 // at least make possible to see nothing :-)
1197 if ( repositories == null || repositories.isEmpty() )
1202 boolean allow = false;
1204 // if securitySession != null, it means that the user was prompted for authentication
1205 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1207 for ( String repository : repositories )
1211 if ( isAuthorized( request, repository ) )
1217 catch ( DavException e )
1225 for ( String repository : repositories )
1229 if ( servletAuth.isAuthorized( activePrincipal, repository,
1230 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1236 catch ( UnauthorizedException e )
1246 private Path writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1247 throws RepositoryMetadataException, DigesterException, IOException
1249 Path outputFile = Paths.get( outputFilename );
1250 if ( Files.exists(outputFile) )
1252 org.apache.archiva.common.utils.FileUtils.deleteQuietly( outputFile );
1255 Files.createDirectories(outputFile.getParent());
1256 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1258 createChecksumFile( outputFilename, digestSha1 );
1259 createChecksumFile( outputFilename, digestMd5 );
1264 private void createChecksumFile( String path, Digester digester )
1265 throws DigesterException, IOException
1267 Path checksumFile = Paths.get( path + digester.getFilenameExtension() );
1268 if ( !Files.exists(checksumFile) )
1270 org.apache.archiva.common.utils.FileUtils.deleteQuietly( checksumFile );
1271 checksum.createChecksum( Paths.get( path ).toFile(), digester );
1273 else if ( !Files.isRegularFile( checksumFile) )
1275 log.error( "Checksum file is not a file." );
1279 private boolean isProjectReference( String requestedResource )
1283 metadataTools.toVersionedReference( requestedResource );
1286 catch ( RepositoryMetadataException re )
1292 protected Path buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1293 DavServletRequest request,
1294 RepositoryGroupConfiguration repositoryGroupConfiguration )
1300 HttpSession session = request.getSession();
1302 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1303 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1304 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1305 if ( temporaryGroupIndexMap == null )
1307 temporaryGroupIndexMap = new HashMap<>();
1310 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1312 if ( tmp != null && tmp.getDirectory() != null && Files.exists(tmp.getDirectory()))
1314 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1315 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1317 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1318 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1319 indexMerger.cleanTemporaryGroupIndex( tmp );
1323 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1324 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1325 return tmp.getDirectory();
1329 Set<String> authzRepos = new HashSet<String>();
1331 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1333 for ( String repository : repositories )
1337 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1339 authzRepos.add( repository );
1340 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1343 catch ( UnauthorizedException e )
1345 // TODO: review exception handling
1347 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1352 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1353 repositoryGroupConfiguration.getId(), authzRepos );
1355 Path tempRepoFile = Files.createTempDirectory( "temp" );
1356 tempRepoFile.toFile().deleteOnExit();
1358 IndexMergerRequest indexMergerRequest =
1359 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1360 repositoryGroupConfiguration.getMergedIndexPath(),
1361 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1362 tempRepoFile ).temporary( true );
1364 MergedRemoteIndexesTaskRequest taskRequest =
1365 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1367 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1369 IndexingContext indexingContext = job.execute().getIndexingContext();
1371 Path mergedRepoDir = indexingContext.getIndexDirectoryFile().toPath();
1372 TemporaryGroupIndex temporaryGroupIndex =
1373 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1374 repositoryGroupConfiguration.getMergedIndexTtl() ) //
1375 .setCreationTime( new Date().getTime() );
1376 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1377 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1378 temporaryGroupIndexMap );
1379 return mergedRepoDir;
1381 catch ( RepositorySearchException e )
1383 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1385 catch ( IndexMergerException e )
1387 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1389 catch ( IOException e )
1391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1396 public void setServletAuth( ServletAuthenticator servletAuth )
1398 this.servletAuth = servletAuth;
1401 public void setHttpAuth( HttpAuthenticator httpAuth )
1403 this.httpAuth = httpAuth;
1406 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1408 this.scheduler = scheduler;
1411 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1413 this.archivaConfiguration = archivaConfiguration;
1416 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1418 this.repositoryFactory = repositoryFactory;
1421 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1423 this.repositoryRequest = repositoryRequest;
1426 public void setConnectors( RepositoryProxyConnectors connectors )
1428 this.connectors = connectors;
1431 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1433 return remoteRepositoryAdmin;
1436 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1438 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1441 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1443 return managedRepositoryAdmin;
1446 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1448 this.managedRepositoryAdmin = managedRepositoryAdmin;
1451 public RepositoryRegistry getRepositoryRegistry( )
1453 return repositoryRegistry;
1456 public void setRepositoryRegistry( RepositoryRegistry repositoryRegistry )
1458 this.repositoryRegistry = repositoryRegistry;