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.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.common.utils.PathUtil;
28 import org.apache.archiva.common.utils.VersionUtil;
29 import org.apache.archiva.configuration.ArchivaConfiguration;
30 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
31 import org.apache.archiva.model.ArchivaRepositoryMetadata;
32 import org.apache.archiva.model.ArtifactReference;
33 import org.apache.archiva.policies.ProxyDownloadException;
34 import org.apache.archiva.proxy.RepositoryProxyConnectors;
35 import org.apache.archiva.repository.ManagedRepositoryContent;
36 import org.apache.archiva.repository.RepositoryContentFactory;
37 import org.apache.archiva.repository.RepositoryException;
38 import org.apache.archiva.repository.RepositoryNotFoundException;
39 import org.apache.archiva.repository.content.LegacyPathParser;
40 import org.apache.archiva.repository.content.RepositoryRequest;
41 import org.apache.archiva.repository.layout.LayoutException;
42 import org.apache.archiva.repository.metadata.MetadataTools;
43 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
44 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
45 import org.apache.archiva.repository.metadata.RepositoryMetadataReader;
46 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
47 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
48 import org.apache.archiva.security.ServletAuthenticator;
49 import org.apache.archiva.webdav.util.MimeTypes;
50 import org.apache.archiva.webdav.util.RepositoryPathUtil;
51 import org.apache.archiva.webdav.util.WebdavMethodUtil;
52 import org.apache.commons.io.FileUtils;
53 import org.apache.commons.lang.StringUtils;
54 import org.apache.jackrabbit.webdav.DavException;
55 import org.apache.jackrabbit.webdav.DavResource;
56 import org.apache.jackrabbit.webdav.DavResourceFactory;
57 import org.apache.jackrabbit.webdav.DavResourceLocator;
58 import org.apache.jackrabbit.webdav.DavServletRequest;
59 import org.apache.jackrabbit.webdav.DavServletResponse;
60 import org.apache.jackrabbit.webdav.DavSession;
61 import org.apache.jackrabbit.webdav.lock.LockManager;
62 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
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 );
114 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
120 private RepositoryContentFactory repositoryFactory;
125 private RepositoryRequest repositoryRequest;
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;
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;
177 private Digester digestSha1;
182 private Digester digestMd5;
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 if ( log.isDebugEnabled() )
515 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
516 + managedRepository.getId() + "' (current user '" + activePrincipal
519 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
520 logicalResource.getPath(), event, activePrincipal );
523 if ( !resourceFile.exists() )
525 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
531 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
533 String resourcePath = logicalResource.getPath();
535 // check if target repo is enabled for releases
536 // we suppose that release-artifacts can be deployed only to repos enabled for releases
537 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
538 && !repositoryRequest.isSupportFile( resourcePath ) )
540 ArtifactReference artifact = null;
543 artifact = managedRepository.toArtifactReference( resourcePath );
545 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
547 // check if artifact already exists and if artifact re-deployment to the repository is allowed
548 if ( managedRepository.hasContent( artifact )
549 && managedRepository.getRepository().isBlockRedeployments() )
551 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
552 + "' is not allowed." );
553 throw new DavException( HttpServletResponse.SC_CONFLICT,
554 "Overwriting released artifacts is not allowed." );
558 catch ( LayoutException e )
560 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
565 * Create parent directories that don't exist when writing a file This actually makes this
566 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
567 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
568 * create the collections themselves.
571 File rootDirectory = new File( managedRepository.getRepoRoot() );
572 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
574 if ( !destDir.exists() )
577 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
579 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
582 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
583 AuditEvent.CREATE_DIR, activePrincipal );
590 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
593 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
595 ManagedRepositoryContent managedRepository;
598 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
600 catch ( RepositoryNotFoundException e )
602 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
603 "Invalid repository: " + archivaLocator.getRepositoryId() );
605 catch ( RepositoryException e )
607 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
610 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
611 if ( logicalResource.startsWith( "/" ) )
613 logicalResource = logicalResource.substring( 1 );
615 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
616 DavResource resource =
617 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
618 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
620 resource.addLockManager( lockManager );
624 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
625 LogicalResource resource )
628 String path = resource.getPath();
629 if ( repositoryRequest.isSupportFile( path ) )
631 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
633 return ( proxiedFile != null );
636 // Is it a Metadata resource?
637 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
639 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
642 // Not any of the above? Then it's gotta be an artifact reference.
645 // Get the artifact reference in a layout neutral way.
646 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
648 if ( artifact != null )
650 applyServerSideRelocation( managedRepository, artifact );
652 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
654 resource.setPath( managedRepository.toPath( artifact ) );
655 if ( log.isDebugEnabled() )
657 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
658 + artifact.getVersion() + "'" );
660 return ( proxiedFile != null );
663 catch ( LayoutException e )
667 catch ( ProxyDownloadException e )
669 log.error( e.getMessage(), e );
670 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
671 "Unable to fetch artifact resource." );
677 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
678 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
681 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
682 * metadatas and serving the expected artifact.
684 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
685 throws ProxyDownloadException
687 if ( "pom".equals( artifact.getType() ) )
692 // Build the artifact POM reference
693 ArtifactReference pomReference = new ArtifactReference();
694 pomReference.setGroupId( artifact.getGroupId() );
695 pomReference.setArtifactId( artifact.getArtifactId() );
696 pomReference.setVersion( artifact.getVersion() );
697 pomReference.setType( "pom" );
699 // Get the artifact POM from proxied repositories if needed
700 connectors.fetchFromProxies( managedRepository, pomReference );
702 // Open and read the POM from the managed repo
703 File pom = managedRepository.toFile( pomReference );
712 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
713 FileReader reader = new FileReader( pom );
717 model = new MavenXpp3Reader().read( reader );
721 if ( reader != null )
727 DistributionManagement dist = model.getDistributionManagement();
730 Relocation relocation = dist.getRelocation();
731 if ( relocation != null )
733 // artifact is relocated : update the repositoryPath
734 if ( relocation.getGroupId() != null )
736 artifact.setGroupId( relocation.getGroupId() );
738 if ( relocation.getArtifactId() != null )
740 artifact.setArtifactId( relocation.getArtifactId() );
742 if ( relocation.getVersion() != null )
744 artifact.setVersion( relocation.getVersion() );
749 catch ( FileNotFoundException e )
751 // Artifact has no POM in repo : ignore
753 catch ( IOException e )
755 // Unable to read POM : ignore.
757 catch ( XmlPullParserException e )
759 // Invalid POM : ignore
765 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
768 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
769 event.setRemoteIP( remoteIP );
771 for ( AuditListener listener : auditListeners )
773 listener.auditEvent( event );
777 public void addAuditListener( AuditListener listener )
779 this.auditListeners.add( listener );
782 public void clearAuditListeners()
784 this.auditListeners.clear();
787 public void removeAuditListener( AuditListener listener )
789 this.auditListeners.remove( listener );
792 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
794 // [MRM-503] - Metadata file need Pragma:no-cache response
796 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
798 response.addHeader( "Pragma", "no-cache" );
799 response.addHeader( "Cache-Control", "no-cache" );
802 // We need to specify this so connecting wagons can work correctly
803 response.addDateHeader( "last-modified", resource.getModificationTime() );
805 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
808 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
811 if ( !( locator instanceof ArchivaDavResourceLocator ) )
813 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
814 "Locator does not implement RepositoryLocator" );
818 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
820 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
823 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
825 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
826 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
828 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
830 return archivaLocator;
833 private static class LogicalResource
837 public LogicalResource( String path )
842 public String getPath()
847 public void setPath( String path )
853 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
858 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
859 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
861 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
863 WebdavMethodUtil.getMethodPermission(
864 request.getMethod() ) );
866 catch ( AuthenticationException e )
868 // safety check for MRM-911
869 String guest = UserManager.GUEST_USERNAME;
872 if ( servletAuth.isAuthorized( guest,
873 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
874 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
879 catch ( UnauthorizedException ae )
881 throw new UnauthorizedDavException( repositoryId,
882 "You are not authenticated and authorized to access any repository." );
885 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
887 catch ( MustChangePasswordException e )
889 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
891 catch ( AccountLockedException e )
893 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
895 catch ( AuthorizationException e )
897 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
898 "Fatal Authorization Subsystem Error." );
900 catch ( UnauthorizedException e )
902 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
906 private DavResource getResource( DavServletRequest request, List<String> repositories,
907 ArchivaDavResourceLocator locator )
910 List<File> mergedRepositoryContents = new ArrayList<File>();
911 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
912 if ( path.startsWith( "/" ) )
914 path = path.substring( 1 );
916 LogicalResource logicalResource = new LogicalResource( path );
919 // if the current user logged in has permission to any of the repositories, allow user to
920 // browse the repo group but displaying only the repositories which the user has permission to access.
921 // otherwise, prompt for authentication.
923 String activePrincipal = getActivePrincipal( request );
925 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
929 for ( String repository : repositories )
931 ManagedRepositoryContent managedRepository = null;
935 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
937 catch ( RepositoryNotFoundException e )
939 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
940 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
942 catch ( RepositoryException e )
944 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
945 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
948 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
949 if ( resourceFile.exists() )
951 // for prompted authentication
952 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
956 if ( isAuthorized( request, repository ) )
958 mergedRepositoryContents.add( resourceFile );
959 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
962 catch ( DavException e )
964 // TODO: review exception handling
965 if ( log.isDebugEnabled() )
968 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
969 + "': " + e.getMessage() );
975 // for the current user logged in
978 if ( servletAuth.isAuthorized( activePrincipal, repository,
979 WebdavMethodUtil.getMethodPermission(
980 request.getMethod() ) ) )
982 mergedRepositoryContents.add( resourceFile );
983 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
986 catch ( UnauthorizedException e )
988 // TODO: review exception handling
989 if ( log.isDebugEnabled() )
992 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
993 + "': " + e.getMessage() );
1002 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1005 ArchivaVirtualDavResource resource =
1006 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1009 // compatibility with MRM-440 to ensure browsing the repository group works ok
1010 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1012 throw new BrowserRedirectException( resource.getHref() );
1018 protected String getActivePrincipal( DavServletRequest request )
1020 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1021 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1025 * Check if the current user is authorized to access any of the repos
1028 * @param repositories
1029 * @param activePrincipal
1032 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1034 boolean allow = false;
1036 // if securitySession != null, it means that the user was prompted for authentication
1037 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1039 for ( String repository : repositories )
1043 if ( isAuthorized( request, repository ) )
1049 catch ( DavException e )
1057 for ( String repository : repositories )
1061 if ( servletAuth.isAuthorized( activePrincipal, repository,
1062 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1068 catch ( UnauthorizedException e )
1078 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1079 throws RepositoryMetadataException, DigesterException, IOException
1081 File outputFile = new File( outputFilename );
1082 if ( outputFile.exists() )
1084 FileUtils.deleteQuietly( outputFile );
1087 outputFile.getParentFile().mkdirs();
1088 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1090 createChecksumFile( outputFilename, digestSha1 );
1091 createChecksumFile( outputFilename, digestMd5 );
1096 private void createChecksumFile( String path, Digester digester )
1097 throws DigesterException, IOException
1099 File checksumFile = new File( path + digester.getFilenameExtension() );
1100 if ( !checksumFile.exists() )
1102 FileUtils.deleteQuietly( checksumFile );
1103 checksum.createChecksum( new File( path ), digester );
1105 else if ( !checksumFile.isFile() )
1107 log.error( "Checksum file is not a file." );
1111 private boolean isProjectReference( String requestedResource )
1115 metadataTools.toVersionedReference( requestedResource );
1118 catch ( RepositoryMetadataException re )
1124 public void setServletAuth( ServletAuthenticator servletAuth )
1126 this.servletAuth = servletAuth;
1129 public void setHttpAuth( HttpAuthenticator httpAuth )
1131 this.httpAuth = httpAuth;
1134 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1136 this.scheduler = scheduler;
1139 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1141 this.archivaConfiguration = archivaConfiguration;
1144 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1146 this.repositoryFactory = repositoryFactory;
1149 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1151 this.repositoryRequest = repositoryRequest;
1154 public void setConnectors( RepositoryProxyConnectors connectors )
1156 this.connectors = connectors;