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
23 import java.io.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
29 import javax.servlet.http.HttpServletResponse;
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.jackrabbit.webdav.DavException;
34 import org.apache.jackrabbit.webdav.DavResource;
35 import org.apache.jackrabbit.webdav.DavResourceFactory;
36 import org.apache.jackrabbit.webdav.DavResourceLocator;
37 import org.apache.jackrabbit.webdav.DavServletRequest;
38 import org.apache.jackrabbit.webdav.DavServletResponse;
39 import org.apache.jackrabbit.webdav.DavSession;
40 import org.apache.jackrabbit.webdav.lock.LockManager;
41 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
42 import org.apache.maven.archiva.common.utils.PathUtil;
43 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
44 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
45 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
46 import org.apache.maven.archiva.model.ArtifactReference;
47 import org.apache.maven.archiva.policies.ProxyDownloadException;
48 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
49 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
50 import org.apache.maven.archiva.repository.RepositoryContentFactory;
51 import org.apache.maven.archiva.repository.RepositoryException;
52 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
53 import org.apache.maven.archiva.repository.audit.AuditEvent;
54 import org.apache.maven.archiva.repository.audit.AuditListener;
55 import org.apache.maven.archiva.repository.audit.Auditable;
56 import org.apache.maven.archiva.repository.content.RepositoryRequest;
57 import org.apache.maven.archiva.repository.layout.LayoutException;
58 import org.apache.maven.archiva.repository.metadata.MetadataTools;
59 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
64 import org.apache.maven.archiva.security.ServletAuthenticator;
65 import org.apache.maven.archiva.webdav.util.MimeTypes;
66 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
67 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
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;
90 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
92 public class ArchivaDavResourceFactory
93 implements DavResourceFactory, Auditable
95 private static final String PROXIED_SUFFIX = " (proxied)";
97 private static final String HTTP_PUT_METHOD = "PUT";
99 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
102 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
104 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
107 * @plexus.requirement
109 private RepositoryContentFactory repositoryFactory;
112 * @plexus.requirement
114 private RepositoryRequest repositoryRequest;
117 * @plexus.requirement role-hint="default"
119 private RepositoryProxyConnectors connectors;
122 * @plexus.requirement
124 private MetadataTools metadataTools;
127 * @plexus.requirement
129 private MimeTypes mimeTypes;
132 * @plexus.requirement
134 private ArchivaConfiguration archivaConfiguration;
137 * @plexus.requirement
139 private ServletAuthenticator servletAuth;
142 * @plexus.requirement role-hint="basic"
144 private HttpAuthenticator httpAuth;
147 * Lock Manager - use simple implementation from JackRabbit
149 private final LockManager lockManager = new SimpleLockManager();
152 * @plexus.requirement
154 private ChecksumFile checksum;
157 * @plexus.requirement role-hint="sha1"
159 private Digester digestSha1;
162 * @plexus.requirement role-hint="md5";
164 private Digester digestMd5;
167 * @plexus.requirement
169 private ArchivaTaskScheduler scheduler;
171 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
172 final DavServletResponse response )
175 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
177 RepositoryGroupConfiguration repoGroupConfig =
178 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
180 String activePrincipal = getActivePrincipal( request );
182 List<String> resourcesInAbsolutePath = new ArrayList<String>();
184 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
185 DavResource resource;
186 if ( repoGroupConfig != null )
190 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
191 "Write method not allowed for repository groups." );
194 log.debug( "Repository group '" + repoGroupConfig.getId() + "' accessed by '" + activePrincipal + "'" );
196 // handle browse requests for virtual repos
197 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
199 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
204 processRepositoryGroup( request, archivaLocator, repoGroupConfig.getRepositories(),
205 activePrincipal, resourcesInAbsolutePath );
210 ManagedRepositoryContent managedRepository = null;
214 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
216 catch ( RepositoryNotFoundException e )
218 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
219 + archivaLocator.getRepositoryId() );
221 catch ( RepositoryException e )
223 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
226 log.debug( "Managed repository '" + managedRepository.getId() + "' accessed by '" + activePrincipal + "'" );
228 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
230 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
231 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
234 String requestedResource = request.getRequestURI();
236 // MRM-872 : merge all available metadata
237 // merge metadata only when requested via the repo group
238 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) )
239 && repoGroupConfig != null )
241 // this should only be at the project level not version level!
242 if ( isProjectReference( requestedResource ) )
244 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
245 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
247 ArchivaDavResource res = (ArchivaDavResource) resource;
249 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
250 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
252 // for MRM-872 handle checksums of the merged metadata files
253 if ( repositoryRequest.isSupportFile( requestedResource ) )
255 File metadataChecksum =
256 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
257 if ( metadataChecksum.exists() )
259 LogicalResource logicalResource =
260 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
263 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
264 null, request.getRemoteAddr(), activePrincipal,
265 request.getDavSession(), archivaLocator, this, mimeTypes,
266 auditListeners, scheduler );
271 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
273 // merge the metadata of all repos under group
274 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
275 for ( String resourceAbsPath : resourcesInAbsolutePath )
279 File metadataFile = new File( resourceAbsPath );
280 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
281 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
283 catch ( RepositoryMetadataException r )
285 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
286 "Error occurred while reading metadata file." );
292 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
294 LogicalResource logicalResource =
295 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
298 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
299 null, request.getRemoteAddr(), activePrincipal,
300 request.getDavSession(), archivaLocator, this, mimeTypes,
301 auditListeners, scheduler );
303 catch ( RepositoryMetadataException r )
305 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
306 "Error occurred while writing metadata file." );
308 catch ( IOException ie )
310 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
311 "Error occurred while generating checksum files." );
313 catch ( DigesterException de )
315 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
316 "Error occurred while generating checksum files." );
323 setHeaders( response, locator, resource );
325 // compatibility with MRM-440 to ensure browsing the repository works ok
326 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
328 throw new BrowserRedirectException( resource.getHref() );
330 resource.addLockManager( lockManager );
334 private DavResource processRepositoryGroup( final DavServletRequest request,
335 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
336 String activePrincipal, List<String> resourcesInAbsolutePath )
339 DavResource resource = null;
340 List<DavException> storedExceptions = new ArrayList<DavException>();
342 for ( String repositoryId : repositories )
344 ManagedRepositoryContent managedRepository = null;
347 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
349 catch ( RepositoryNotFoundException e )
351 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
353 catch ( RepositoryException e )
355 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
360 DavResource updatedResource =
361 processRepository( request, archivaLocator, activePrincipal, managedRepository );
362 if ( resource == null )
364 resource = updatedResource;
367 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
368 if ( logicalResource.endsWith( "/" ) )
370 logicalResource = logicalResource.substring( 1 );
372 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
374 catch ( DavException e )
376 storedExceptions.add( e );
380 if ( resource == null )
382 if ( !storedExceptions.isEmpty() )
385 for( DavException e : storedExceptions )
387 if( 401 == e.getErrorCode() )
393 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
397 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
403 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
404 String activePrincipal, ManagedRepositoryContent managedRepository )
407 DavResource resource = null;
408 if ( isAuthorized( request, managedRepository.getId() ) )
410 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
411 if ( path.startsWith( "/" ) )
413 path = path.substring( 1 );
415 LogicalResource logicalResource = new LogicalResource( path );
416 File resourceFile = new File( managedRepository.getRepoRoot(), path );
418 new ArchivaDavResource( resourceFile.getAbsolutePath(), path,
419 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
420 request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners,
423 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
425 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
427 // force a resource not found
428 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
432 if ( !resource.isCollection() )
434 boolean previouslyExisted = resourceFile.exists();
436 // Attempt to fetch the resource from any defined proxy.
437 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
439 // At this point the incoming request can either be in default or
440 // legacy layout format.
443 // Perform an adjustment of the resource to the managed
444 // repository expected path.
445 String localResourcePath =
446 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
447 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
449 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
450 managedRepository.getRepository(), request.getRemoteAddr(),
451 activePrincipal, request.getDavSession(), archivaLocator, this,
452 mimeTypes, auditListeners, scheduler );
454 catch ( LayoutException e )
456 if ( !resourceFile.exists() )
458 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
465 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
468 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '" +
469 managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
471 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
472 logicalResource.getPath(), event, activePrincipal );
475 if ( !resourceFile.exists() )
477 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
483 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
486 * Create parent directories that don't exist when writing a file This actually makes this
487 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
488 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
489 * create the collections themselves.
492 File rootDirectory = new File( managedRepository.getRepoRoot() );
493 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
495 if ( !destDir.exists() )
498 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
500 log.debug( "Creating destination directory '" + destDir.getName() + "' (current user '" + activePrincipal + "')" );
502 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath,
503 AuditEvent.CREATE_DIR, activePrincipal );
510 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
513 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
515 ManagedRepositoryContent managedRepository;
518 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
520 catch ( RepositoryNotFoundException e )
522 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
523 + archivaLocator.getRepositoryId() );
525 catch ( RepositoryException e )
527 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
530 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
531 if ( logicalResource.startsWith( "/" ) )
533 logicalResource = logicalResource.substring( 1 );
535 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
536 DavResource resource =
537 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
538 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
540 resource.addLockManager( lockManager );
544 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
545 LogicalResource resource )
548 String path = resource.getPath();
549 if ( repositoryRequest.isSupportFile( path ) )
551 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
553 return ( proxiedFile != null );
556 // Is it a Metadata resource?
557 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
559 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
562 // Not any of the above? Then it's gotta be an artifact reference.
565 // Get the artifact reference in a layout neutral way.
566 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
568 if ( artifact != null )
570 applyServerSideRelocation( managedRepository, artifact );
572 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
574 resource.setPath( managedRepository.toPath( artifact ) );
576 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + "'" );
578 return ( proxiedFile != null );
581 catch ( LayoutException e )
585 catch ( ProxyDownloadException e )
587 log.error( e.getMessage(), e );
588 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
594 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
595 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
598 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
599 * metadatas and serving the expected artifact.
601 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
602 throws ProxyDownloadException
604 if ( "pom".equals( artifact.getType() ) )
609 // Build the artifact POM reference
610 ArtifactReference pomReference = new ArtifactReference();
611 pomReference.setGroupId( artifact.getGroupId() );
612 pomReference.setArtifactId( artifact.getArtifactId() );
613 pomReference.setVersion( artifact.getVersion() );
614 pomReference.setType( "pom" );
616 // Get the artifact POM from proxied repositories if needed
617 connectors.fetchFromProxies( managedRepository, pomReference );
619 // Open and read the POM from the managed repo
620 File pom = managedRepository.toFile( pomReference );
629 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
630 FileReader reader = new FileReader( pom );
634 model = new MavenXpp3Reader().read( reader );
638 if ( reader != null )
644 DistributionManagement dist = model.getDistributionManagement();
647 Relocation relocation = dist.getRelocation();
648 if ( relocation != null )
650 // artifact is relocated : update the repositoryPath
651 if ( relocation.getGroupId() != null )
653 artifact.setGroupId( relocation.getGroupId() );
655 if ( relocation.getArtifactId() != null )
657 artifact.setArtifactId( relocation.getArtifactId() );
659 if ( relocation.getVersion() != null )
661 artifact.setVersion( relocation.getVersion() );
666 catch ( FileNotFoundException e )
668 // Artifact has no POM in repo : ignore
670 catch ( IOException e )
672 // Unable to read POM : ignore.
674 catch ( XmlPullParserException e )
676 // Invalid POM : ignore
681 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
684 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
685 event.setRemoteIP( remoteIP );
687 for ( AuditListener listener : auditListeners )
689 listener.auditEvent( event );
693 public void addAuditListener( AuditListener listener )
695 this.auditListeners.add( listener );
698 public void clearAuditListeners()
700 this.auditListeners.clear();
703 public void removeAuditListener( AuditListener listener )
705 this.auditListeners.remove( listener );
708 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
710 // [MRM-503] - Metadata file need Pragma:no-cache response
712 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
714 response.addHeader( "Pragma", "no-cache" );
715 response.addHeader( "Cache-Control", "no-cache" );
718 // We need to specify this so connecting wagons can work correctly
719 response.addDateHeader( "last-modified", resource.getModificationTime() );
721 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
724 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
727 if ( !( locator instanceof ArchivaDavResourceLocator ) )
729 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
730 "Locator does not implement RepositoryLocator" );
734 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
736 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
739 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
741 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
742 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
744 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
746 return archivaLocator;
749 private static class LogicalResource
753 public LogicalResource( String path )
758 public String getPath()
763 public void setPath( String path )
769 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
774 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
775 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
777 return servletAuth.isAuthenticated( request, result )
778 && servletAuth.isAuthorized( request, securitySession, repositoryId,
779 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
781 catch ( AuthenticationException e )
783 // safety check for MRM-911
784 String guest = UserManager.GUEST_USERNAME;
787 if ( servletAuth.isAuthorized(
789 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
790 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
795 catch ( UnauthorizedException ae )
797 throw new UnauthorizedDavException( repositoryId,
798 "You are not authenticated and authorized to access any repository." );
801 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
803 catch ( MustChangePasswordException e )
805 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
807 catch ( AccountLockedException e )
809 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
811 catch ( AuthorizationException e )
813 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
814 "Fatal Authorization Subsystem Error." );
816 catch ( UnauthorizedException e )
818 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
822 private DavResource getResource( DavServletRequest request, List<String> repositories,
823 ArchivaDavResourceLocator locator )
826 List<File> mergedRepositoryContents = new ArrayList<File>();
827 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
828 if ( path.startsWith( "/" ) )
830 path = path.substring( 1 );
832 LogicalResource logicalResource = new LogicalResource( path );
835 // if the current user logged in has permission to any of the repositories, allow user to
836 // browse the repo group but displaying only the repositories which the user has permission to access.
837 // otherwise, prompt for authentication.
839 String activePrincipal = getActivePrincipal( request );
841 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
845 for ( String repository : repositories )
847 ManagedRepositoryContent managedRepository = null;
851 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
853 catch ( RepositoryNotFoundException e )
855 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
856 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
858 catch ( RepositoryException e )
860 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
861 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
864 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
865 if ( resourceFile.exists() )
867 // for prompted authentication
868 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
872 if ( isAuthorized( request, repository ) )
874 mergedRepositoryContents.add( resourceFile );
875 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
878 catch ( DavException e )
880 // TODO: review exception handling
881 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
882 + "': " + e.getMessage() );
887 // for the current user logged in
890 if ( servletAuth.isAuthorized( activePrincipal, repository,
891 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
893 mergedRepositoryContents.add( resourceFile );
894 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
897 catch ( UnauthorizedException e )
899 // TODO: review exception handling
900 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
901 + "': " + e.getMessage() );
909 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
912 ArchivaVirtualDavResource resource =
913 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
916 // compatibility with MRM-440 to ensure browsing the repository group works ok
917 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
919 throw new BrowserRedirectException( resource.getHref() );
925 protected String getActivePrincipal( DavServletRequest request )
927 User sessionUser = httpAuth.getSessionUser( request.getSession() );
928 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
932 * Check if the current user is authorized to access any of the repos
935 * @param repositories
936 * @param activePrincipal
939 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
941 boolean allow = false;
943 // if securitySession != null, it means that the user was prompted for authentication
944 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
946 for ( String repository : repositories )
950 if ( isAuthorized( request, repository ) )
956 catch ( DavException e )
964 for ( String repository : repositories )
968 if ( servletAuth.isAuthorized( activePrincipal, repository,
969 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
975 catch ( UnauthorizedException e )
985 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
986 throws RepositoryMetadataException, DigesterException, IOException
988 File outputFile = new File( outputFilename );
989 if ( outputFile.exists() )
991 FileUtils.deleteQuietly( outputFile );
994 outputFile.getParentFile().mkdirs();
995 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
997 createChecksumFile( outputFilename, digestSha1 );
998 createChecksumFile( outputFilename, digestMd5 );
1003 private void createChecksumFile( String path, Digester digester )
1004 throws DigesterException, IOException
1006 File checksumFile = new File( path + digester.getFilenameExtension() );
1007 if ( !checksumFile.exists() )
1009 FileUtils.deleteQuietly( checksumFile );
1010 checksum.createChecksum( new File( path ), digester );
1012 else if ( !checksumFile.isFile() )
1014 log.error( "Checksum file is not a file." );
1018 private boolean isProjectReference( String requestedResource )
1022 metadataTools.toVersionedReference( requestedResource );
1025 catch ( RepositoryMetadataException re )
1031 public void setServletAuth( ServletAuthenticator servletAuth )
1033 this.servletAuth = servletAuth;
1036 public void setHttpAuth( HttpAuthenticator httpAuth )
1038 this.httpAuth = httpAuth;
1041 public void setScheduler( ArchivaTaskScheduler scheduler )
1043 this.scheduler = scheduler;
1046 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1048 this.archivaConfiguration = archivaConfiguration;
1051 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1053 this.repositoryFactory = repositoryFactory;
1056 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1058 this.repositoryRequest = repositoryRequest;