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.search.RepositorySearch;
35 import org.apache.archiva.model.ArchivaRepositoryMetadata;
36 import org.apache.archiva.model.ArtifactReference;
37 import org.apache.archiva.policies.ProxyDownloadException;
38 import org.apache.archiva.proxy.RepositoryProxyConnectors;
39 import org.apache.archiva.repository.ManagedRepositoryContent;
40 import org.apache.archiva.repository.RepositoryContentFactory;
41 import org.apache.archiva.repository.RepositoryException;
42 import org.apache.archiva.repository.RepositoryNotFoundException;
43 import org.apache.archiva.repository.content.LegacyPathParser;
44 import org.apache.archiva.repository.content.RepositoryRequest;
45 import org.apache.archiva.repository.layout.LayoutException;
46 import org.apache.archiva.repository.metadata.MetadataTools;
47 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
48 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
49 import org.apache.archiva.repository.metadata.RepositoryMetadataReader;
50 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
51 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
52 import org.apache.archiva.security.ServletAuthenticator;
53 import org.apache.archiva.webdav.util.MimeTypes;
54 import org.apache.archiva.webdav.util.RepositoryPathUtil;
55 import org.apache.archiva.webdav.util.WebdavMethodUtil;
56 import org.apache.commons.io.FileUtils;
57 import org.apache.commons.io.FilenameUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.jackrabbit.webdav.DavException;
60 import org.apache.jackrabbit.webdav.DavResource;
61 import org.apache.jackrabbit.webdav.DavResourceFactory;
62 import org.apache.jackrabbit.webdav.DavResourceLocator;
63 import org.apache.jackrabbit.webdav.DavServletRequest;
64 import org.apache.jackrabbit.webdav.DavServletResponse;
65 import org.apache.jackrabbit.webdav.DavSession;
66 import org.apache.jackrabbit.webdav.lock.LockManager;
67 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.Relocation;
71 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
72 import org.codehaus.plexus.digest.ChecksumFile;
73 import org.codehaus.plexus.digest.Digester;
74 import org.codehaus.plexus.digest.DigesterException;
75 import org.codehaus.plexus.redback.authentication.AuthenticationException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
77 import org.codehaus.plexus.redback.authorization.AuthorizationException;
78 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
79 import org.codehaus.plexus.redback.policy.AccountLockedException;
80 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
81 import org.codehaus.plexus.redback.system.SecuritySession;
82 import org.codehaus.plexus.redback.users.User;
83 import org.codehaus.plexus.redback.users.UserManager;
84 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
85 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.springframework.context.ApplicationContext;
89 import org.springframework.stereotype.Service;
91 import javax.annotation.PostConstruct;
92 import javax.inject.Inject;
93 import javax.inject.Named;
94 import javax.servlet.http.HttpServletResponse;
95 import javax.servlet.http.HttpSession;
97 import java.io.FileNotFoundException;
98 import java.io.FileReader;
99 import java.io.IOException;
100 import java.util.ArrayList;
101 import java.util.HashSet;
102 import java.util.List;
103 import java.util.Set;
108 @Service( "davResourceFactory#archiva" )
109 public class ArchivaDavResourceFactory
110 implements DavResourceFactory, Auditable
112 private static final String PROXIED_SUFFIX = " (proxied)";
114 private static final String HTTP_PUT_METHOD = "PUT";
116 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
122 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
128 private RepositoryContentFactory repositoryFactory;
133 private RepositoryRequest repositoryRequest;
139 @Named( value = "repositoryProxyConnectors#default" )
140 private RepositoryProxyConnectors connectors;
146 private MetadataTools metadataTools;
152 private MimeTypes mimeTypes;
157 private ArchivaConfiguration archivaConfiguration;
163 private ServletAuthenticator servletAuth;
169 @Named( value = "httpAuthenticator#basic" )
170 private HttpAuthenticator httpAuth;
173 private IndexMerger indexMerger;
176 private RepositorySearch repositorySearch;
179 * Lock Manager - use simple implementation from JackRabbit
181 private final LockManager lockManager = new SimpleLockManager();
186 private ChecksumFile checksum;
191 private Digester digestSha1;
196 private Digester digestMd5;
202 @Named( value = "archivaTaskScheduler#repository" )
203 private RepositoryArchivaTaskScheduler scheduler;
205 private ApplicationContext applicationContext;
208 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
209 ArchivaConfiguration archivaConfiguration )
210 throws PlexusSisuBridgeException
212 this.archivaConfiguration = archivaConfiguration;
213 this.applicationContext = applicationContext;
214 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
216 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
217 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
219 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
223 public void initialize()
228 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
229 final DavServletResponse response )
232 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
234 RepositoryGroupConfiguration repoGroupConfig =
235 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
237 String activePrincipal = getActivePrincipal( request );
239 List<String> resourcesInAbsolutePath = new ArrayList<String>();
241 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
242 DavResource resource;
243 if ( repoGroupConfig != null )
247 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
248 "Write method not allowed for repository groups." );
251 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
253 // handle browse requests for virtual repos
254 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
256 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
260 // make a copy to avoid potential concurrent modifications (eg. by configuration)
261 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
263 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
264 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
265 resourcesInAbsolutePath );
270 ManagedRepositoryContent managedRepository = null;
274 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
276 catch ( RepositoryNotFoundException e )
278 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
279 "Invalid repository: " + archivaLocator.getRepositoryId() );
281 catch ( RepositoryException e )
283 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
286 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
288 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
290 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
291 resourcesInAbsolutePath.add(
292 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
295 String requestedResource = request.getRequestURI();
297 // MRM-872 : merge all available metadata
298 // merge metadata only when requested via the repo group
299 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
300 requestedResource ) ) && repoGroupConfig != null )
302 // this should only be at the project level not version level!
303 if ( isProjectReference( requestedResource ) )
305 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
306 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
308 ArchivaDavResource res = (ArchivaDavResource) resource;
310 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
312 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
314 // for MRM-872 handle checksums of the merged metadata files
315 if ( repositoryRequest.isSupportFile( requestedResource ) )
317 File metadataChecksum =
318 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
319 if ( metadataChecksum.exists() )
321 LogicalResource logicalResource =
322 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
325 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
326 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
327 archivaLocator, this, mimeTypes, auditListeners, scheduler );
332 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
334 // merge the metadata of all repos under group
335 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
336 for ( String resourceAbsPath : resourcesInAbsolutePath )
340 File metadataFile = new File( resourceAbsPath );
341 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
342 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
344 catch ( RepositoryMetadataException r )
346 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
347 "Error occurred while reading metadata file." );
353 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
355 LogicalResource logicalResource = new LogicalResource(
356 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
359 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
360 request.getRemoteAddr(), activePrincipal,
361 request.getDavSession(), archivaLocator, this, mimeTypes,
362 auditListeners, scheduler );
364 catch ( RepositoryMetadataException r )
366 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
367 "Error occurred while writing metadata file." );
369 catch ( IOException ie )
371 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
372 "Error occurred while generating checksum files." );
374 catch ( DigesterException de )
376 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
377 "Error occurred while generating checksum files." );
384 setHeaders( response, locator, resource );
386 // compatibility with MRM-440 to ensure browsing the repository works ok
387 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
389 throw new BrowserRedirectException( resource.getHref() );
391 resource.addLockManager( lockManager );
395 private DavResource processRepositoryGroup( final DavServletRequest request,
396 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
397 String activePrincipal, List<String> resourcesInAbsolutePath )
400 DavResource resource = null;
401 List<DavException> storedExceptions = new ArrayList<DavException>();
403 for ( String repositoryId : repositories )
405 ManagedRepositoryContent managedRepository;
408 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
410 catch ( RepositoryNotFoundException e )
412 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
414 catch ( RepositoryException e )
416 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
421 DavResource updatedResource =
422 processRepository( request, archivaLocator, activePrincipal, managedRepository );
423 if ( resource == null )
425 resource = updatedResource;
428 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
429 if ( logicalResource.endsWith( "/" ) )
431 logicalResource = logicalResource.substring( 1 );
433 resourcesInAbsolutePath.add(
434 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
436 catch ( DavException e )
438 storedExceptions.add( e );
442 if ( resource == null )
444 if ( !storedExceptions.isEmpty() )
447 for ( DavException e : storedExceptions )
449 if ( 401 == e.getErrorCode() )
455 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
459 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
465 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
466 String activePrincipal, ManagedRepositoryContent managedRepository )
469 DavResource resource = null;
470 if ( isAuthorized( request, managedRepository.getId() ) )
472 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
473 if ( path.startsWith( "/" ) )
475 path = path.substring( 1 );
477 LogicalResource logicalResource = new LogicalResource( path );
478 File resourceFile = new File( managedRepository.getRepoRoot(), path );
479 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
480 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
481 archivaLocator, this, mimeTypes, auditListeners, scheduler );
483 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
485 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
487 // force a resource not found
488 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
492 if ( !resource.isCollection() )
494 boolean previouslyExisted = resourceFile.exists();
496 // Attempt to fetch the resource from any defined proxy.
497 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
499 // At this point the incoming request can either be in default or
500 // legacy layout format.
503 // Perform an adjustment of the resource to the managed
504 // repository expected path.
505 String localResourcePath =
506 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
507 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
509 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
510 managedRepository.getRepository(), request.getRemoteAddr(),
511 activePrincipal, request.getDavSession(), archivaLocator, this,
512 mimeTypes, auditListeners, scheduler );
514 catch ( LayoutException e )
516 if ( !resourceFile.exists() )
518 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
524 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
527 if ( log.isDebugEnabled() )
529 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
530 + managedRepository.getId() + "' (current user '" + activePrincipal
533 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
534 logicalResource.getPath(), event, activePrincipal );
537 if ( !resourceFile.exists() )
539 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
545 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
547 String resourcePath = logicalResource.getPath();
549 // check if target repo is enabled for releases
550 // we suppose that release-artifacts can be deployed only to repos enabled for releases
551 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
552 && !repositoryRequest.isSupportFile( resourcePath ) )
554 ArtifactReference artifact = null;
557 artifact = managedRepository.toArtifactReference( resourcePath );
559 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
561 // check if artifact already exists and if artifact re-deployment to the repository is allowed
562 if ( managedRepository.hasContent( artifact )
563 && managedRepository.getRepository().isBlockRedeployments() )
565 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
566 + "' is not allowed." );
567 throw new DavException( HttpServletResponse.SC_CONFLICT,
568 "Overwriting released artifacts is not allowed." );
572 catch ( LayoutException e )
574 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
579 * Create parent directories that don't exist when writing a file This actually makes this
580 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
581 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
582 * create the collections themselves.
585 File rootDirectory = new File( managedRepository.getRepoRoot() );
586 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
588 if ( !destDir.exists() )
591 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
593 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
596 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
597 AuditEvent.CREATE_DIR, activePrincipal );
604 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
607 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
609 ManagedRepositoryContent managedRepository;
612 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
614 catch ( RepositoryNotFoundException e )
616 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
617 "Invalid repository: " + archivaLocator.getRepositoryId() );
619 catch ( RepositoryException e )
621 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
624 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
625 if ( logicalResource.startsWith( "/" ) )
627 logicalResource = logicalResource.substring( 1 );
629 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
630 DavResource resource =
631 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
632 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
634 resource.addLockManager( lockManager );
638 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
639 LogicalResource resource )
642 String path = resource.getPath();
643 if ( repositoryRequest.isSupportFile( path ) )
645 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
647 return ( proxiedFile != null );
650 // Is it a Metadata resource?
651 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
653 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
656 // Not any of the above? Then it's gotta be an artifact reference.
659 // Get the artifact reference in a layout neutral way.
660 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
662 if ( artifact != null )
664 applyServerSideRelocation( managedRepository, artifact );
666 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
668 resource.setPath( managedRepository.toPath( artifact ) );
669 if ( log.isDebugEnabled() )
671 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
672 + artifact.getVersion() + "'" );
674 return ( proxiedFile != null );
677 catch ( LayoutException e )
681 catch ( ProxyDownloadException e )
683 log.error( e.getMessage(), e );
684 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
685 "Unable to fetch artifact resource." );
691 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
692 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
695 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
696 * metadatas and serving the expected artifact.
698 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
699 throws ProxyDownloadException
701 if ( "pom".equals( artifact.getType() ) )
706 // Build the artifact POM reference
707 ArtifactReference pomReference = new ArtifactReference();
708 pomReference.setGroupId( artifact.getGroupId() );
709 pomReference.setArtifactId( artifact.getArtifactId() );
710 pomReference.setVersion( artifact.getVersion() );
711 pomReference.setType( "pom" );
713 // Get the artifact POM from proxied repositories if needed
714 connectors.fetchFromProxies( managedRepository, pomReference );
716 // Open and read the POM from the managed repo
717 File pom = managedRepository.toFile( pomReference );
726 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
727 FileReader reader = new FileReader( pom );
731 model = new MavenXpp3Reader().read( reader );
735 if ( reader != null )
741 DistributionManagement dist = model.getDistributionManagement();
744 Relocation relocation = dist.getRelocation();
745 if ( relocation != null )
747 // artifact is relocated : update the repositoryPath
748 if ( relocation.getGroupId() != null )
750 artifact.setGroupId( relocation.getGroupId() );
752 if ( relocation.getArtifactId() != null )
754 artifact.setArtifactId( relocation.getArtifactId() );
756 if ( relocation.getVersion() != null )
758 artifact.setVersion( relocation.getVersion() );
763 catch ( FileNotFoundException e )
765 // Artifact has no POM in repo : ignore
767 catch ( IOException e )
769 // Unable to read POM : ignore.
771 catch ( XmlPullParserException e )
773 // Invalid POM : ignore
779 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
782 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
783 event.setRemoteIP( remoteIP );
785 for ( AuditListener listener : auditListeners )
787 listener.auditEvent( event );
791 public void addAuditListener( AuditListener listener )
793 this.auditListeners.add( listener );
796 public void clearAuditListeners()
798 this.auditListeners.clear();
801 public void removeAuditListener( AuditListener listener )
803 this.auditListeners.remove( listener );
806 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
808 // [MRM-503] - Metadata file need Pragma:no-cache response
810 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
812 response.addHeader( "Pragma", "no-cache" );
813 response.addHeader( "Cache-Control", "no-cache" );
816 // We need to specify this so connecting wagons can work correctly
817 response.addDateHeader( "last-modified", resource.getModificationTime() );
819 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
822 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
825 if ( !( locator instanceof ArchivaDavResourceLocator ) )
827 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
828 "Locator does not implement RepositoryLocator" );
832 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
834 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
837 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
839 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
840 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
842 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
844 return archivaLocator;
847 private static class LogicalResource
851 public LogicalResource( String path )
856 public String getPath()
861 public void setPath( String path )
867 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
872 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
873 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
875 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
877 WebdavMethodUtil.getMethodPermission(
878 request.getMethod() ) );
880 catch ( AuthenticationException e )
882 // safety check for MRM-911
883 String guest = UserManager.GUEST_USERNAME;
886 if ( servletAuth.isAuthorized( guest,
887 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
888 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
893 catch ( UnauthorizedException ae )
895 throw new UnauthorizedDavException( repositoryId,
896 "You are not authenticated and authorized to access any repository." );
899 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
901 catch ( MustChangePasswordException e )
903 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
905 catch ( AccountLockedException e )
907 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
909 catch ( AuthorizationException e )
911 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
912 "Fatal Authorization Subsystem Error." );
914 catch ( UnauthorizedException e )
916 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
920 private DavResource getResource( DavServletRequest request, List<String> repositories,
921 ArchivaDavResourceLocator locator )
924 List<File> mergedRepositoryContents = new ArrayList<File>();
925 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
926 if ( path.startsWith( "/" ) )
928 path = path.substring( 1 );
930 LogicalResource logicalResource = new LogicalResource( path );
933 // if the current user logged in has permission to any of the repositories, allow user to
934 // browse the repo group but displaying only the repositories which the user has permission to access.
935 // otherwise, prompt for authentication.
937 String activePrincipal = getActivePrincipal( request );
939 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
945 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
946 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
950 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request );
951 mergedRepositoryContents.add( mergedRepoDir );
954 catch ( RepositoryAdminException e )
956 throw new DavException( 500, e );
958 catch ( IndexMergerException e )
960 throw new DavException( 500, e );
966 for ( String repository : repositories )
968 ManagedRepositoryContent managedRepository = null;
972 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
974 catch ( RepositoryNotFoundException e )
976 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
977 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
979 catch ( RepositoryException e )
981 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
982 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
985 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
986 if ( resourceFile.exists() )
988 // in case of group displaying index directory doesn't have sense !!
989 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
990 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
992 if ( !new File( repoIndexDirectory ).isAbsolute() )
994 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
995 StringUtils.isEmpty( repoIndexDirectory )
997 : repoIndexDirectory ).getAbsolutePath();
1000 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1002 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1003 ".indexer" ).getAbsolutePath();
1006 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1007 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1009 // for prompted authentication
1010 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1014 if ( isAuthorized( request, repository ) )
1016 mergedRepositoryContents.add( resourceFile );
1017 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1020 catch ( DavException e )
1022 // TODO: review exception handling
1023 if ( log.isDebugEnabled() )
1025 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1026 + activePrincipal + "': " + e.getMessage() );
1033 // for the current user logged in
1036 if ( servletAuth.isAuthorized( activePrincipal, repository,
1037 WebdavMethodUtil.getMethodPermission(
1038 request.getMethod() ) ) )
1040 mergedRepositoryContents.add( resourceFile );
1041 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1044 catch ( UnauthorizedException e )
1046 // TODO: review exception handling
1047 if ( log.isDebugEnabled() )
1049 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1050 + activePrincipal + "': " + e.getMessage() );
1061 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1064 ArchivaVirtualDavResource resource =
1065 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1068 // compatibility with MRM-440 to ensure browsing the repository group works ok
1069 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1071 throw new BrowserRedirectException( resource.getHref() );
1077 protected String getActivePrincipal( DavServletRequest request )
1079 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1080 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1084 * Check if the current user is authorized to access any of the repos
1087 * @param repositories
1088 * @param activePrincipal
1091 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1093 boolean allow = false;
1095 // if securitySession != null, it means that the user was prompted for authentication
1096 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1098 for ( String repository : repositories )
1102 if ( isAuthorized( request, repository ) )
1108 catch ( DavException e )
1116 for ( String repository : repositories )
1120 if ( servletAuth.isAuthorized( activePrincipal, repository,
1121 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1127 catch ( UnauthorizedException e )
1137 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1138 throws RepositoryMetadataException, DigesterException, IOException
1140 File outputFile = new File( outputFilename );
1141 if ( outputFile.exists() )
1143 FileUtils.deleteQuietly( outputFile );
1146 outputFile.getParentFile().mkdirs();
1147 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1149 createChecksumFile( outputFilename, digestSha1 );
1150 createChecksumFile( outputFilename, digestMd5 );
1155 private void createChecksumFile( String path, Digester digester )
1156 throws DigesterException, IOException
1158 File checksumFile = new File( path + digester.getFilenameExtension() );
1159 if ( !checksumFile.exists() )
1161 FileUtils.deleteQuietly( checksumFile );
1162 checksum.createChecksum( new File( path ), digester );
1164 else if ( !checksumFile.isFile() )
1166 log.error( "Checksum file is not a file." );
1170 private boolean isProjectReference( String requestedResource )
1174 metadataTools.toVersionedReference( requestedResource );
1177 catch ( RepositoryMetadataException re )
1183 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1184 DavServletRequest request )
1185 throws RepositoryAdminException, IndexMergerException
1188 Set<String> authzRepos = new HashSet<String>();
1189 for ( String repository : repositories )
1193 if ( servletAuth.isAuthorized( activePrincipal, repository,
1194 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1196 authzRepos.add( repository );
1197 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1200 catch ( UnauthorizedException e )
1202 // TODO: review exception handling
1203 if ( log.isDebugEnabled() )
1205 log.debug( "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1211 File mergedRepoDir = indexMerger.buildMergedIndex( authzRepos, true );
1212 return mergedRepoDir;
1216 public void setServletAuth( ServletAuthenticator servletAuth )
1218 this.servletAuth = servletAuth;
1221 public void setHttpAuth( HttpAuthenticator httpAuth )
1223 this.httpAuth = httpAuth;
1226 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1228 this.scheduler = scheduler;
1231 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1233 this.archivaConfiguration = archivaConfiguration;
1236 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1238 this.repositoryFactory = repositoryFactory;
1241 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1243 this.repositoryRequest = repositoryRequest;
1246 public void setConnectors( RepositoryProxyConnectors connectors )
1248 this.connectors = connectors;