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.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;
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"
114 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
120 private RepositoryContentFactory repositoryFactory;
125 private RepositoryRequest repositoryRequest;
128 * plexus.requirement role-hint="default"
131 @Named( value = "repositoryProxyConnectors#default" )
132 private RepositoryProxyConnectors connectors;
138 private MetadataTools metadataTools;
144 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();
172 private ChecksumFile checksum;
175 * plexus.requirement role-hint="sha1"
177 private Digester digestSha1;
180 * plexus.requirement role-hint="md5";
182 private Digester digestMd5;
185 * plexus.requirement role="org.apache.archiva.scheduler.ArchivaTaskScheduler" role-hint="repository"
188 @Named( value = "archivaTaskScheduler#repository" )
189 private RepositoryArchivaTaskScheduler scheduler;
191 private ApplicationContext applicationContext;
194 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
195 ArchivaConfiguration archivaConfiguration )
196 throws PlexusSisuBridgeException
198 this.archivaConfiguration = archivaConfiguration;
199 this.applicationContext = applicationContext;
200 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
202 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
203 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
205 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
209 public void initialize()
214 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
215 final DavServletResponse response )
218 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
220 RepositoryGroupConfiguration repoGroupConfig =
221 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
223 String activePrincipal = getActivePrincipal( request );
225 List<String> resourcesInAbsolutePath = new ArrayList<String>();
227 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
228 DavResource resource;
229 if ( repoGroupConfig != null )
233 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
234 "Write method not allowed for repository groups." );
237 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
239 // handle browse requests for virtual repos
240 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
242 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
246 // make a copy to avoid potential concurrent modifications (eg. by configuration)
247 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
249 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
250 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
251 resourcesInAbsolutePath );
256 ManagedRepositoryContent managedRepository = null;
260 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
262 catch ( RepositoryNotFoundException e )
264 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
265 "Invalid repository: " + archivaLocator.getRepositoryId() );
267 catch ( RepositoryException e )
269 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
272 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
274 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
276 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
277 resourcesInAbsolutePath.add(
278 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
281 String requestedResource = request.getRequestURI();
283 // MRM-872 : merge all available metadata
284 // merge metadata only when requested via the repo group
285 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
286 requestedResource ) ) && repoGroupConfig != null )
288 // this should only be at the project level not version level!
289 if ( isProjectReference( requestedResource ) )
291 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
292 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
294 ArchivaDavResource res = (ArchivaDavResource) resource;
296 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
298 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
300 // for MRM-872 handle checksums of the merged metadata files
301 if ( repositoryRequest.isSupportFile( requestedResource ) )
303 File metadataChecksum =
304 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
305 if ( metadataChecksum.exists() )
307 LogicalResource logicalResource =
308 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
311 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
312 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
313 archivaLocator, this, mimeTypes, auditListeners, scheduler );
318 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
320 // merge the metadata of all repos under group
321 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
322 for ( String resourceAbsPath : resourcesInAbsolutePath )
326 File metadataFile = new File( resourceAbsPath );
327 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
328 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
330 catch ( RepositoryMetadataException r )
332 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
333 "Error occurred while reading metadata file." );
339 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
341 LogicalResource logicalResource = new LogicalResource(
342 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
345 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
346 request.getRemoteAddr(), activePrincipal,
347 request.getDavSession(), archivaLocator, this, mimeTypes,
348 auditListeners, scheduler );
350 catch ( RepositoryMetadataException r )
352 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
353 "Error occurred while writing metadata file." );
355 catch ( IOException ie )
357 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
358 "Error occurred while generating checksum files." );
360 catch ( DigesterException de )
362 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
363 "Error occurred while generating checksum files." );
370 setHeaders( response, locator, resource );
372 // compatibility with MRM-440 to ensure browsing the repository works ok
373 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
375 throw new BrowserRedirectException( resource.getHref() );
377 resource.addLockManager( lockManager );
381 private DavResource processRepositoryGroup( final DavServletRequest request,
382 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
383 String activePrincipal, List<String> resourcesInAbsolutePath )
386 DavResource resource = null;
387 List<DavException> storedExceptions = new ArrayList<DavException>();
389 for ( String repositoryId : repositories )
391 ManagedRepositoryContent managedRepository;
394 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
396 catch ( RepositoryNotFoundException e )
398 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
400 catch ( RepositoryException e )
402 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
407 DavResource updatedResource =
408 processRepository( request, archivaLocator, activePrincipal, managedRepository );
409 if ( resource == null )
411 resource = updatedResource;
414 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
415 if ( logicalResource.endsWith( "/" ) )
417 logicalResource = logicalResource.substring( 1 );
419 resourcesInAbsolutePath.add(
420 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
422 catch ( DavException e )
424 storedExceptions.add( e );
428 if ( resource == null )
430 if ( !storedExceptions.isEmpty() )
433 for ( DavException e : storedExceptions )
435 if ( 401 == e.getErrorCode() )
441 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
445 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
451 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
452 String activePrincipal, ManagedRepositoryContent managedRepository )
455 DavResource resource = null;
456 if ( isAuthorized( request, managedRepository.getId() ) )
458 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
459 if ( path.startsWith( "/" ) )
461 path = path.substring( 1 );
463 LogicalResource logicalResource = new LogicalResource( path );
464 File resourceFile = new File( managedRepository.getRepoRoot(), path );
465 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
466 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
467 archivaLocator, this, mimeTypes, auditListeners, scheduler );
469 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
471 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
473 // force a resource not found
474 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
478 if ( !resource.isCollection() )
480 boolean previouslyExisted = resourceFile.exists();
482 // Attempt to fetch the resource from any defined proxy.
483 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
485 // At this point the incoming request can either be in default or
486 // legacy layout format.
489 // Perform an adjustment of the resource to the managed
490 // repository expected path.
491 String localResourcePath =
492 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
493 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
495 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
496 managedRepository.getRepository(), request.getRemoteAddr(),
497 activePrincipal, request.getDavSession(), archivaLocator, this,
498 mimeTypes, auditListeners, scheduler );
500 catch ( LayoutException e )
502 if ( !resourceFile.exists() )
504 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
510 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
513 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
514 + managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
516 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
517 logicalResource.getPath(), event, activePrincipal );
520 if ( !resourceFile.exists() )
522 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
528 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
530 String resourcePath = logicalResource.getPath();
532 // check if target repo is enabled for releases
533 // we suppose that release-artifacts can be deployed only to repos enabled for releases
534 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
535 && !repositoryRequest.isSupportFile( resourcePath ) )
537 ArtifactReference artifact = null;
540 artifact = managedRepository.toArtifactReference( resourcePath );
542 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
544 // check if artifact already exists and if artifact re-deployment to the repository is allowed
545 if ( managedRepository.hasContent( artifact )
546 && managedRepository.getRepository().isBlockRedeployments() )
548 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
549 + "' is not allowed." );
550 throw new DavException( HttpServletResponse.SC_CONFLICT,
551 "Overwriting released artifacts is not allowed." );
555 catch ( LayoutException e )
557 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
562 * Create parent directories that don't exist when writing a file This actually makes this
563 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
564 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
565 * create the collections themselves.
568 File rootDirectory = new File( managedRepository.getRepoRoot() );
569 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
571 if ( !destDir.exists() )
574 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
576 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
579 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
580 AuditEvent.CREATE_DIR, activePrincipal );
587 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
590 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
592 ManagedRepositoryContent managedRepository;
595 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
597 catch ( RepositoryNotFoundException e )
599 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
600 "Invalid repository: " + archivaLocator.getRepositoryId() );
602 catch ( RepositoryException e )
604 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
607 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
608 if ( logicalResource.startsWith( "/" ) )
610 logicalResource = logicalResource.substring( 1 );
612 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
613 DavResource resource =
614 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
615 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
617 resource.addLockManager( lockManager );
621 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
622 LogicalResource resource )
625 String path = resource.getPath();
626 if ( repositoryRequest.isSupportFile( path ) )
628 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
630 return ( proxiedFile != null );
633 // Is it a Metadata resource?
634 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
636 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
639 // Not any of the above? Then it's gotta be an artifact reference.
642 // Get the artifact reference in a layout neutral way.
643 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
645 if ( artifact != null )
647 applyServerSideRelocation( managedRepository, artifact );
649 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
651 resource.setPath( managedRepository.toPath( artifact ) );
653 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
654 + artifact.getVersion() + "'" );
656 return ( proxiedFile != null );
659 catch ( LayoutException e )
663 catch ( ProxyDownloadException e )
665 log.error( e.getMessage(), e );
666 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
667 "Unable to fetch artifact resource." );
673 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
674 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
677 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
678 * metadatas and serving the expected artifact.
680 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
681 throws ProxyDownloadException
683 if ( "pom".equals( artifact.getType() ) )
688 // Build the artifact POM reference
689 ArtifactReference pomReference = new ArtifactReference();
690 pomReference.setGroupId( artifact.getGroupId() );
691 pomReference.setArtifactId( artifact.getArtifactId() );
692 pomReference.setVersion( artifact.getVersion() );
693 pomReference.setType( "pom" );
695 // Get the artifact POM from proxied repositories if needed
696 connectors.fetchFromProxies( managedRepository, pomReference );
698 // Open and read the POM from the managed repo
699 File pom = managedRepository.toFile( pomReference );
708 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
709 FileReader reader = new FileReader( pom );
713 model = new MavenXpp3Reader().read( reader );
717 if ( reader != null )
723 DistributionManagement dist = model.getDistributionManagement();
726 Relocation relocation = dist.getRelocation();
727 if ( relocation != null )
729 // artifact is relocated : update the repositoryPath
730 if ( relocation.getGroupId() != null )
732 artifact.setGroupId( relocation.getGroupId() );
734 if ( relocation.getArtifactId() != null )
736 artifact.setArtifactId( relocation.getArtifactId() );
738 if ( relocation.getVersion() != null )
740 artifact.setVersion( relocation.getVersion() );
745 catch ( FileNotFoundException e )
747 // Artifact has no POM in repo : ignore
749 catch ( IOException e )
751 // Unable to read POM : ignore.
753 catch ( XmlPullParserException e )
755 // Invalid POM : ignore
761 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
764 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
765 event.setRemoteIP( remoteIP );
767 for ( AuditListener listener : auditListeners )
769 listener.auditEvent( event );
773 public void addAuditListener( AuditListener listener )
775 this.auditListeners.add( listener );
778 public void clearAuditListeners()
780 this.auditListeners.clear();
783 public void removeAuditListener( AuditListener listener )
785 this.auditListeners.remove( listener );
788 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
790 // [MRM-503] - Metadata file need Pragma:no-cache response
792 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
794 response.addHeader( "Pragma", "no-cache" );
795 response.addHeader( "Cache-Control", "no-cache" );
798 // We need to specify this so connecting wagons can work correctly
799 response.addDateHeader( "last-modified", resource.getModificationTime() );
801 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
804 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
807 if ( !( locator instanceof ArchivaDavResourceLocator ) )
809 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
810 "Locator does not implement RepositoryLocator" );
814 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
816 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
819 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
821 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
822 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
824 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
826 return archivaLocator;
829 private static class LogicalResource
833 public LogicalResource( String path )
838 public String getPath()
843 public void setPath( String path )
849 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
854 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
855 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
857 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
859 WebdavMethodUtil.getMethodPermission(
860 request.getMethod() ) );
862 catch ( AuthenticationException e )
864 // safety check for MRM-911
865 String guest = UserManager.GUEST_USERNAME;
868 if ( servletAuth.isAuthorized( guest,
869 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
870 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
875 catch ( UnauthorizedException ae )
877 throw new UnauthorizedDavException( repositoryId,
878 "You are not authenticated and authorized to access any repository." );
881 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
883 catch ( MustChangePasswordException e )
885 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
887 catch ( AccountLockedException e )
889 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
891 catch ( AuthorizationException e )
893 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
894 "Fatal Authorization Subsystem Error." );
896 catch ( UnauthorizedException e )
898 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
902 private DavResource getResource( DavServletRequest request, List<String> repositories,
903 ArchivaDavResourceLocator locator )
906 List<File> mergedRepositoryContents = new ArrayList<File>();
907 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
908 if ( path.startsWith( "/" ) )
910 path = path.substring( 1 );
912 LogicalResource logicalResource = new LogicalResource( path );
915 // if the current user logged in has permission to any of the repositories, allow user to
916 // browse the repo group but displaying only the repositories which the user has permission to access.
917 // otherwise, prompt for authentication.
919 String activePrincipal = getActivePrincipal( request );
921 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
925 for ( String repository : repositories )
927 ManagedRepositoryContent managedRepository = null;
931 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
933 catch ( RepositoryNotFoundException e )
935 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
936 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
938 catch ( RepositoryException e )
940 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
941 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
944 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
945 if ( resourceFile.exists() )
947 // for prompted authentication
948 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
952 if ( isAuthorized( request, repository ) )
954 mergedRepositoryContents.add( resourceFile );
955 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
958 catch ( DavException e )
960 // TODO: review exception handling
962 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
968 // for the current user logged in
971 if ( servletAuth.isAuthorized( activePrincipal, repository,
972 WebdavMethodUtil.getMethodPermission(
973 request.getMethod() ) ) )
975 mergedRepositoryContents.add( resourceFile );
976 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
979 catch ( UnauthorizedException e )
981 // TODO: review exception handling
983 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': "
992 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
995 ArchivaVirtualDavResource resource =
996 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
999 // compatibility with MRM-440 to ensure browsing the repository group works ok
1000 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1002 throw new BrowserRedirectException( resource.getHref() );
1008 protected String getActivePrincipal( DavServletRequest request )
1010 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1011 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1015 * Check if the current user is authorized to access any of the repos
1018 * @param repositories
1019 * @param activePrincipal
1022 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1024 boolean allow = false;
1026 // if securitySession != null, it means that the user was prompted for authentication
1027 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1029 for ( String repository : repositories )
1033 if ( isAuthorized( request, repository ) )
1039 catch ( DavException e )
1047 for ( String repository : repositories )
1051 if ( servletAuth.isAuthorized( activePrincipal, repository,
1052 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1058 catch ( UnauthorizedException e )
1068 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1069 throws RepositoryMetadataException, DigesterException, IOException
1071 File outputFile = new File( outputFilename );
1072 if ( outputFile.exists() )
1074 FileUtils.deleteQuietly( outputFile );
1077 outputFile.getParentFile().mkdirs();
1078 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1080 createChecksumFile( outputFilename, digestSha1 );
1081 createChecksumFile( outputFilename, digestMd5 );
1086 private void createChecksumFile( String path, Digester digester )
1087 throws DigesterException, IOException
1089 File checksumFile = new File( path + digester.getFilenameExtension() );
1090 if ( !checksumFile.exists() )
1092 FileUtils.deleteQuietly( checksumFile );
1093 checksum.createChecksum( new File( path ), digester );
1095 else if ( !checksumFile.isFile() )
1097 log.error( "Checksum file is not a file." );
1101 private boolean isProjectReference( String requestedResource )
1105 metadataTools.toVersionedReference( requestedResource );
1108 catch ( RepositoryMetadataException re )
1114 public void setServletAuth( ServletAuthenticator servletAuth )
1116 this.servletAuth = servletAuth;
1119 public void setHttpAuth( HttpAuthenticator httpAuth )
1121 this.httpAuth = httpAuth;
1124 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1126 this.scheduler = scheduler;
1129 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1131 this.archivaConfiguration = archivaConfiguration;
1134 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1136 this.repositoryFactory = repositoryFactory;
1139 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1141 this.repositoryRequest = repositoryRequest;
1144 public void setConnectors( RepositoryProxyConnectors connectors )
1146 this.connectors = connectors;