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;
96 import java.io.FileNotFoundException;
97 import java.io.FileReader;
98 import java.io.IOException;
99 import java.util.ArrayList;
100 import java.util.HashSet;
101 import java.util.List;
102 import java.util.Set;
107 @Service( "davResourceFactory#archiva" )
108 public class ArchivaDavResourceFactory
109 implements DavResourceFactory, Auditable
111 private static final String PROXIED_SUFFIX = " (proxied)";
113 private static final String HTTP_PUT_METHOD = "PUT";
115 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
121 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
127 private RepositoryContentFactory repositoryFactory;
132 private RepositoryRequest repositoryRequest;
138 @Named( value = "repositoryProxyConnectors#default" )
139 private RepositoryProxyConnectors connectors;
145 private MetadataTools metadataTools;
151 private MimeTypes mimeTypes;
156 private ArchivaConfiguration archivaConfiguration;
162 private ServletAuthenticator servletAuth;
168 @Named( value = "httpAuthenticator#basic" )
169 private HttpAuthenticator httpAuth;
172 private IndexMerger indexMerger;
175 private RepositorySearch repositorySearch;
178 * Lock Manager - use simple implementation from JackRabbit
180 private final LockManager lockManager = new SimpleLockManager();
185 private ChecksumFile checksum;
190 private Digester digestSha1;
195 private Digester digestMd5;
201 @Named( value = "archivaTaskScheduler#repository" )
202 private RepositoryArchivaTaskScheduler scheduler;
204 private ApplicationContext applicationContext;
207 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
208 ArchivaConfiguration archivaConfiguration )
209 throws PlexusSisuBridgeException
211 this.archivaConfiguration = archivaConfiguration;
212 this.applicationContext = applicationContext;
213 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
215 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
216 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
218 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
222 public void initialize()
227 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
228 final DavServletResponse response )
231 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
233 RepositoryGroupConfiguration repoGroupConfig =
234 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
236 String activePrincipal = getActivePrincipal( request );
238 List<String> resourcesInAbsolutePath = new ArrayList<String>();
240 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
241 DavResource resource;
242 if ( repoGroupConfig != null )
246 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
247 "Write method not allowed for repository groups." );
250 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
252 // handle browse requests for virtual repos
253 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
255 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
259 // make a copy to avoid potential concurrent modifications (eg. by configuration)
260 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
262 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
263 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
264 resourcesInAbsolutePath );
269 ManagedRepositoryContent managedRepository = null;
273 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
275 catch ( RepositoryNotFoundException e )
277 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
278 "Invalid repository: " + archivaLocator.getRepositoryId() );
280 catch ( RepositoryException e )
282 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
285 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
287 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
289 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
290 resourcesInAbsolutePath.add(
291 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
294 String requestedResource = request.getRequestURI();
296 // MRM-872 : merge all available metadata
297 // merge metadata only when requested via the repo group
298 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
299 requestedResource ) ) && repoGroupConfig != null )
301 // this should only be at the project level not version level!
302 if ( isProjectReference( requestedResource ) )
304 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
305 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
307 ArchivaDavResource res = (ArchivaDavResource) resource;
309 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
311 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
313 // for MRM-872 handle checksums of the merged metadata files
314 if ( repositoryRequest.isSupportFile( requestedResource ) )
316 File metadataChecksum =
317 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
318 if ( metadataChecksum.exists() )
320 LogicalResource logicalResource =
321 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
324 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
325 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
326 archivaLocator, this, mimeTypes, auditListeners, scheduler );
331 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
333 // merge the metadata of all repos under group
334 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
335 for ( String resourceAbsPath : resourcesInAbsolutePath )
339 File metadataFile = new File( resourceAbsPath );
340 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
341 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
343 catch ( RepositoryMetadataException r )
345 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
346 "Error occurred while reading metadata file." );
352 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
354 LogicalResource logicalResource = new LogicalResource(
355 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
358 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
359 request.getRemoteAddr(), activePrincipal,
360 request.getDavSession(), archivaLocator, this, mimeTypes,
361 auditListeners, scheduler );
363 catch ( RepositoryMetadataException r )
365 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
366 "Error occurred while writing metadata file." );
368 catch ( IOException ie )
370 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
371 "Error occurred while generating checksum files." );
373 catch ( DigesterException de )
375 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
376 "Error occurred while generating checksum files." );
383 setHeaders( response, locator, resource );
385 // compatibility with MRM-440 to ensure browsing the repository works ok
386 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
388 throw new BrowserRedirectException( resource.getHref() );
390 resource.addLockManager( lockManager );
394 private DavResource processRepositoryGroup( final DavServletRequest request,
395 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
396 String activePrincipal, List<String> resourcesInAbsolutePath )
399 DavResource resource = null;
400 List<DavException> storedExceptions = new ArrayList<DavException>();
402 for ( String repositoryId : repositories )
404 ManagedRepositoryContent managedRepository;
407 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
409 catch ( RepositoryNotFoundException e )
411 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
413 catch ( RepositoryException e )
415 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
420 DavResource updatedResource =
421 processRepository( request, archivaLocator, activePrincipal, managedRepository );
422 if ( resource == null )
424 resource = updatedResource;
427 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
428 if ( logicalResource.endsWith( "/" ) )
430 logicalResource = logicalResource.substring( 1 );
432 resourcesInAbsolutePath.add(
433 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
435 catch ( DavException e )
437 storedExceptions.add( e );
441 if ( resource == null )
443 if ( !storedExceptions.isEmpty() )
446 for ( DavException e : storedExceptions )
448 if ( 401 == e.getErrorCode() )
454 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
458 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
464 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
465 String activePrincipal, ManagedRepositoryContent managedRepository )
468 DavResource resource = null;
469 if ( isAuthorized( request, managedRepository.getId() ) )
471 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
472 if ( path.startsWith( "/" ) )
474 path = path.substring( 1 );
476 LogicalResource logicalResource = new LogicalResource( path );
477 File resourceFile = new File( managedRepository.getRepoRoot(), path );
478 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
479 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
480 archivaLocator, this, mimeTypes, auditListeners, scheduler );
482 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
484 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
486 // force a resource not found
487 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
491 if ( !resource.isCollection() )
493 boolean previouslyExisted = resourceFile.exists();
495 // Attempt to fetch the resource from any defined proxy.
496 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
498 // At this point the incoming request can either be in default or
499 // legacy layout format.
502 // Perform an adjustment of the resource to the managed
503 // repository expected path.
504 String localResourcePath =
505 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
506 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
508 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
509 managedRepository.getRepository(), request.getRemoteAddr(),
510 activePrincipal, request.getDavSession(), archivaLocator, this,
511 mimeTypes, auditListeners, scheduler );
513 catch ( LayoutException e )
515 if ( !resourceFile.exists() )
517 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
523 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
526 if ( log.isDebugEnabled() )
528 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
529 + managedRepository.getId() + "' (current user '" + activePrincipal
532 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
533 logicalResource.getPath(), event, activePrincipal );
536 if ( !resourceFile.exists() )
538 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
544 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
546 String resourcePath = logicalResource.getPath();
548 // check if target repo is enabled for releases
549 // we suppose that release-artifacts can be deployed only to repos enabled for releases
550 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
551 && !repositoryRequest.isSupportFile( resourcePath ) )
553 ArtifactReference artifact = null;
556 artifact = managedRepository.toArtifactReference( resourcePath );
558 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
560 // check if artifact already exists and if artifact re-deployment to the repository is allowed
561 if ( managedRepository.hasContent( artifact )
562 && managedRepository.getRepository().isBlockRedeployments() )
564 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
565 + "' is not allowed." );
566 throw new DavException( HttpServletResponse.SC_CONFLICT,
567 "Overwriting released artifacts is not allowed." );
571 catch ( LayoutException e )
573 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
578 * Create parent directories that don't exist when writing a file This actually makes this
579 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
580 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
581 * create the collections themselves.
584 File rootDirectory = new File( managedRepository.getRepoRoot() );
585 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
587 if ( !destDir.exists() )
590 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
592 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
595 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
596 AuditEvent.CREATE_DIR, activePrincipal );
603 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
606 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
608 ManagedRepositoryContent managedRepository;
611 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
613 catch ( RepositoryNotFoundException e )
615 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
616 "Invalid repository: " + archivaLocator.getRepositoryId() );
618 catch ( RepositoryException e )
620 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
623 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
624 if ( logicalResource.startsWith( "/" ) )
626 logicalResource = logicalResource.substring( 1 );
628 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
629 DavResource resource =
630 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
631 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
633 resource.addLockManager( lockManager );
637 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
638 LogicalResource resource )
641 String path = resource.getPath();
642 if ( repositoryRequest.isSupportFile( path ) )
644 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
646 return ( proxiedFile != null );
649 // Is it a Metadata resource?
650 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
652 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
655 // Not any of the above? Then it's gotta be an artifact reference.
658 // Get the artifact reference in a layout neutral way.
659 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
661 if ( artifact != null )
663 applyServerSideRelocation( managedRepository, artifact );
665 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
667 resource.setPath( managedRepository.toPath( artifact ) );
668 if ( log.isDebugEnabled() )
670 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
671 + artifact.getVersion() + "'" );
673 return ( proxiedFile != null );
676 catch ( LayoutException e )
680 catch ( ProxyDownloadException e )
682 log.error( e.getMessage(), e );
683 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
684 "Unable to fetch artifact resource." );
690 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
691 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
694 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
695 * metadatas and serving the expected artifact.
697 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
698 throws ProxyDownloadException
700 if ( "pom".equals( artifact.getType() ) )
705 // Build the artifact POM reference
706 ArtifactReference pomReference = new ArtifactReference();
707 pomReference.setGroupId( artifact.getGroupId() );
708 pomReference.setArtifactId( artifact.getArtifactId() );
709 pomReference.setVersion( artifact.getVersion() );
710 pomReference.setType( "pom" );
712 // Get the artifact POM from proxied repositories if needed
713 connectors.fetchFromProxies( managedRepository, pomReference );
715 // Open and read the POM from the managed repo
716 File pom = managedRepository.toFile( pomReference );
725 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
726 FileReader reader = new FileReader( pom );
730 model = new MavenXpp3Reader().read( reader );
734 if ( reader != null )
740 DistributionManagement dist = model.getDistributionManagement();
743 Relocation relocation = dist.getRelocation();
744 if ( relocation != null )
746 // artifact is relocated : update the repositoryPath
747 if ( relocation.getGroupId() != null )
749 artifact.setGroupId( relocation.getGroupId() );
751 if ( relocation.getArtifactId() != null )
753 artifact.setArtifactId( relocation.getArtifactId() );
755 if ( relocation.getVersion() != null )
757 artifact.setVersion( relocation.getVersion() );
762 catch ( FileNotFoundException e )
764 // Artifact has no POM in repo : ignore
766 catch ( IOException e )
768 // Unable to read POM : ignore.
770 catch ( XmlPullParserException e )
772 // Invalid POM : ignore
778 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
781 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
782 event.setRemoteIP( remoteIP );
784 for ( AuditListener listener : auditListeners )
786 listener.auditEvent( event );
790 public void addAuditListener( AuditListener listener )
792 this.auditListeners.add( listener );
795 public void clearAuditListeners()
797 this.auditListeners.clear();
800 public void removeAuditListener( AuditListener listener )
802 this.auditListeners.remove( listener );
805 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
807 // [MRM-503] - Metadata file need Pragma:no-cache response
809 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
811 response.addHeader( "Pragma", "no-cache" );
812 response.addHeader( "Cache-Control", "no-cache" );
815 // We need to specify this so connecting wagons can work correctly
816 response.addDateHeader( "last-modified", resource.getModificationTime() );
818 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
821 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
824 if ( !( locator instanceof ArchivaDavResourceLocator ) )
826 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
827 "Locator does not implement RepositoryLocator" );
831 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
833 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
836 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
838 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
839 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
841 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
843 return archivaLocator;
846 private static class LogicalResource
850 public LogicalResource( String path )
855 public String getPath()
860 public void setPath( String path )
866 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
871 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
872 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
874 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
876 WebdavMethodUtil.getMethodPermission(
877 request.getMethod() ) );
879 catch ( AuthenticationException e )
881 // safety check for MRM-911
882 String guest = UserManager.GUEST_USERNAME;
885 if ( servletAuth.isAuthorized( guest,
886 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
887 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
892 catch ( UnauthorizedException ae )
894 throw new UnauthorizedDavException( repositoryId,
895 "You are not authenticated and authorized to access any repository." );
898 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
900 catch ( MustChangePasswordException e )
902 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
904 catch ( AccountLockedException e )
906 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
908 catch ( AuthorizationException e )
910 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
911 "Fatal Authorization Subsystem Error." );
913 catch ( UnauthorizedException e )
915 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
919 private DavResource getResource( DavServletRequest request, List<String> repositories,
920 ArchivaDavResourceLocator locator )
923 List<File> mergedRepositoryContents = new ArrayList<File>();
924 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
925 if ( path.startsWith( "/" ) )
927 path = path.substring( 1 );
929 LogicalResource logicalResource = new LogicalResource( path );
932 // if the current user logged in has permission to any of the repositories, allow user to
933 // browse the repo group but displaying only the repositories which the user has permission to access.
934 // otherwise, prompt for authentication.
936 String activePrincipal = getActivePrincipal( request );
938 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
942 for ( String repository : repositories )
944 ManagedRepositoryContent managedRepository = null;
948 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
950 catch ( RepositoryNotFoundException e )
952 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
953 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
955 catch ( RepositoryException e )
957 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
958 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
961 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
962 if ( resourceFile.exists() )
964 // in case of group displaying index directory doesn't have sense !!
965 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
966 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
968 if ( !new File( repoIndexDirectory ).isAbsolute() )
970 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
971 StringUtils.isEmpty( repoIndexDirectory )
973 : repoIndexDirectory ).getAbsolutePath();
976 if ( StringUtils.isEmpty( repoIndexDirectory ) )
979 new File( managedRepository.getRepository().getLocation(), ".indexer" ).getAbsolutePath();
982 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
983 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
985 // for prompted authentication
986 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
990 if ( isAuthorized( request, repository ) )
992 mergedRepositoryContents.add( resourceFile );
993 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
996 catch ( DavException e )
998 // TODO: review exception handling
999 if ( log.isDebugEnabled() )
1002 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
1003 + "': " + e.getMessage() );
1010 // for the current user logged in
1013 if ( servletAuth.isAuthorized( activePrincipal, repository,
1014 WebdavMethodUtil.getMethodPermission(
1015 request.getMethod() ) ) )
1017 mergedRepositoryContents.add( resourceFile );
1018 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1021 catch ( UnauthorizedException e )
1023 // TODO: review exception handling
1024 if ( log.isDebugEnabled() )
1027 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
1028 + "': " + e.getMessage() );
1036 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1037 if ( StringUtils.endsWith( path, ".indexer" ) )
1041 Set<String> authzRepos = new HashSet<String>();
1042 for ( String repository : repositories )
1046 if ( servletAuth.isAuthorized( activePrincipal, repository,
1047 WebdavMethodUtil.getMethodPermission(
1048 request.getMethod() ) ) )
1050 authzRepos.add( repository );
1051 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1054 catch ( UnauthorizedException e )
1056 // TODO: review exception handling
1057 if ( log.isDebugEnabled() )
1060 "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1066 File mergedRepoDir = indexMerger.buildMergedIndex( authzRepos, true );
1067 mergedRepositoryContents.add( mergedRepoDir );
1070 catch ( RepositoryAdminException e )
1072 throw new DavException( 500, e );
1074 catch ( IndexMergerException e )
1076 throw new DavException( 500, e );
1083 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1086 ArchivaVirtualDavResource resource =
1087 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1090 // compatibility with MRM-440 to ensure browsing the repository group works ok
1091 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1093 throw new BrowserRedirectException( resource.getHref() );
1099 protected String getActivePrincipal( DavServletRequest request )
1101 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1102 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1106 * Check if the current user is authorized to access any of the repos
1109 * @param repositories
1110 * @param activePrincipal
1113 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1115 boolean allow = false;
1117 // if securitySession != null, it means that the user was prompted for authentication
1118 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1120 for ( String repository : repositories )
1124 if ( isAuthorized( request, repository ) )
1130 catch ( DavException e )
1138 for ( String repository : repositories )
1142 if ( servletAuth.isAuthorized( activePrincipal, repository,
1143 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1149 catch ( UnauthorizedException e )
1159 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1160 throws RepositoryMetadataException, DigesterException, IOException
1162 File outputFile = new File( outputFilename );
1163 if ( outputFile.exists() )
1165 FileUtils.deleteQuietly( outputFile );
1168 outputFile.getParentFile().mkdirs();
1169 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1171 createChecksumFile( outputFilename, digestSha1 );
1172 createChecksumFile( outputFilename, digestMd5 );
1177 private void createChecksumFile( String path, Digester digester )
1178 throws DigesterException, IOException
1180 File checksumFile = new File( path + digester.getFilenameExtension() );
1181 if ( !checksumFile.exists() )
1183 FileUtils.deleteQuietly( checksumFile );
1184 checksum.createChecksum( new File( path ), digester );
1186 else if ( !checksumFile.isFile() )
1188 log.error( "Checksum file is not a file." );
1192 private boolean isProjectReference( String requestedResource )
1196 metadataTools.toVersionedReference( requestedResource );
1199 catch ( RepositoryMetadataException re )
1205 public void setServletAuth( ServletAuthenticator servletAuth )
1207 this.servletAuth = servletAuth;
1210 public void setHttpAuth( HttpAuthenticator httpAuth )
1212 this.httpAuth = httpAuth;
1215 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1217 this.scheduler = scheduler;
1220 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1222 this.archivaConfiguration = archivaConfiguration;
1225 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1227 this.repositoryFactory = repositoryFactory;
1230 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1232 this.repositoryRequest = repositoryRequest;
1235 public void setConnectors( RepositoryProxyConnectors connectors )
1237 this.connectors = connectors;