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.remote.RemoteRepositoryAdmin;
25 import org.apache.archiva.audit.AuditEvent;
26 import org.apache.archiva.audit.AuditListener;
27 import org.apache.archiva.audit.Auditable;
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.TemporaryGroupIndex;
37 import org.apache.archiva.indexer.search.RepositorySearch;
38 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
39 import org.apache.archiva.model.ArchivaRepositoryMetadata;
40 import org.apache.archiva.model.ArtifactReference;
41 import org.apache.archiva.policies.ProxyDownloadException;
42 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
43 import org.apache.archiva.redback.authentication.AuthenticationException;
44 import org.apache.archiva.redback.authentication.AuthenticationResult;
45 import org.apache.archiva.redback.authorization.AuthorizationException;
46 import org.apache.archiva.redback.authorization.UnauthorizedException;
47 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
48 import org.apache.archiva.redback.policy.AccountLockedException;
49 import org.apache.archiva.redback.policy.MustChangePasswordException;
50 import org.apache.archiva.redback.system.SecuritySession;
51 import org.apache.archiva.redback.users.User;
52 import org.apache.archiva.redback.users.UserManager;
53 import org.apache.archiva.repository.ManagedRepositoryContent;
54 import org.apache.archiva.repository.RepositoryContentFactory;
55 import org.apache.archiva.repository.RepositoryException;
56 import org.apache.archiva.repository.RepositoryNotFoundException;
57 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
58 import org.apache.archiva.repository.layout.LayoutException;
59 import org.apache.archiva.repository.metadata.MetadataTools;
60 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
64 import org.apache.archiva.security.ServletAuthenticator;
65 import org.apache.archiva.webdav.util.MimeTypes;
66 import org.apache.archiva.webdav.util.RepositoryPathUtil;
67 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
68 import org.apache.archiva.webdav.util.WebdavMethodUtil;
69 import org.apache.archiva.xml.XMLException;
70 import org.apache.commons.io.FileUtils;
71 import org.apache.commons.io.FilenameUtils;
72 import org.apache.commons.lang.StringUtils;
73 import org.apache.jackrabbit.webdav.DavException;
74 import org.apache.jackrabbit.webdav.DavResource;
75 import org.apache.jackrabbit.webdav.DavResourceFactory;
76 import org.apache.jackrabbit.webdav.DavResourceLocator;
77 import org.apache.jackrabbit.webdav.DavServletRequest;
78 import org.apache.jackrabbit.webdav.DavServletResponse;
79 import org.apache.jackrabbit.webdav.DavSession;
80 import org.apache.jackrabbit.webdav.lock.LockManager;
81 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
82 import org.apache.maven.index.context.IndexingContext;
83 import org.apache.maven.model.DistributionManagement;
84 import org.apache.maven.model.Model;
85 import org.apache.maven.model.Relocation;
86 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
87 import org.codehaus.plexus.digest.ChecksumFile;
88 import org.codehaus.plexus.digest.Digester;
89 import org.codehaus.plexus.digest.DigesterException;
90 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
93 import org.springframework.context.ApplicationContext;
94 import org.springframework.stereotype.Service;
96 import javax.annotation.PostConstruct;
97 import javax.inject.Inject;
98 import javax.inject.Named;
99 import javax.servlet.http.HttpServletResponse;
100 import javax.servlet.http.HttpSession;
102 import java.io.FileNotFoundException;
103 import java.io.FileReader;
104 import java.io.IOException;
105 import java.util.ArrayList;
106 import java.util.Date;
107 import java.util.HashMap;
108 import java.util.HashSet;
109 import java.util.List;
110 import java.util.Map;
111 import java.util.Set;
116 @Service ( "davResourceFactory#archiva" )
117 public class ArchivaDavResourceFactory
118 implements DavResourceFactory, Auditable
120 private static final String PROXIED_SUFFIX = " (proxied)";
122 private static final String HTTP_PUT_METHOD = "PUT";
124 private static final MavenXpp3Reader MAVEN_XPP_3_READER = new MavenXpp3Reader();
126 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
132 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
138 private RepositoryContentFactory repositoryFactory;
143 private RepositoryRequest repositoryRequest;
149 @Named ( value = "repositoryProxyConnectors#default" )
150 private RepositoryProxyConnectors connectors;
156 private MetadataTools metadataTools;
162 private MimeTypes mimeTypes;
167 private ArchivaConfiguration archivaConfiguration;
173 private ServletAuthenticator servletAuth;
179 @Named ( value = "httpAuthenticator#basic" )
180 private HttpAuthenticator httpAuth;
183 private RemoteRepositoryAdmin remoteRepositoryAdmin;
186 private IndexMerger indexMerger;
189 private RepositorySearch repositorySearch;
192 * Lock Manager - use simple implementation from JackRabbit
194 private final LockManager lockManager = new SimpleLockManager();
199 private ChecksumFile checksum;
204 private Digester digestSha1;
209 private Digester digestMd5;
215 @Named ( value = "archivaTaskScheduler#repository" )
216 private RepositoryArchivaTaskScheduler scheduler;
218 private ApplicationContext applicationContext;
221 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
222 ArchivaConfiguration archivaConfiguration )
223 throws PlexusSisuBridgeException
225 this.archivaConfiguration = archivaConfiguration;
226 this.applicationContext = applicationContext;
227 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
229 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
230 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
232 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
236 public void initialize()
241 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
242 final DavServletResponse response )
245 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
247 RepositoryGroupConfiguration repoGroupConfig =
248 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
250 String activePrincipal = getActivePrincipal( request );
252 List<String> resourcesInAbsolutePath = new ArrayList<String>();
254 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
255 DavResource resource;
256 if ( repoGroupConfig != null )
260 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
261 "Write method not allowed for repository groups." );
264 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
266 // handle browse requests for virtual repos
267 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
269 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
270 archivaLocator.getRepositoryId() );
274 // make a copy to avoid potential concurrent modifications (eg. by configuration)
275 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
277 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
278 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
279 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
287 RemoteRepository remoteRepository =
288 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
290 if ( remoteRepository != null )
292 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
293 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
294 File resourceFile = StringUtils.equals( logicalResource, "/" )
295 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
296 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
297 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
298 request.getRemoteAddr(), activePrincipal,
299 request.getDavSession(), archivaLocator, this, mimeTypes,
300 auditListeners, scheduler );
301 setHeaders( response, locator, resource );
305 catch ( RepositoryAdminException e )
307 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
308 archivaLocator.getRepositoryId(), e.getMessage() );
311 ManagedRepositoryContent managedRepository = null;
315 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
317 catch ( RepositoryNotFoundException e )
319 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
320 "Invalid repository: " + archivaLocator.getRepositoryId() );
322 catch ( RepositoryException e )
324 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
327 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
329 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
331 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
332 resourcesInAbsolutePath.add(
333 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
336 String requestedResource = request.getRequestURI();
338 // MRM-872 : merge all available metadata
339 // merge metadata only when requested via the repo group
340 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
341 requestedResource ) ) && repoGroupConfig != null )
343 // this should only be at the project level not version level!
344 if ( isProjectReference( requestedResource ) )
347 ArchivaDavResource res = (ArchivaDavResource) resource;
349 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
351 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
353 // for MRM-872 handle checksums of the merged metadata files
354 if ( repositoryRequest.isSupportFile( requestedResource ) )
356 File metadataChecksum =
357 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
358 if ( metadataChecksum.exists() )
360 LogicalResource logicalResource =
361 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
364 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
365 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
366 archivaLocator, this, mimeTypes, auditListeners, scheduler );
371 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
373 // merge the metadata of all repos under group
374 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
375 for ( String resourceAbsPath : resourcesInAbsolutePath )
379 File metadataFile = new File( resourceAbsPath );
380 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
381 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
383 catch ( XMLException e )
385 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
386 "Error occurred while reading metadata file." );
388 catch ( RepositoryMetadataException r )
390 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
391 "Error occurred while merging metadata file." );
397 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
399 LogicalResource logicalResource = new LogicalResource(
400 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
403 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
404 request.getRemoteAddr(), activePrincipal,
405 request.getDavSession(), archivaLocator, this, mimeTypes,
406 auditListeners, scheduler );
408 catch ( RepositoryMetadataException r )
410 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
411 "Error occurred while writing metadata file." );
413 catch ( IOException ie )
415 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
416 "Error occurred while generating checksum files." );
418 catch ( DigesterException de )
420 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
421 "Error occurred while generating checksum files." );
428 setHeaders( response, locator, resource );
430 // compatibility with MRM-440 to ensure browsing the repository works ok
431 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
433 throw new BrowserRedirectException( resource.getHref() );
435 resource.addLockManager( lockManager );
439 private DavResource processRepositoryGroup( final DavServletRequest request,
440 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
441 String activePrincipal, List<String> resourcesInAbsolutePath,
442 String repositoryGroupId )
445 DavResource resource = null;
446 List<DavException> storedExceptions = new ArrayList<DavException>();
448 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
450 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
452 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
454 // we are in the case of index file request
455 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
456 File temporaryIndexDirectory =
457 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
459 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
460 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
461 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
462 archivaLocator, this, mimeTypes, auditListeners, scheduler );
467 for ( String repositoryId : repositories )
469 ManagedRepositoryContent managedRepository;
472 managedRepository = 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 DavResource updatedResource =
486 processRepository( request, archivaLocator, activePrincipal, managedRepository );
487 if ( resource == null )
489 resource = updatedResource;
492 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
493 if ( logicalResource.endsWith( "/" ) )
495 logicalResource = logicalResource.substring( 1 );
497 resourcesInAbsolutePath.add(
498 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
500 catch ( DavException e )
502 storedExceptions.add( e );
506 if ( resource == null )
508 if ( !storedExceptions.isEmpty() )
511 for ( DavException e : storedExceptions )
513 if ( 401 == e.getErrorCode() )
519 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
523 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
529 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
530 String activePrincipal, ManagedRepositoryContent managedRepository )
533 DavResource resource = null;
534 if ( isAuthorized( request, managedRepository.getId() ) )
536 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
537 if ( path.startsWith( "/" ) )
539 path = path.substring( 1 );
541 LogicalResource logicalResource = new LogicalResource( path );
542 File resourceFile = new File( managedRepository.getRepoRoot(), path );
543 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
544 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
545 archivaLocator, this, mimeTypes, auditListeners, scheduler );
547 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
549 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
551 // force a resource not found
552 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
556 if ( !resource.isCollection() )
558 boolean previouslyExisted = resourceFile.exists();
560 // Attempt to fetch the resource from any defined proxy.
561 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
563 // At this point the incoming request can either be in default or
564 // legacy layout format.
567 // Perform an adjustment of the resource to the managed
568 // repository expected path.
569 String localResourcePath =
570 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
571 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
573 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
574 managedRepository.getRepository(), request.getRemoteAddr(),
575 activePrincipal, request.getDavSession(), archivaLocator, this,
576 mimeTypes, auditListeners, scheduler );
578 catch ( LayoutException e )
580 if ( !resourceFile.exists() )
582 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
588 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
591 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
592 resourceFile.getName(), managedRepository.getId(), activePrincipal );
594 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
595 logicalResource.getPath(), event, activePrincipal );
598 if ( !resourceFile.exists() )
600 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
606 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
608 String resourcePath = logicalResource.getPath();
610 // check if target repo is enabled for releases
611 // we suppose that release-artifacts can be deployed only to repos enabled for releases
612 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
613 && !repositoryRequest.isSupportFile( resourcePath ) )
615 ArtifactReference artifact = null;
618 artifact = managedRepository.toArtifactReference( resourcePath );
620 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
622 // check if artifact already exists and if artifact re-deployment to the repository is allowed
623 if ( managedRepository.hasContent( artifact )
624 && managedRepository.getRepository().isBlockRedeployments() )
626 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
627 managedRepository.getId() );
628 throw new DavException( HttpServletResponse.SC_CONFLICT,
629 "Overwriting released artifacts is not allowed." );
633 catch ( LayoutException e )
635 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
640 * Create parent directories that don't exist when writing a file This actually makes this
641 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
642 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
643 * create the collections themselves.
646 File rootDirectory = new File( managedRepository.getRepoRoot() );
647 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
649 if ( !destDir.exists() )
652 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
654 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
657 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
658 AuditEvent.CREATE_DIR, activePrincipal );
665 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
668 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
670 ManagedRepositoryContent managedRepository;
673 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
675 catch ( RepositoryNotFoundException e )
677 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
678 "Invalid repository: " + archivaLocator.getRepositoryId() );
680 catch ( RepositoryException e )
682 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
685 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
686 if ( logicalResource.startsWith( "/" ) )
688 logicalResource = logicalResource.substring( 1 );
690 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
691 DavResource resource =
692 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
693 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
695 resource.addLockManager( lockManager );
699 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
700 LogicalResource resource )
703 String path = resource.getPath();
704 if ( repositoryRequest.isSupportFile( path ) )
706 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
708 return ( proxiedFile != null );
711 // Is it a Metadata resource?
712 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
714 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
717 // Is it an Archetype Catalog?
718 if ( repositoryRequest.isArchetypeCatalog( path ) )
720 // FIXME we must implement a merge of remote archetype catalog from remote servers.
721 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
723 return ( proxiedFile != null );
726 // Not any of the above? Then it's gotta be an artifact reference.
729 // Get the artifact reference in a layout neutral way.
730 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
732 if ( artifact != null )
734 applyServerSideRelocation( managedRepository, artifact );
736 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
738 resource.setPath( managedRepository.toPath( artifact ) );
740 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
741 artifact.getVersion() );
743 return ( proxiedFile != null );
746 catch ( LayoutException e )
750 catch ( ProxyDownloadException e )
752 log.error( e.getMessage(), e );
753 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
754 "Unable to fetch artifact resource." );
760 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
761 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
764 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
765 * metadatas and serving the expected artifact.
767 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
768 throws ProxyDownloadException
770 if ( "pom".equals( artifact.getType() ) )
775 // Build the artifact POM reference
776 ArtifactReference pomReference = new ArtifactReference();
777 pomReference.setGroupId( artifact.getGroupId() );
778 pomReference.setArtifactId( artifact.getArtifactId() );
779 pomReference.setVersion( artifact.getVersion() );
780 pomReference.setType( "pom" );
782 // Get the artifact POM from proxied repositories if needed
783 connectors.fetchFromProxies( managedRepository, pomReference );
785 // Open and read the POM from the managed repo
786 File pom = managedRepository.toFile( pomReference );
795 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
796 FileReader reader = new FileReader( pom );
800 model = MAVEN_XPP_3_READER.read( reader );
804 if ( reader != null )
810 DistributionManagement dist = model.getDistributionManagement();
813 Relocation relocation = dist.getRelocation();
814 if ( relocation != null )
816 // artifact is relocated : update the repositoryPath
817 if ( relocation.getGroupId() != null )
819 artifact.setGroupId( relocation.getGroupId() );
821 if ( relocation.getArtifactId() != null )
823 artifact.setArtifactId( relocation.getArtifactId() );
825 if ( relocation.getVersion() != null )
827 artifact.setVersion( relocation.getVersion() );
832 catch ( FileNotFoundException e )
834 // Artifact has no POM in repo : ignore
836 catch ( IOException e )
838 // Unable to read POM : ignore.
840 catch ( XmlPullParserException e )
842 // Invalid POM : ignore
848 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
851 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
852 event.setRemoteIP( remoteIP );
854 for ( AuditListener listener : auditListeners )
856 listener.auditEvent( event );
860 public void addAuditListener( AuditListener listener )
862 this.auditListeners.add( listener );
865 public void clearAuditListeners()
867 this.auditListeners.clear();
870 public void removeAuditListener( AuditListener listener )
872 this.auditListeners.remove( listener );
875 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
877 // [MRM-503] - Metadata file need Pragma:no-cache response
879 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
880 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
882 response.setHeader( "Pragma", "no-cache" );
883 response.setHeader( "Cache-Control", "no-cache" );
884 response.setDateHeader( "Last-Modified", new Date().getTime() );
886 // if the resource is a directory don't cache it as new groupId deployed will be available
887 // without need of refreshing browser
890 // We need to specify this so connecting wagons can work correctly
891 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
893 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
896 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
899 if ( !( locator instanceof ArchivaDavResourceLocator ) )
901 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
902 "Locator does not implement RepositoryLocator" );
906 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
908 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
911 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
913 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
914 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
916 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
918 return archivaLocator;
921 private static class LogicalResource
925 public LogicalResource( String path )
930 public String getPath()
935 public void setPath( String path )
941 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
946 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
947 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
949 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
951 WebdavMethodUtil.getMethodPermission(
952 request.getMethod() ) );
954 catch ( AuthenticationException e )
956 // safety check for MRM-911
957 String guest = UserManager.GUEST_USERNAME;
960 if ( servletAuth.isAuthorized( guest,
961 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
962 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
967 catch ( UnauthorizedException ae )
969 throw new UnauthorizedDavException( repositoryId,
970 "You are not authenticated and authorized to access any repository." );
973 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
975 catch ( MustChangePasswordException e )
977 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
979 catch ( AccountLockedException e )
981 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
983 catch ( AuthorizationException e )
985 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
986 "Fatal Authorization Subsystem Error." );
988 catch ( UnauthorizedException e )
990 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
994 private DavResource getResource( DavServletRequest request, List<String> repositories,
995 ArchivaDavResourceLocator locator, String groupId )
998 List<File> mergedRepositoryContents = new ArrayList<File>();
999 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
1000 if ( path.startsWith( "/" ) )
1002 path = path.substring( 1 );
1004 LogicalResource logicalResource = new LogicalResource( path );
1007 // if the current user logged in has permission to any of the repositories, allow user to
1008 // browse the repo group but displaying only the repositories which the user has permission to access.
1009 // otherwise, prompt for authentication.
1011 String activePrincipal = getActivePrincipal( request );
1013 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1019 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1020 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
1022 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
1023 mergedRepositoryContents.add( mergedRepoDir );
1027 for ( String repository : repositories )
1029 ManagedRepositoryContent managedRepository = null;
1033 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1035 catch ( RepositoryNotFoundException e )
1037 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1038 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1040 catch ( RepositoryException e )
1042 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1043 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1046 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1047 if ( resourceFile.exists() )
1049 // in case of group displaying index directory doesn't have sense !!
1050 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1051 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1053 if ( !new File( repoIndexDirectory ).isAbsolute() )
1055 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1056 StringUtils.isEmpty( repoIndexDirectory )
1058 : repoIndexDirectory ).getAbsolutePath();
1061 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1063 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1064 ".indexer" ).getAbsolutePath();
1067 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1068 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1070 // for prompted authentication
1071 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1075 if ( isAuthorized( request, repository ) )
1077 mergedRepositoryContents.add( resourceFile );
1078 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1081 catch ( DavException e )
1083 // TODO: review exception handling
1085 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1086 activePrincipal, e.getMessage() );
1093 // for the current user logged in
1096 if ( servletAuth.isAuthorized( activePrincipal, repository,
1097 WebdavMethodUtil.getMethodPermission(
1098 request.getMethod() ) ) )
1100 mergedRepositoryContents.add( resourceFile );
1101 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1104 catch ( UnauthorizedException e )
1106 // TODO: review exception handling
1108 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1109 activePrincipal, e.getMessage() );
1120 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1123 ArchivaVirtualDavResource resource =
1124 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1127 // compatibility with MRM-440 to ensure browsing the repository group works ok
1128 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1130 throw new BrowserRedirectException( resource.getHref() );
1136 protected String getActivePrincipal( DavServletRequest request )
1138 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1139 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1143 * Check if the current user is authorized to access any of the repos
1146 * @param repositories
1147 * @param activePrincipal
1150 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1152 // when no repositories configured it's impossible to browse nothing !
1153 // at least make possible to see nothing :-)
1154 if ( repositories == null || repositories.isEmpty() )
1159 boolean allow = false;
1161 // if securitySession != null, it means that the user was prompted for authentication
1162 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1164 for ( String repository : repositories )
1168 if ( isAuthorized( request, repository ) )
1174 catch ( DavException e )
1182 for ( String repository : repositories )
1186 if ( servletAuth.isAuthorized( activePrincipal, repository,
1187 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1193 catch ( UnauthorizedException e )
1203 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1204 throws RepositoryMetadataException, DigesterException, IOException
1206 File outputFile = new File( outputFilename );
1207 if ( outputFile.exists() )
1209 FileUtils.deleteQuietly( outputFile );
1212 outputFile.getParentFile().mkdirs();
1213 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1215 createChecksumFile( outputFilename, digestSha1 );
1216 createChecksumFile( outputFilename, digestMd5 );
1221 private void createChecksumFile( String path, Digester digester )
1222 throws DigesterException, IOException
1224 File checksumFile = new File( path + digester.getFilenameExtension() );
1225 if ( !checksumFile.exists() )
1227 FileUtils.deleteQuietly( checksumFile );
1228 checksum.createChecksum( new File( path ), digester );
1230 else if ( !checksumFile.isFile() )
1232 log.error( "Checksum file is not a file." );
1236 private boolean isProjectReference( String requestedResource )
1240 metadataTools.toVersionedReference( requestedResource );
1243 catch ( RepositoryMetadataException re )
1249 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1250 DavServletRequest request, String groupId )
1256 HttpSession session = request.getSession();
1258 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1259 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1260 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1261 if ( temporaryGroupIndexMap == null )
1263 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1266 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1268 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1270 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getDefaultGroupIndexTtl() * 60
1273 log.debug( "tmp group index is too old so delete it" );
1274 indexMerger.cleanTemporaryGroupIndex( tmp );
1278 return tmp.getDirectory();
1282 Set<String> authzRepos = new HashSet<String>();
1283 for ( String repository : repositories )
1287 if ( servletAuth.isAuthorized( activePrincipal, repository,
1288 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1290 authzRepos.add( repository );
1291 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1294 catch ( UnauthorizedException e )
1296 // TODO: review exception handling
1298 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1302 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'", groupId,
1304 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1305 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1306 TemporaryGroupIndex temporaryGroupIndex =
1307 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1308 new Date().getTime() );
1309 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1310 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1311 temporaryGroupIndexMap );
1312 return mergedRepoDir;
1314 catch ( RepositoryAdminException e )
1316 throw new DavException( 500, e );
1318 catch ( IndexMergerException e )
1320 throw new DavException( 500, e );
1325 public void setServletAuth( ServletAuthenticator servletAuth )
1327 this.servletAuth = servletAuth;
1330 public void setHttpAuth( HttpAuthenticator httpAuth )
1332 this.httpAuth = httpAuth;
1335 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1337 this.scheduler = scheduler;
1340 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1342 this.archivaConfiguration = archivaConfiguration;
1345 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1347 this.repositoryFactory = repositoryFactory;
1350 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1352 this.repositoryRequest = repositoryRequest;
1355 public void setConnectors( RepositoryProxyConnectors connectors )
1357 this.connectors = connectors;
1360 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1362 return remoteRepositoryAdmin;
1365 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1367 this.remoteRepositoryAdmin = remoteRepositoryAdmin;