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.ManagedRepository;
24 import org.apache.archiva.admin.model.beans.RemoteRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
27 import org.apache.archiva.metadata.model.facets.AuditEvent;
28 import org.apache.archiva.repository.events.AuditListener;
29 import org.apache.archiva.audit.Auditable;
30 import org.apache.archiva.common.filelock.FileLockManager;
31 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
32 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
33 import org.apache.archiva.common.utils.PathUtil;
34 import org.apache.archiva.common.utils.VersionUtil;
35 import org.apache.archiva.configuration.ArchivaConfiguration;
36 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
37 import org.apache.archiva.indexer.merger.IndexMerger;
38 import org.apache.archiva.indexer.merger.IndexMergerException;
39 import org.apache.archiva.indexer.merger.IndexMergerRequest;
40 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
41 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
42 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
43 import org.apache.archiva.indexer.search.RepositorySearch;
44 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
45 import org.apache.archiva.metadata.repository.storage.RelocationException;
46 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
47 import org.apache.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.archiva.model.ArtifactReference;
49 import org.apache.archiva.policies.ProxyDownloadException;
50 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
51 import org.apache.archiva.redback.authentication.AuthenticationException;
52 import org.apache.archiva.redback.authentication.AuthenticationResult;
53 import org.apache.archiva.redback.authorization.AuthorizationException;
54 import org.apache.archiva.redback.authorization.UnauthorizedException;
55 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
56 import org.apache.archiva.redback.policy.AccountLockedException;
57 import org.apache.archiva.redback.policy.MustChangePasswordException;
58 import org.apache.archiva.redback.system.SecuritySession;
59 import org.apache.archiva.redback.users.User;
60 import org.apache.archiva.redback.users.UserManager;
61 import org.apache.archiva.repository.ManagedRepositoryContent;
62 import org.apache.archiva.repository.RepositoryContentFactory;
63 import org.apache.archiva.repository.RepositoryException;
64 import org.apache.archiva.repository.RepositoryNotFoundException;
65 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
66 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
67 import org.apache.archiva.repository.layout.LayoutException;
68 import org.apache.archiva.repository.metadata.MetadataTools;
69 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
71 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
72 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
73 import org.apache.archiva.security.ServletAuthenticator;
74 import org.apache.archiva.webdav.util.MimeTypes;
75 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
76 import org.apache.archiva.webdav.util.WebdavMethodUtil;
77 import org.apache.archiva.xml.XMLException;
78 import org.apache.commons.io.FileUtils;
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;
107 import java.io.IOException;
108 import java.nio.file.Files;
109 import java.util.ArrayList;
110 import java.util.Date;
111 import java.util.HashMap;
112 import java.util.HashSet;
113 import java.util.List;
114 import java.util.Map;
115 import java.util.Set;
120 @Service( "davResourceFactory#archiva" )
121 public class ArchivaDavResourceFactory
122 implements DavResourceFactory, Auditable
124 private static final String PROXIED_SUFFIX = " (proxied)";
126 private static final String HTTP_PUT_METHOD = "PUT";
128 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
131 private List<AuditListener> auditListeners = new ArrayList<>();
134 private RepositoryContentFactory repositoryFactory;
136 private RepositoryRequest repositoryRequest;
139 @Named( value = "repositoryProxyConnectors#default" )
140 private RepositoryProxyConnectors connectors;
143 private MetadataTools metadataTools;
146 private MimeTypes mimeTypes;
148 private ArchivaConfiguration archivaConfiguration;
151 private ServletAuthenticator servletAuth;
154 @Named( value = "httpAuthenticator#basic" )
155 private HttpAuthenticator httpAuth;
158 private RemoteRepositoryAdmin remoteRepositoryAdmin;
161 private ManagedRepositoryAdmin managedRepositoryAdmin;
164 private IndexMerger indexMerger;
167 private RepositorySearch repositorySearch;
170 * Lock Manager - use simple implementation from JackRabbit
172 private final LockManager lockManager = new SimpleLockManager();
174 private ChecksumFile checksum;
176 private Digester digestSha1;
178 private Digester digestMd5;
181 @Named( value = "archivaTaskScheduler#repository" )
182 private RepositoryArchivaTaskScheduler scheduler;
185 @Named( value = "fileLockManager#default" )
186 private FileLockManager fileLockManager;
188 private ApplicationContext applicationContext;
191 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
192 ArchivaConfiguration archivaConfiguration )
193 throws PlexusSisuBridgeException
195 this.archivaConfiguration = archivaConfiguration;
196 this.applicationContext = applicationContext;
197 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
199 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
200 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
202 // TODO remove this hard dependency on maven !!
203 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
207 public void initialize()
213 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
214 final DavServletResponse response )
217 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
219 RepositoryGroupConfiguration repoGroupConfig =
220 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
222 String activePrincipal = getActivePrincipal( request );
224 List<String> resourcesInAbsolutePath = new ArrayList<>();
226 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
227 DavResource resource;
228 if ( repoGroupConfig != null )
232 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
233 "Write method not allowed for repository groups." );
236 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
238 // handle browse requests for virtual repos
239 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
243 DavResource davResource =
244 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
247 setHeaders( response, locator, davResource );
252 catch ( RepositoryAdminException e )
254 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
259 // make a copy to avoid potential concurrent modifications (eg. by configuration)
260 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
262 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
263 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
264 resourcesInAbsolutePath, repoGroupConfig );
272 RemoteRepository remoteRepository =
273 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
275 if ( remoteRepository != null )
277 String logicalResource = getLogicalResource( archivaLocator, null, false );
278 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
279 File resourceFile = StringUtils.equals( logicalResource, "/" )
280 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
281 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
282 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
283 request.getRemoteAddr(), activePrincipal,
284 request.getDavSession(), archivaLocator, this, mimeTypes,
285 auditListeners, scheduler, fileLockManager );
286 setHeaders( response, locator, resource );
290 catch ( RepositoryAdminException e )
292 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
293 archivaLocator.getRepositoryId(), e.getMessage() );
296 ManagedRepositoryContent managedRepositoryContent = null;
300 managedRepositoryContent =
301 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
303 catch ( RepositoryNotFoundException e )
305 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
306 "Invalid repository: " + archivaLocator.getRepositoryId() );
308 catch ( RepositoryException e )
310 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
313 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
317 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
318 managedRepositoryAdmin.getManagedRepository(
319 archivaLocator.getRepositoryId() )
322 String logicalResource = getLogicalResource( archivaLocator, null, false );
323 resourcesInAbsolutePath.add(
324 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
327 catch ( RepositoryAdminException e )
329 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
333 String requestedResource = request.getRequestURI();
335 // MRM-872 : merge all available metadata
336 // merge metadata only when requested via the repo group
337 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
338 requestedResource ) ) && repoGroupConfig != null )
340 // this should only be at the project level not version level!
341 if ( isProjectReference( requestedResource ) )
344 ArchivaDavResource res = (ArchivaDavResource) resource;
346 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
348 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
350 // for MRM-872 handle checksums of the merged metadata files
351 if ( repositoryRequest.isSupportFile( requestedResource ) )
353 File metadataChecksum =
354 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
355 if ( metadataChecksum.exists() )
357 LogicalResource logicalResource =
358 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
361 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), 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 File metadataFile = new File( 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 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
397 LogicalResource logicalResource =
398 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
401 new ArchivaDavResource( resourceFile.getAbsolutePath(), 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 );
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 File temporaryIndexDirectory =
456 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
458 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
459 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
460 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
461 archivaLocator, this, mimeTypes, auditListeners, scheduler,
467 for ( String repositoryId : repositories )
469 ManagedRepositoryContent managedRepositoryContent;
472 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
474 catch ( RepositoryNotFoundException e )
476 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
478 catch ( RepositoryException e )
480 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
485 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
486 DavResource updatedResource =
487 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
489 if ( resource == null )
491 resource = updatedResource;
494 String logicalResource = getLogicalResource( archivaLocator, null, false );
495 if ( logicalResource.endsWith( "/" ) )
497 logicalResource = logicalResource.substring( 1 );
499 resourcesInAbsolutePath.add(
500 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
502 catch ( DavException e )
504 storedExceptions.add( e );
506 catch ( RepositoryAdminException e )
508 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
512 if ( resource == null )
514 if ( !storedExceptions.isEmpty() )
517 for ( DavException e : storedExceptions )
519 if ( 401 == e.getErrorCode() )
525 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
529 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
535 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
536 boolean useOrigResourcePath )
538 // FIXME remove this hack
539 // but currently managedRepository can be null in case of group
540 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
541 RepositoryStorage repositoryStorage =
542 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
543 String path = repositoryStorage.getFilePath(
544 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
546 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
547 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
552 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator,
553 ManagedRepositoryContent managedRepositoryContent, String contextPath )
556 String layout = managedRepositoryContent.getRepository() == null
557 ? new ManagedRepository().getLayout()
558 : managedRepositoryContent.getRepository().getLayout();
559 RepositoryStorage repositoryStorage =
560 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
563 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(),
564 managedRepositoryContent );
566 catch ( RelocationException e )
568 String path = e.getPath();
569 log.debug( "Relocation to {}", path );
571 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
572 e.getRelocationType() );
574 catch ( XMLException e )
576 log.error( e.getMessage(), e );
577 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
581 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
582 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
583 ManagedRepository managedRepository )
586 DavResource resource = null;
587 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
589 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
590 // Maven Centric part ask evaluation if -SNAPSHOT
591 // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
593 String path = readMethod ?
594 evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
595 : getLogicalResource( archivaLocator, managedRepository, false );
596 if ( path.startsWith( "/" ) )
598 path = path.substring( 1 );
600 LogicalResource logicalResource = new LogicalResource( path );
601 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
603 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
604 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
605 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
607 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
609 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
611 // force a resource not found
612 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
616 if ( !resource.isCollection() )
618 boolean previouslyExisted = resourceFile.exists();
620 // Attempt to fetch the resource from any defined proxy.
622 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
624 // At this point the incoming request can either be in default or
625 // legacy layout format.
628 // Perform an adjustment of the resource to the managed
629 // repository expected path.
630 String localResourcePath =
631 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
632 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
634 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
635 managedRepositoryContent.getRepository(),
636 request.getRemoteAddr(), activePrincipal,
637 request.getDavSession(), archivaLocator, this, mimeTypes,
638 auditListeners, scheduler, fileLockManager );
640 catch ( LayoutException e )
642 if ( !resourceFile.exists() )
644 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
650 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
653 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
654 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
656 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
657 logicalResource.getPath(), event, activePrincipal );
660 if ( !resourceFile.exists() )
662 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
668 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
670 String resourcePath = logicalResource.getPath();
672 // check if target repo is enabled for releases
673 // we suppose that release-artifacts can be deployed only to repos enabled for releases
674 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
675 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
677 ArtifactReference artifact = null;
680 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
682 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
684 // check if artifact already exists and if artifact re-deployment to the repository is allowed
685 if ( managedRepositoryContent.hasContent( artifact )
686 && managedRepositoryContent.getRepository().isBlockRedeployments() )
688 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
689 managedRepositoryContent.getId() );
690 throw new DavException( HttpServletResponse.SC_CONFLICT,
691 "Overwriting released artifacts is not allowed." );
695 catch ( LayoutException e )
697 log.warn( "Artifact path '{}' is invalid.", resourcePath );
702 * Create parent directories that don't exist when writing a file This actually makes this
703 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
704 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
705 * create the collections themselves.
708 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
709 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
711 if ( !destDir.exists() )
714 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
716 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
719 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
720 AuditEvent.CREATE_DIR, activePrincipal );
728 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
731 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
733 ManagedRepositoryContent managedRepositoryContent;
736 managedRepositoryContent =
737 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
739 catch ( RepositoryNotFoundException e )
741 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
742 "Invalid repository: " + archivaLocator.getRepositoryId() );
744 catch ( RepositoryException e )
746 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
749 DavResource resource = null;
752 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
753 archivaLocator.getRepositoryId() ), false );
754 if ( logicalResource.startsWith( "/" ) )
756 logicalResource = logicalResource.substring( 1 );
758 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
759 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
760 managedRepositoryContent.getRepository(), davSession, archivaLocator,
761 this, mimeTypes, auditListeners, scheduler, fileLockManager );
763 resource.addLockManager( lockManager );
765 catch ( RepositoryAdminException e )
767 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
772 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
773 LogicalResource resource )
776 String path = resource.getPath();
777 if ( repositoryRequest.isSupportFile( path ) )
779 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
781 return ( proxiedFile != null );
784 // Is it a Metadata resource?
785 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
787 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
790 // Is it an Archetype Catalog?
791 if ( repositoryRequest.isArchetypeCatalog( path ) )
793 // FIXME we must implement a merge of remote archetype catalog from remote servers.
794 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
796 return ( proxiedFile != null );
799 // Not any of the above? Then it's gotta be an artifact reference.
802 // Get the artifact reference in a layout neutral way.
803 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
805 if ( artifact != null )
807 String repositoryLayout = managedRepository.getRepository().getLayout();
809 RepositoryStorage repositoryStorage =
810 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
811 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
813 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
815 resource.setPath( managedRepository.toPath( artifact ) );
817 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
818 artifact.getVersion() );
820 return ( proxiedFile != null );
823 catch ( LayoutException e )
827 catch ( ProxyDownloadException e )
829 log.error( e.getMessage(), e );
830 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
831 "Unable to fetch artifact resource." );
838 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
841 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
842 event.setRemoteIP( remoteIP );
844 for ( AuditListener listener : auditListeners )
846 listener.auditEvent( event );
851 public void addAuditListener( AuditListener listener )
853 this.auditListeners.add( listener );
857 public void clearAuditListeners()
859 this.auditListeners.clear();
863 public void removeAuditListener( AuditListener listener )
865 this.auditListeners.remove( listener );
868 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
870 // [MRM-503] - Metadata file need Pragma:no-cache response
872 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
873 && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
875 response.setHeader( "Pragma", "no-cache" );
876 response.setHeader( "Cache-Control", "no-cache" );
877 response.setDateHeader( "Last-Modified", new Date().getTime() );
879 // if the resource is a directory don't cache it as new groupId deployed will be available
880 // without need of refreshing browser
881 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
882 resource instanceof ArchivaVirtualDavResource && ( new File(
883 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
885 response.setHeader( "Pragma", "no-cache" );
886 response.setHeader( "Cache-Control", "no-cache" );
887 response.setDateHeader( "Last-Modified", new Date().getTime() );
891 // We need to specify this so connecting wagons can work correctly
892 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
894 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
897 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
900 if ( !( locator instanceof ArchivaDavResourceLocator ) )
902 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
903 "Locator does not implement RepositoryLocator" );
907 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
909 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
912 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
914 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
915 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
917 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
919 return archivaLocator;
922 private static class LogicalResource
926 public LogicalResource( String path )
931 public String getPath()
936 public void setPath( String path )
942 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
947 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
948 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
950 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
952 WebdavMethodUtil.getMethodPermission(
953 request.getMethod() )
956 catch ( AuthenticationException e )
958 // safety check for MRM-911
959 String guest = UserManager.GUEST_USERNAME;
962 if ( servletAuth.isAuthorized( guest,
963 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
964 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
969 catch ( UnauthorizedException ae )
971 throw new UnauthorizedDavException( repositoryId,
972 "You are not authenticated and authorized to access any repository." );
975 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
977 catch ( MustChangePasswordException e )
979 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
981 catch ( AccountLockedException e )
983 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
985 catch ( AuthorizationException e )
987 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
988 "Fatal Authorization Subsystem Error." );
990 catch ( UnauthorizedException e )
992 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
996 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
997 ArchivaDavResourceLocator locator,
998 RepositoryGroupConfiguration repositoryGroupConfiguration )
999 throws DavException, RepositoryAdminException
1001 if ( repositoryGroupConfiguration.getRepositories() == null
1002 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1005 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1007 return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1008 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1011 List<File> mergedRepositoryContents = new ArrayList<>();
1012 // multiple repo types so we guess they are all the same type
1013 // so use the first one
1014 // FIXME add a method with group in the repository storage
1015 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1017 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1018 if ( path.startsWith( "/" ) )
1020 path = path.substring( 1 );
1022 LogicalResource logicalResource = new LogicalResource( path );
1025 // if the current user logged in has permission to any of the repositories, allow user to
1026 // browse the repo group but displaying only the repositories which the user has permission to access.
1027 // otherwise, prompt for authentication.
1029 String activePrincipal = getActivePrincipal( request );
1031 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1034 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1039 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1041 File mergedRepoDir =
1042 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1043 mergedRepositoryContents.add( mergedRepoDir );
1047 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1049 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1050 repositoryGroupConfiguration.getId() + "/"
1051 + repositoryGroupConfiguration.getMergedIndexPath()
1053 if ( !tmpDirectory.exists() )
1055 synchronized ( tmpDirectory.getAbsolutePath() )
1057 if ( !tmpDirectory.exists() )
1059 tmpDirectory.mkdirs();
1063 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1065 for ( String repository : repositories )
1067 ManagedRepositoryContent managedRepository = null;
1071 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1073 catch ( RepositoryNotFoundException e )
1075 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1076 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1078 catch ( RepositoryException e )
1080 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1081 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1084 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1085 if ( resourceFile.exists() )
1087 // in case of group displaying index directory doesn't have sense !!
1088 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1089 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1091 if ( !new File( repoIndexDirectory ).isAbsolute() )
1093 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1094 StringUtils.isEmpty( repoIndexDirectory )
1096 : repoIndexDirectory
1097 ).getAbsolutePath();
1100 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1102 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1103 ".indexer" ).getAbsolutePath();
1106 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1107 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1109 // for prompted authentication
1110 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1114 if ( isAuthorized( request, repository ) )
1116 mergedRepositoryContents.add( resourceFile );
1117 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1120 catch ( DavException e )
1122 // TODO: review exception handling
1124 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1125 activePrincipal, e.getMessage() );
1132 // for the current user logged in
1135 if ( servletAuth.isAuthorized( activePrincipal, repository,
1136 WebdavMethodUtil.getMethodPermission(
1137 request.getMethod() )
1140 mergedRepositoryContents.add( resourceFile );
1141 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1144 catch ( UnauthorizedException e )
1146 // TODO: review exception handling
1148 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1149 activePrincipal, e.getMessage() );
1160 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1163 ArchivaVirtualDavResource resource =
1164 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1167 // compatibility with MRM-440 to ensure browsing the repository group works ok
1168 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1170 throw new BrowserRedirectException( resource.getHref() );
1176 protected String getActivePrincipal( DavServletRequest request )
1178 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1179 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1183 * Check if the current user is authorized to access any of the repos
1186 * @param repositories
1187 * @param activePrincipal
1190 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1192 // when no repositories configured it's impossible to browse nothing !
1193 // at least make possible to see nothing :-)
1194 if ( repositories == null || repositories.isEmpty() )
1199 boolean allow = false;
1201 // if securitySession != null, it means that the user was prompted for authentication
1202 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1204 for ( String repository : repositories )
1208 if ( isAuthorized( request, repository ) )
1214 catch ( DavException e )
1222 for ( String repository : repositories )
1226 if ( servletAuth.isAuthorized( activePrincipal, repository,
1227 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1233 catch ( UnauthorizedException e )
1243 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1244 throws RepositoryMetadataException, DigesterException, IOException
1246 File outputFile = new File( outputFilename );
1247 if ( outputFile.exists() )
1249 FileUtils.deleteQuietly( outputFile );
1252 outputFile.getParentFile().mkdirs();
1253 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1255 createChecksumFile( outputFilename, digestSha1 );
1256 createChecksumFile( outputFilename, digestMd5 );
1261 private void createChecksumFile( String path, Digester digester )
1262 throws DigesterException, IOException
1264 File checksumFile = new File( path + digester.getFilenameExtension() );
1265 if ( !checksumFile.exists() )
1267 FileUtils.deleteQuietly( checksumFile );
1268 checksum.createChecksum( new File( path ), digester );
1270 else if ( !checksumFile.isFile() )
1272 log.error( "Checksum file is not a file." );
1276 private boolean isProjectReference( String requestedResource )
1280 metadataTools.toVersionedReference( requestedResource );
1283 catch ( RepositoryMetadataException re )
1289 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1290 DavServletRequest request,
1291 RepositoryGroupConfiguration repositoryGroupConfiguration )
1297 HttpSession session = request.getSession();
1299 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1300 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1301 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1302 if ( temporaryGroupIndexMap == null )
1304 temporaryGroupIndexMap = new HashMap<>();
1307 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1309 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1311 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1312 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1314 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1315 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1316 indexMerger.cleanTemporaryGroupIndex( tmp );
1320 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1321 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1322 return tmp.getDirectory();
1326 Set<String> authzRepos = new HashSet<String>();
1328 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1330 for ( String repository : repositories )
1334 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1336 authzRepos.add( repository );
1337 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1340 catch ( UnauthorizedException e )
1342 // TODO: review exception handling
1344 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1348 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1349 repositoryGroupConfiguration.getId(), authzRepos );
1351 File tempRepoFile = Files.createTempDirectory("temp").toFile();
1352 tempRepoFile.deleteOnExit();
1354 IndexMergerRequest indexMergerRequest =
1355 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1356 repositoryGroupConfiguration.getMergedIndexPath(),
1357 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1358 tempRepoFile ).temporary( true );
1360 MergedRemoteIndexesTaskRequest taskRequest =
1361 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1363 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1365 IndexingContext indexingContext = job.execute().getIndexingContext();
1367 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1368 TemporaryGroupIndex temporaryGroupIndex =
1369 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1370 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1371 new Date().getTime() );
1372 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1373 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1374 temporaryGroupIndexMap );
1375 return mergedRepoDir;
1377 catch ( RepositoryAdminException e )
1379 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1381 catch ( IndexMergerException e )
1383 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1384 } catch ( IOException e )
1386 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1391 public void setServletAuth( ServletAuthenticator servletAuth )
1393 this.servletAuth = servletAuth;
1396 public void setHttpAuth( HttpAuthenticator httpAuth )
1398 this.httpAuth = httpAuth;
1401 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1403 this.scheduler = scheduler;
1406 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1408 this.archivaConfiguration = archivaConfiguration;
1411 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1413 this.repositoryFactory = repositoryFactory;
1416 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1418 this.repositoryRequest = repositoryRequest;
1421 public void setConnectors( RepositoryProxyConnectors connectors )
1423 this.connectors = connectors;
1426 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1428 return remoteRepositoryAdmin;
1431 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1433 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1436 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1438 return managedRepositoryAdmin;
1441 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1443 this.managedRepositoryAdmin = managedRepositoryAdmin;