1 package org.apache.maven.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.audit.AuditEvent;
23 import org.apache.archiva.audit.AuditListener;
24 import org.apache.archiva.audit.Auditable;
25 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
27 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
28 import org.apache.commons.io.FileUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.jackrabbit.webdav.DavException;
31 import org.apache.jackrabbit.webdav.DavResource;
32 import org.apache.jackrabbit.webdav.DavResourceFactory;
33 import org.apache.jackrabbit.webdav.DavResourceLocator;
34 import org.apache.jackrabbit.webdav.DavServletRequest;
35 import org.apache.jackrabbit.webdav.DavServletResponse;
36 import org.apache.jackrabbit.webdav.DavSession;
37 import org.apache.jackrabbit.webdav.lock.LockManager;
38 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
39 import org.apache.maven.archiva.common.utils.PathUtil;
40 import org.apache.maven.archiva.common.utils.VersionUtil;
41 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
42 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
43 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
44 import org.apache.maven.archiva.model.ArtifactReference;
45 import org.apache.maven.archiva.policies.ProxyDownloadException;
46 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
47 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
48 import org.apache.maven.archiva.repository.RepositoryContentFactory;
49 import org.apache.maven.archiva.repository.RepositoryException;
50 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
51 import org.apache.maven.archiva.repository.content.LegacyPathParser;
52 import org.apache.maven.archiva.repository.content.RepositoryRequest;
53 import org.apache.maven.archiva.repository.layout.LayoutException;
54 import org.apache.maven.archiva.repository.metadata.MetadataTools;
55 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
56 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
57 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
58 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
59 import org.apache.maven.archiva.security.ServletAuthenticator;
60 import org.apache.maven.archiva.webdav.util.MimeTypes;
61 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
62 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
63 import org.apache.maven.model.DistributionManagement;
64 import org.apache.maven.model.Model;
65 import org.apache.maven.model.Relocation;
66 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
67 import org.codehaus.plexus.digest.ChecksumFile;
68 import org.codehaus.plexus.digest.Digester;
69 import org.codehaus.plexus.digest.DigesterException;
70 import org.codehaus.plexus.redback.authentication.AuthenticationException;
71 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
72 import org.codehaus.plexus.redback.authorization.AuthorizationException;
73 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
74 import org.codehaus.plexus.redback.policy.AccountLockedException;
75 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
76 import org.codehaus.plexus.redback.system.SecuritySession;
77 import org.codehaus.plexus.redback.users.User;
78 import org.codehaus.plexus.redback.users.UserManager;
79 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
80 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.springframework.context.ApplicationContext;
84 import org.springframework.stereotype.Service;
86 import javax.annotation.PostConstruct;
87 import javax.inject.Inject;
88 import javax.inject.Named;
89 import javax.servlet.http.HttpServletResponse;
91 import java.io.FileNotFoundException;
92 import java.io.FileReader;
93 import java.io.IOException;
94 import java.util.ArrayList;
95 import java.util.List;
98 * plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
100 @Service( "davResourceFactory#archiva" )
101 public class ArchivaDavResourceFactory
102 implements DavResourceFactory, Auditable
104 private static final String PROXIED_SUFFIX = " (proxied)";
106 private static final String HTTP_PUT_METHOD = "PUT";
108 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
111 * plexus.requirement role="org.apache.archiva.audit.AuditListener"
113 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
119 private RepositoryContentFactory repositoryFactory;
124 private RepositoryRequest repositoryRequest;
127 * plexus.requirement role-hint="default"
130 @Named( value = "repositoryProxyConnectors#default" )
131 private RepositoryProxyConnectors connectors;
137 private MetadataTools metadataTools;
143 private MimeTypes mimeTypes;
149 private ArchivaConfiguration archivaConfiguration;
155 private ServletAuthenticator servletAuth;
158 * plexus.requirement role-hint="basic"
161 @Named( value = "httpAuthenticator#basic" )
162 private HttpAuthenticator httpAuth;
165 * Lock Manager - use simple implementation from JackRabbit
167 private final LockManager lockManager = new SimpleLockManager();
173 private ChecksumFile checksum;
176 * plexus.requirement role-hint="sha1"
179 //Named( value = "digester#sha1" )
180 private Digester digestSha1;
183 * plexus.requirement role-hint="md5";
186 //Named( value = "digester#md5" )
187 private Digester digestMd5;
190 * plexus.requirement role="org.apache.archiva.scheduler.ArchivaTaskScheduler" role-hint="repository"
193 @Named( value = "archivaTaskScheduler#repository" )
194 private RepositoryArchivaTaskScheduler scheduler;
197 private ApplicationContext applicationContext;
200 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
201 ArchivaConfiguration archivaConfiguration )
202 throws PlexusSisuBridgeException
204 this.archivaConfiguration = archivaConfiguration;
205 this.applicationContext = applicationContext;
206 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
208 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
209 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
211 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
212 this.auditListeners =
213 new ArrayList<AuditListener>( applicationContext.getBeansOfType( AuditListener.class ).values() );
217 public void initialize()
223 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
224 final DavServletResponse response )
227 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
229 RepositoryGroupConfiguration repoGroupConfig =
230 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
232 String activePrincipal = getActivePrincipal( request );
234 List<String> resourcesInAbsolutePath = new ArrayList<String>();
236 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
237 DavResource resource;
238 if ( repoGroupConfig != null )
242 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
243 "Write method not allowed for repository groups." );
246 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
248 // handle browse requests for virtual repos
249 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
251 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
255 // make a copy to avoid potential concurrent modifications (eg. by configuration)
256 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
258 ArrayList<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
259 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
260 resourcesInAbsolutePath );
265 ManagedRepositoryContent managedRepository = null;
269 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
271 catch ( RepositoryNotFoundException e )
273 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
274 "Invalid repository: " + archivaLocator.getRepositoryId() );
276 catch ( RepositoryException e )
278 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
281 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
283 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
285 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
286 resourcesInAbsolutePath.add(
287 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
290 String requestedResource = request.getRequestURI();
292 // MRM-872 : merge all available metadata
293 // merge metadata only when requested via the repo group
294 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
295 requestedResource ) ) && repoGroupConfig != null )
297 // this should only be at the project level not version level!
298 if ( isProjectReference( requestedResource ) )
300 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
301 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
303 ArchivaDavResource res = (ArchivaDavResource) resource;
305 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
307 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
309 // for MRM-872 handle checksums of the merged metadata files
310 if ( repositoryRequest.isSupportFile( requestedResource ) )
312 File metadataChecksum =
313 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
314 if ( metadataChecksum.exists() )
316 LogicalResource logicalResource =
317 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
320 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
321 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
322 archivaLocator, this, mimeTypes, auditListeners, scheduler );
327 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
329 // merge the metadata of all repos under group
330 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
331 for ( String resourceAbsPath : resourcesInAbsolutePath )
335 File metadataFile = new File( resourceAbsPath );
336 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
337 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
339 catch ( RepositoryMetadataException r )
341 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
342 "Error occurred while reading metadata file." );
348 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
350 LogicalResource logicalResource = new LogicalResource(
351 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
354 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
355 request.getRemoteAddr(), activePrincipal,
356 request.getDavSession(), archivaLocator, this, mimeTypes,
357 auditListeners, scheduler );
359 catch ( RepositoryMetadataException r )
361 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
362 "Error occurred while writing metadata file." );
364 catch ( IOException ie )
366 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
367 "Error occurred while generating checksum files." );
369 catch ( DigesterException de )
371 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
372 "Error occurred while generating checksum files." );
379 setHeaders( response, locator, resource );
381 // compatibility with MRM-440 to ensure browsing the repository works ok
382 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
384 throw new BrowserRedirectException( resource.getHref() );
386 resource.addLockManager( lockManager );
390 private DavResource processRepositoryGroup( final DavServletRequest request,
391 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
392 String activePrincipal, List<String> resourcesInAbsolutePath )
395 DavResource resource = null;
396 List<DavException> storedExceptions = new ArrayList<DavException>();
398 for ( String repositoryId : repositories )
400 ManagedRepositoryContent managedRepository;
403 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
405 catch ( RepositoryNotFoundException e )
407 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
409 catch ( RepositoryException e )
411 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
416 DavResource updatedResource =
417 processRepository( request, archivaLocator, activePrincipal, managedRepository );
418 if ( resource == null )
420 resource = updatedResource;
423 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
424 if ( logicalResource.endsWith( "/" ) )
426 logicalResource = logicalResource.substring( 1 );
428 resourcesInAbsolutePath.add(
429 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
431 catch ( DavException e )
433 storedExceptions.add( e );
437 if ( resource == null )
439 if ( !storedExceptions.isEmpty() )
442 for ( DavException e : storedExceptions )
444 if ( 401 == e.getErrorCode() )
450 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
454 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
460 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
461 String activePrincipal, ManagedRepositoryContent managedRepository )
464 DavResource resource = null;
465 if ( isAuthorized( request, managedRepository.getId() ) )
467 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
468 if ( path.startsWith( "/" ) )
470 path = path.substring( 1 );
472 LogicalResource logicalResource = new LogicalResource( path );
473 File resourceFile = new File( managedRepository.getRepoRoot(), path );
474 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
475 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
476 archivaLocator, this, mimeTypes, auditListeners, scheduler );
478 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
480 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
482 // force a resource not found
483 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
487 if ( !resource.isCollection() )
489 boolean previouslyExisted = resourceFile.exists();
491 // Attempt to fetch the resource from any defined proxy.
492 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
494 // At this point the incoming request can either be in default or
495 // legacy layout format.
498 // Perform an adjustment of the resource to the managed
499 // repository expected path.
500 String localResourcePath =
501 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
502 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
504 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
505 managedRepository.getRepository(), request.getRemoteAddr(),
506 activePrincipal, request.getDavSession(), archivaLocator, this,
507 mimeTypes, auditListeners, scheduler );
509 catch ( LayoutException e )
511 if ( !resourceFile.exists() )
513 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
519 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
522 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
523 + managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
525 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
526 logicalResource.getPath(), event, activePrincipal );
529 if ( !resourceFile.exists() )
531 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
537 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
539 String resourcePath = logicalResource.getPath();
541 // check if target repo is enabled for releases
542 // we suppose that release-artifacts can be deployed only to repos enabled for releases
543 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
544 && !repositoryRequest.isSupportFile( resourcePath ) )
546 ArtifactReference artifact = null;
549 artifact = managedRepository.toArtifactReference( resourcePath );
551 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
553 // check if artifact already exists and if artifact re-deployment to the repository is allowed
554 if ( managedRepository.hasContent( artifact )
555 && managedRepository.getRepository().isBlockRedeployments() )
557 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
558 + "' is not allowed." );
559 throw new DavException( HttpServletResponse.SC_CONFLICT,
560 "Overwriting released artifacts is not allowed." );
564 catch ( LayoutException e )
566 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
571 * Create parent directories that don't exist when writing a file This actually makes this
572 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
573 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
574 * create the collections themselves.
577 File rootDirectory = new File( managedRepository.getRepoRoot() );
578 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
580 if ( !destDir.exists() )
583 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
585 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
588 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
589 AuditEvent.CREATE_DIR, activePrincipal );
596 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
599 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
601 ManagedRepositoryContent managedRepository;
604 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
606 catch ( RepositoryNotFoundException e )
608 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
609 "Invalid repository: " + archivaLocator.getRepositoryId() );
611 catch ( RepositoryException e )
613 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
616 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
617 if ( logicalResource.startsWith( "/" ) )
619 logicalResource = logicalResource.substring( 1 );
621 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
622 DavResource resource =
623 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
624 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
626 resource.addLockManager( lockManager );
630 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
631 LogicalResource resource )
634 String path = resource.getPath();
635 if ( repositoryRequest.isSupportFile( path ) )
637 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
639 return ( proxiedFile != null );
642 // Is it a Metadata resource?
643 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
645 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
648 // Not any of the above? Then it's gotta be an artifact reference.
651 // Get the artifact reference in a layout neutral way.
652 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
654 if ( artifact != null )
656 applyServerSideRelocation( managedRepository, artifact );
658 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
660 resource.setPath( managedRepository.toPath( artifact ) );
662 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
663 + artifact.getVersion() + "'" );
665 return ( proxiedFile != null );
668 catch ( LayoutException e )
672 catch ( ProxyDownloadException e )
674 log.error( e.getMessage(), e );
675 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
676 "Unable to fetch artifact resource." );
682 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
683 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
686 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
687 * metadatas and serving the expected artifact.
689 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
690 throws ProxyDownloadException
692 if ( "pom".equals( artifact.getType() ) )
697 // Build the artifact POM reference
698 ArtifactReference pomReference = new ArtifactReference();
699 pomReference.setGroupId( artifact.getGroupId() );
700 pomReference.setArtifactId( artifact.getArtifactId() );
701 pomReference.setVersion( artifact.getVersion() );
702 pomReference.setType( "pom" );
704 // Get the artifact POM from proxied repositories if needed
705 connectors.fetchFromProxies( managedRepository, pomReference );
707 // Open and read the POM from the managed repo
708 File pom = managedRepository.toFile( pomReference );
717 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
718 FileReader reader = new FileReader( pom );
722 model = new MavenXpp3Reader().read( reader );
726 if ( reader != null )
732 DistributionManagement dist = model.getDistributionManagement();
735 Relocation relocation = dist.getRelocation();
736 if ( relocation != null )
738 // artifact is relocated : update the repositoryPath
739 if ( relocation.getGroupId() != null )
741 artifact.setGroupId( relocation.getGroupId() );
743 if ( relocation.getArtifactId() != null )
745 artifact.setArtifactId( relocation.getArtifactId() );
747 if ( relocation.getVersion() != null )
749 artifact.setVersion( relocation.getVersion() );
754 catch ( FileNotFoundException e )
756 // Artifact has no POM in repo : ignore
758 catch ( IOException e )
760 // Unable to read POM : ignore.
762 catch ( XmlPullParserException e )
764 // Invalid POM : ignore
770 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
773 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
774 event.setRemoteIP( remoteIP );
776 for ( AuditListener listener : auditListeners )
778 listener.auditEvent( event );
782 public void addAuditListener( AuditListener listener )
784 this.auditListeners.add( listener );
787 public void clearAuditListeners()
789 this.auditListeners.clear();
792 public void removeAuditListener( AuditListener listener )
794 this.auditListeners.remove( listener );
797 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
799 // [MRM-503] - Metadata file need Pragma:no-cache response
801 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
803 response.addHeader( "Pragma", "no-cache" );
804 response.addHeader( "Cache-Control", "no-cache" );
807 // We need to specify this so connecting wagons can work correctly
808 response.addDateHeader( "last-modified", resource.getModificationTime() );
810 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
813 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
816 if ( !( locator instanceof ArchivaDavResourceLocator ) )
818 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
819 "Locator does not implement RepositoryLocator" );
823 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
825 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
828 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
830 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
831 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
833 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
835 return archivaLocator;
838 private static class LogicalResource
842 public LogicalResource( String path )
847 public String getPath()
852 public void setPath( String path )
858 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
863 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
864 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
866 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
868 WebdavMethodUtil.getMethodPermission(
869 request.getMethod() ) );
871 catch ( AuthenticationException e )
873 // safety check for MRM-911
874 String guest = UserManager.GUEST_USERNAME;
877 if ( servletAuth.isAuthorized( guest,
878 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
879 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
884 catch ( UnauthorizedException ae )
886 throw new UnauthorizedDavException( repositoryId,
887 "You are not authenticated and authorized to access any repository." );
890 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
892 catch ( MustChangePasswordException e )
894 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
896 catch ( AccountLockedException e )
898 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
900 catch ( AuthorizationException e )
902 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
903 "Fatal Authorization Subsystem Error." );
905 catch ( UnauthorizedException e )
907 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
911 private DavResource getResource( DavServletRequest request, List<String> repositories,
912 ArchivaDavResourceLocator locator )
915 List<File> mergedRepositoryContents = new ArrayList<File>();
916 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
917 if ( path.startsWith( "/" ) )
919 path = path.substring( 1 );
921 LogicalResource logicalResource = new LogicalResource( path );
924 // if the current user logged in has permission to any of the repositories, allow user to
925 // browse the repo group but displaying only the repositories which the user has permission to access.
926 // otherwise, prompt for authentication.
928 String activePrincipal = getActivePrincipal( request );
930 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
934 for ( String repository : repositories )
936 ManagedRepositoryContent managedRepository = null;
940 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
942 catch ( RepositoryNotFoundException e )
944 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
945 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
947 catch ( RepositoryException e )
949 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
950 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
953 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
954 if ( resourceFile.exists() )
956 // for prompted authentication
957 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
961 if ( isAuthorized( request, repository ) )
963 mergedRepositoryContents.add( resourceFile );
964 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
967 catch ( DavException e )
969 // TODO: review exception handling
971 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
977 // for the current user logged in
980 if ( servletAuth.isAuthorized( activePrincipal, repository,
981 WebdavMethodUtil.getMethodPermission(
982 request.getMethod() ) ) )
984 mergedRepositoryContents.add( resourceFile );
985 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
988 catch ( UnauthorizedException e )
990 // TODO: review exception handling
992 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
1001 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1004 ArchivaVirtualDavResource resource =
1005 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1008 // compatibility with MRM-440 to ensure browsing the repository group works ok
1009 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1011 throw new BrowserRedirectException( resource.getHref() );
1017 protected String getActivePrincipal( DavServletRequest request )
1019 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1020 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1024 * Check if the current user is authorized to access any of the repos
1027 * @param repositories
1028 * @param activePrincipal
1031 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1033 boolean allow = false;
1035 // if securitySession != null, it means that the user was prompted for authentication
1036 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1038 for ( String repository : repositories )
1042 if ( isAuthorized( request, repository ) )
1048 catch ( DavException e )
1056 for ( String repository : repositories )
1060 if ( servletAuth.isAuthorized( activePrincipal, repository,
1061 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1067 catch ( UnauthorizedException e )
1077 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1078 throws RepositoryMetadataException, DigesterException, IOException
1080 File outputFile = new File( outputFilename );
1081 if ( outputFile.exists() )
1083 FileUtils.deleteQuietly( outputFile );
1086 outputFile.getParentFile().mkdirs();
1087 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1089 createChecksumFile( outputFilename, digestSha1 );
1090 createChecksumFile( outputFilename, digestMd5 );
1095 private void createChecksumFile( String path, Digester digester )
1096 throws DigesterException, IOException
1098 File checksumFile = new File( path + digester.getFilenameExtension() );
1099 if ( !checksumFile.exists() )
1101 FileUtils.deleteQuietly( checksumFile );
1102 checksum.createChecksum( new File( path ), digester );
1104 else if ( !checksumFile.isFile() )
1106 log.error( "Checksum file is not a file." );
1110 private boolean isProjectReference( String requestedResource )
1114 metadataTools.toVersionedReference( requestedResource );
1117 catch ( RepositoryMetadataException re )
1123 public void setServletAuth( ServletAuthenticator servletAuth )
1125 this.servletAuth = servletAuth;
1128 public void setHttpAuth( HttpAuthenticator httpAuth )
1130 this.httpAuth = httpAuth;
1133 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1135 this.scheduler = scheduler;
1138 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1140 this.archivaConfiguration = archivaConfiguration;
1143 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1145 this.repositoryFactory = repositoryFactory;
1148 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1150 this.repositoryRequest = repositoryRequest;
1153 public void setConnectors( RepositoryProxyConnectors connectors )
1155 this.connectors = connectors;