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.audit.AuditEvent;
24 import org.apache.archiva.audit.AuditListener;
25 import org.apache.archiva.audit.Auditable;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
27 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
28 import org.apache.archiva.common.utils.PathUtil;
29 import org.apache.archiva.common.utils.VersionUtil;
30 import org.apache.archiva.configuration.ArchivaConfiguration;
31 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
32 import org.apache.archiva.indexer.merger.IndexMerger;
33 import org.apache.archiva.indexer.merger.IndexMergerException;
34 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
35 import org.apache.archiva.indexer.search.RepositorySearch;
36 import org.apache.archiva.model.ArchivaRepositoryMetadata;
37 import org.apache.archiva.model.ArtifactReference;
38 import org.apache.archiva.policies.ProxyDownloadException;
39 import org.apache.archiva.proxy.RepositoryProxyConnectors;
40 import org.apache.archiva.repository.ManagedRepositoryContent;
41 import org.apache.archiva.repository.RepositoryContentFactory;
42 import org.apache.archiva.repository.RepositoryException;
43 import org.apache.archiva.repository.RepositoryNotFoundException;
44 import org.apache.archiva.repository.content.LegacyPathParser;
45 import org.apache.archiva.repository.content.RepositoryRequest;
46 import org.apache.archiva.repository.layout.LayoutException;
47 import org.apache.archiva.repository.metadata.MetadataTools;
48 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
49 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
50 import org.apache.archiva.repository.metadata.RepositoryMetadataReader;
51 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
52 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
53 import org.apache.archiva.security.ServletAuthenticator;
54 import org.apache.archiva.webdav.util.MimeTypes;
55 import org.apache.archiva.webdav.util.RepositoryPathUtil;
56 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
57 import org.apache.archiva.webdav.util.WebdavMethodUtil;
58 import org.apache.commons.io.FileUtils;
59 import org.apache.commons.io.FilenameUtils;
60 import org.apache.commons.lang.StringUtils;
61 import org.apache.jackrabbit.webdav.DavException;
62 import org.apache.jackrabbit.webdav.DavResource;
63 import org.apache.jackrabbit.webdav.DavResourceFactory;
64 import org.apache.jackrabbit.webdav.DavResourceLocator;
65 import org.apache.jackrabbit.webdav.DavServletRequest;
66 import org.apache.jackrabbit.webdav.DavServletResponse;
67 import org.apache.jackrabbit.webdav.DavSession;
68 import org.apache.jackrabbit.webdav.lock.LockManager;
69 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
70 import org.apache.maven.index.context.IndexingContext;
71 import org.apache.maven.model.DistributionManagement;
72 import org.apache.maven.model.Model;
73 import org.apache.maven.model.Relocation;
74 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
75 import org.codehaus.plexus.digest.ChecksumFile;
76 import org.codehaus.plexus.digest.Digester;
77 import org.codehaus.plexus.digest.DigesterException;
78 import org.codehaus.plexus.redback.authentication.AuthenticationException;
79 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
80 import org.codehaus.plexus.redback.authorization.AuthorizationException;
81 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
82 import org.codehaus.plexus.redback.policy.AccountLockedException;
83 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
84 import org.codehaus.plexus.redback.system.SecuritySession;
85 import org.codehaus.plexus.redback.users.User;
86 import org.codehaus.plexus.redback.users.UserManager;
87 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
88 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91 import org.springframework.context.ApplicationContext;
92 import org.springframework.stereotype.Service;
94 import javax.annotation.PostConstruct;
95 import javax.inject.Inject;
96 import javax.inject.Named;
97 import javax.servlet.http.HttpServletResponse;
98 import javax.servlet.http.HttpSession;
100 import java.io.FileNotFoundException;
101 import java.io.FileReader;
102 import java.io.IOException;
103 import java.util.ArrayList;
104 import java.util.Date;
105 import java.util.HashMap;
106 import java.util.HashSet;
107 import java.util.List;
108 import java.util.Map;
109 import java.util.Set;
114 @Service( "davResourceFactory#archiva" )
115 public class ArchivaDavResourceFactory
116 implements DavResourceFactory, Auditable
118 private static final String PROXIED_SUFFIX = " (proxied)";
120 private static final String HTTP_PUT_METHOD = "PUT";
122 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
128 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
134 private RepositoryContentFactory repositoryFactory;
139 private RepositoryRequest repositoryRequest;
145 @Named( value = "repositoryProxyConnectors#default" )
146 private RepositoryProxyConnectors connectors;
152 private MetadataTools metadataTools;
158 private MimeTypes mimeTypes;
163 private ArchivaConfiguration archivaConfiguration;
169 private ServletAuthenticator servletAuth;
175 @Named( value = "httpAuthenticator#basic" )
176 private HttpAuthenticator httpAuth;
179 private IndexMerger indexMerger;
182 private RepositorySearch repositorySearch;
185 * Lock Manager - use simple implementation from JackRabbit
187 private final LockManager lockManager = new SimpleLockManager();
192 private ChecksumFile checksum;
197 private Digester digestSha1;
202 private Digester digestMd5;
208 @Named( value = "archivaTaskScheduler#repository" )
209 private RepositoryArchivaTaskScheduler scheduler;
211 private ApplicationContext applicationContext;
214 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
215 ArchivaConfiguration archivaConfiguration )
216 throws PlexusSisuBridgeException
218 this.archivaConfiguration = archivaConfiguration;
219 this.applicationContext = applicationContext;
220 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
222 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
223 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
225 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
229 public void initialize()
234 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
235 final DavServletResponse response )
238 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
240 RepositoryGroupConfiguration repoGroupConfig =
241 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
243 String activePrincipal = getActivePrincipal( request );
245 List<String> resourcesInAbsolutePath = new ArrayList<String>();
247 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
248 DavResource resource;
249 if ( repoGroupConfig != null )
253 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
254 "Write method not allowed for repository groups." );
257 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
259 // handle browse requests for virtual repos
260 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
262 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
263 archivaLocator.getRepositoryId() );
267 // make a copy to avoid potential concurrent modifications (eg. by configuration)
268 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
270 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
271 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
272 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
277 ManagedRepositoryContent managedRepository = null;
281 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
283 catch ( RepositoryNotFoundException e )
285 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
286 "Invalid repository: " + archivaLocator.getRepositoryId() );
288 catch ( RepositoryException e )
290 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
293 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
295 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
297 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
298 resourcesInAbsolutePath.add(
299 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
302 String requestedResource = request.getRequestURI();
304 // MRM-872 : merge all available metadata
305 // merge metadata only when requested via the repo group
306 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
307 requestedResource ) ) && repoGroupConfig != null )
309 // this should only be at the project level not version level!
310 if ( isProjectReference( requestedResource ) )
312 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
313 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
315 ArchivaDavResource res = (ArchivaDavResource) resource;
317 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
319 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
321 // for MRM-872 handle checksums of the merged metadata files
322 if ( repositoryRequest.isSupportFile( requestedResource ) )
324 File metadataChecksum =
325 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
326 if ( metadataChecksum.exists() )
328 LogicalResource logicalResource =
329 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
332 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
333 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
334 archivaLocator, this, mimeTypes, auditListeners, scheduler );
339 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
341 // merge the metadata of all repos under group
342 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
343 for ( String resourceAbsPath : resourcesInAbsolutePath )
347 File metadataFile = new File( resourceAbsPath );
348 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
349 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
351 catch ( RepositoryMetadataException r )
353 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
354 "Error occurred while reading metadata file." );
360 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
362 LogicalResource logicalResource = new LogicalResource(
363 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
366 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
367 request.getRemoteAddr(), activePrincipal,
368 request.getDavSession(), archivaLocator, this, mimeTypes,
369 auditListeners, scheduler );
371 catch ( RepositoryMetadataException r )
373 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
374 "Error occurred while writing metadata file." );
376 catch ( IOException ie )
378 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
379 "Error occurred while generating checksum files." );
381 catch ( DigesterException de )
383 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
384 "Error occurred while generating checksum files." );
391 setHeaders( response, locator, resource );
393 // compatibility with MRM-440 to ensure browsing the repository works ok
394 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
396 throw new BrowserRedirectException( resource.getHref() );
398 resource.addLockManager( lockManager );
402 private DavResource processRepositoryGroup( final DavServletRequest request,
403 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
404 String activePrincipal, List<String> resourcesInAbsolutePath,
405 String repositoryGroupId )
408 DavResource resource = null;
409 List<DavException> storedExceptions = new ArrayList<DavException>();
411 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
413 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
415 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
417 // we are in the case of index file request
418 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
419 File temporaryIndexDirectory =
420 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
422 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
423 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
424 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
425 archivaLocator, this, mimeTypes, auditListeners, scheduler );
430 for ( String repositoryId : repositories )
432 ManagedRepositoryContent managedRepository;
435 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
437 catch ( RepositoryNotFoundException e )
439 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
441 catch ( RepositoryException e )
443 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
448 DavResource updatedResource =
449 processRepository( request, archivaLocator, activePrincipal, managedRepository );
450 if ( resource == null )
452 resource = updatedResource;
455 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
456 if ( logicalResource.endsWith( "/" ) )
458 logicalResource = logicalResource.substring( 1 );
460 resourcesInAbsolutePath.add(
461 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
463 catch ( DavException e )
465 storedExceptions.add( e );
469 if ( resource == null )
471 if ( !storedExceptions.isEmpty() )
474 for ( DavException e : storedExceptions )
476 if ( 401 == e.getErrorCode() )
482 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
486 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
492 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
493 String activePrincipal, ManagedRepositoryContent managedRepository )
496 DavResource resource = null;
497 if ( isAuthorized( request, managedRepository.getId() ) )
499 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
500 if ( path.startsWith( "/" ) )
502 path = path.substring( 1 );
504 LogicalResource logicalResource = new LogicalResource( path );
505 File resourceFile = new File( managedRepository.getRepoRoot(), path );
506 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
507 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
508 archivaLocator, this, mimeTypes, auditListeners, scheduler );
510 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
512 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
514 // force a resource not found
515 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
519 if ( !resource.isCollection() )
521 boolean previouslyExisted = resourceFile.exists();
523 // Attempt to fetch the resource from any defined proxy.
524 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
526 // At this point the incoming request can either be in default or
527 // legacy layout format.
530 // Perform an adjustment of the resource to the managed
531 // repository expected path.
532 String localResourcePath =
533 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
534 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
536 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
537 managedRepository.getRepository(), request.getRemoteAddr(),
538 activePrincipal, request.getDavSession(), archivaLocator, this,
539 mimeTypes, auditListeners, scheduler );
541 catch ( LayoutException e )
543 if ( !resourceFile.exists() )
545 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
551 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
554 if ( log.isDebugEnabled() )
556 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
557 + managedRepository.getId() + "' (current user '" + activePrincipal
560 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
561 logicalResource.getPath(), event, activePrincipal );
564 if ( !resourceFile.exists() )
566 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
572 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
574 String resourcePath = logicalResource.getPath();
576 // check if target repo is enabled for releases
577 // we suppose that release-artifacts can be deployed only to repos enabled for releases
578 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
579 && !repositoryRequest.isSupportFile( resourcePath ) )
581 ArtifactReference artifact = null;
584 artifact = managedRepository.toArtifactReference( resourcePath );
586 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
588 // check if artifact already exists and if artifact re-deployment to the repository is allowed
589 if ( managedRepository.hasContent( artifact )
590 && managedRepository.getRepository().isBlockRedeployments() )
592 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
593 + "' is not allowed." );
594 throw new DavException( HttpServletResponse.SC_CONFLICT,
595 "Overwriting released artifacts is not allowed." );
599 catch ( LayoutException e )
601 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
606 * Create parent directories that don't exist when writing a file This actually makes this
607 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
608 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
609 * create the collections themselves.
612 File rootDirectory = new File( managedRepository.getRepoRoot() );
613 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
615 if ( !destDir.exists() )
618 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
620 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
623 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
624 AuditEvent.CREATE_DIR, activePrincipal );
631 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
634 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
636 ManagedRepositoryContent managedRepository;
639 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
641 catch ( RepositoryNotFoundException e )
643 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
644 "Invalid repository: " + archivaLocator.getRepositoryId() );
646 catch ( RepositoryException e )
648 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
651 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
652 if ( logicalResource.startsWith( "/" ) )
654 logicalResource = logicalResource.substring( 1 );
656 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
657 DavResource resource =
658 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
659 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
661 resource.addLockManager( lockManager );
665 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
666 LogicalResource resource )
669 String path = resource.getPath();
670 if ( repositoryRequest.isSupportFile( path ) )
672 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
674 return ( proxiedFile != null );
677 // Is it a Metadata resource?
678 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
680 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
683 // Not any of the above? Then it's gotta be an artifact reference.
686 // Get the artifact reference in a layout neutral way.
687 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
689 if ( artifact != null )
691 applyServerSideRelocation( managedRepository, artifact );
693 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
695 resource.setPath( managedRepository.toPath( artifact ) );
696 if ( log.isDebugEnabled() )
698 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
699 + artifact.getVersion() + "'" );
701 return ( proxiedFile != null );
704 catch ( LayoutException e )
708 catch ( ProxyDownloadException e )
710 log.error( e.getMessage(), e );
711 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
712 "Unable to fetch artifact resource." );
718 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
719 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
722 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
723 * metadatas and serving the expected artifact.
725 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
726 throws ProxyDownloadException
728 if ( "pom".equals( artifact.getType() ) )
733 // Build the artifact POM reference
734 ArtifactReference pomReference = new ArtifactReference();
735 pomReference.setGroupId( artifact.getGroupId() );
736 pomReference.setArtifactId( artifact.getArtifactId() );
737 pomReference.setVersion( artifact.getVersion() );
738 pomReference.setType( "pom" );
740 // Get the artifact POM from proxied repositories if needed
741 connectors.fetchFromProxies( managedRepository, pomReference );
743 // Open and read the POM from the managed repo
744 File pom = managedRepository.toFile( pomReference );
753 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
754 FileReader reader = new FileReader( pom );
758 model = new MavenXpp3Reader().read( reader );
762 if ( reader != null )
768 DistributionManagement dist = model.getDistributionManagement();
771 Relocation relocation = dist.getRelocation();
772 if ( relocation != null )
774 // artifact is relocated : update the repositoryPath
775 if ( relocation.getGroupId() != null )
777 artifact.setGroupId( relocation.getGroupId() );
779 if ( relocation.getArtifactId() != null )
781 artifact.setArtifactId( relocation.getArtifactId() );
783 if ( relocation.getVersion() != null )
785 artifact.setVersion( relocation.getVersion() );
790 catch ( FileNotFoundException e )
792 // Artifact has no POM in repo : ignore
794 catch ( IOException e )
796 // Unable to read POM : ignore.
798 catch ( XmlPullParserException e )
800 // Invalid POM : ignore
806 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
809 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
810 event.setRemoteIP( remoteIP );
812 for ( AuditListener listener : auditListeners )
814 listener.auditEvent( event );
818 public void addAuditListener( AuditListener listener )
820 this.auditListeners.add( listener );
823 public void clearAuditListeners()
825 this.auditListeners.clear();
828 public void removeAuditListener( AuditListener listener )
830 this.auditListeners.remove( listener );
833 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
835 // [MRM-503] - Metadata file need Pragma:no-cache response
837 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
839 response.addHeader( "Pragma", "no-cache" );
840 response.addHeader( "Cache-Control", "no-cache" );
843 // We need to specify this so connecting wagons can work correctly
844 response.addDateHeader( "last-modified", resource.getModificationTime() );
846 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
849 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
852 if ( !( locator instanceof ArchivaDavResourceLocator ) )
854 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
855 "Locator does not implement RepositoryLocator" );
859 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
861 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
864 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
866 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
867 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
869 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
871 return archivaLocator;
874 private static class LogicalResource
878 public LogicalResource( String path )
883 public String getPath()
888 public void setPath( String path )
894 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
899 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
900 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
902 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
904 WebdavMethodUtil.getMethodPermission(
905 request.getMethod() ) );
907 catch ( AuthenticationException e )
909 // safety check for MRM-911
910 String guest = UserManager.GUEST_USERNAME;
913 if ( servletAuth.isAuthorized( guest,
914 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
915 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
920 catch ( UnauthorizedException ae )
922 throw new UnauthorizedDavException( repositoryId,
923 "You are not authenticated and authorized to access any repository." );
926 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
928 catch ( MustChangePasswordException e )
930 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
932 catch ( AccountLockedException e )
934 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
936 catch ( AuthorizationException e )
938 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
939 "Fatal Authorization Subsystem Error." );
941 catch ( UnauthorizedException e )
943 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
947 private DavResource getResource( DavServletRequest request, List<String> repositories,
948 ArchivaDavResourceLocator locator, String groupId )
951 List<File> mergedRepositoryContents = new ArrayList<File>();
952 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
953 if ( path.startsWith( "/" ) )
955 path = path.substring( 1 );
957 LogicalResource logicalResource = new LogicalResource( path );
960 // if the current user logged in has permission to any of the repositories, allow user to
961 // browse the repo group but displaying only the repositories which the user has permission to access.
962 // otherwise, prompt for authentication.
964 String activePrincipal = getActivePrincipal( request );
966 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
972 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
973 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
975 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
976 mergedRepositoryContents.add( mergedRepoDir );
980 for ( String repository : repositories )
982 ManagedRepositoryContent managedRepository = null;
986 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
988 catch ( RepositoryNotFoundException e )
990 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
991 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
993 catch ( RepositoryException e )
995 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
996 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
999 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1000 if ( resourceFile.exists() )
1002 // in case of group displaying index directory doesn't have sense !!
1003 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1004 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1006 if ( !new File( repoIndexDirectory ).isAbsolute() )
1008 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1009 StringUtils.isEmpty( repoIndexDirectory )
1011 : repoIndexDirectory ).getAbsolutePath();
1014 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1016 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1017 ".indexer" ).getAbsolutePath();
1020 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1021 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1023 // for prompted authentication
1024 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1028 if ( isAuthorized( request, repository ) )
1030 mergedRepositoryContents.add( resourceFile );
1031 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1034 catch ( DavException e )
1036 // TODO: review exception handling
1037 if ( log.isDebugEnabled() )
1039 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1040 + activePrincipal + "': " + e.getMessage() );
1047 // for the current user logged in
1050 if ( servletAuth.isAuthorized( activePrincipal, repository,
1051 WebdavMethodUtil.getMethodPermission(
1052 request.getMethod() ) ) )
1054 mergedRepositoryContents.add( resourceFile );
1055 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1058 catch ( UnauthorizedException e )
1060 // TODO: review exception handling
1061 if ( log.isDebugEnabled() )
1063 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1064 + activePrincipal + "': " + e.getMessage() );
1075 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1078 ArchivaVirtualDavResource resource =
1079 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1082 // compatibility with MRM-440 to ensure browsing the repository group works ok
1083 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1085 throw new BrowserRedirectException( resource.getHref() );
1091 protected String getActivePrincipal( DavServletRequest request )
1093 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1094 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1098 * Check if the current user is authorized to access any of the repos
1101 * @param repositories
1102 * @param activePrincipal
1105 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1107 boolean allow = false;
1109 // if securitySession != null, it means that the user was prompted for authentication
1110 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1112 for ( String repository : repositories )
1116 if ( isAuthorized( request, repository ) )
1122 catch ( DavException e )
1130 for ( String repository : repositories )
1134 if ( servletAuth.isAuthorized( activePrincipal, repository,
1135 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1141 catch ( UnauthorizedException e )
1151 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1152 throws RepositoryMetadataException, DigesterException, IOException
1154 File outputFile = new File( outputFilename );
1155 if ( outputFile.exists() )
1157 FileUtils.deleteQuietly( outputFile );
1160 outputFile.getParentFile().mkdirs();
1161 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1163 createChecksumFile( outputFilename, digestSha1 );
1164 createChecksumFile( outputFilename, digestMd5 );
1169 private void createChecksumFile( String path, Digester digester )
1170 throws DigesterException, IOException
1172 File checksumFile = new File( path + digester.getFilenameExtension() );
1173 if ( !checksumFile.exists() )
1175 FileUtils.deleteQuietly( checksumFile );
1176 checksum.createChecksum( new File( path ), digester );
1178 else if ( !checksumFile.isFile() )
1180 log.error( "Checksum file is not a file." );
1184 private boolean isProjectReference( String requestedResource )
1188 metadataTools.toVersionedReference( requestedResource );
1191 catch ( RepositoryMetadataException re )
1197 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1198 DavServletRequest request, String groupId )
1204 HttpSession session = request.getSession();
1206 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1207 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1208 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1209 if ( temporaryGroupIndexMap == null )
1211 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1214 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1216 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1218 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( IndexMerger.DEFAULT_GROUP_INDEX_TTL * 60
1221 log.debug( "tmp group index is too old so delete it" );
1222 indexMerger.cleanTemporaryGroupIndex( tmp );
1226 return tmp.getDirectory();
1230 Set<String> authzRepos = new HashSet<String>();
1231 for ( String repository : repositories )
1235 if ( servletAuth.isAuthorized( activePrincipal, repository,
1236 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1238 authzRepos.add( repository );
1239 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1242 catch ( UnauthorizedException e )
1244 // TODO: review exception handling
1245 if ( log.isDebugEnabled() )
1247 log.debug( "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1252 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1253 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1254 TemporaryGroupIndex temporaryGroupIndex =
1255 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1256 new Date().getTime() );
1257 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1258 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1259 temporaryGroupIndexMap );
1260 return mergedRepoDir;
1262 catch ( RepositoryAdminException e )
1264 throw new DavException( 500, e );
1266 catch ( IndexMergerException e )
1268 throw new DavException( 500, e );
1273 public void setServletAuth( ServletAuthenticator servletAuth )
1275 this.servletAuth = servletAuth;
1278 public void setHttpAuth( HttpAuthenticator httpAuth )
1280 this.httpAuth = httpAuth;
1283 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1285 this.scheduler = scheduler;
1288 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1290 this.archivaConfiguration = archivaConfiguration;
1293 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1295 this.repositoryFactory = repositoryFactory;
1298 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1300 this.repositoryRequest = repositoryRequest;
1303 public void setConnectors( RepositoryProxyConnectors connectors )
1305 this.connectors = connectors;