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.repository.scanner.RepositoryContentConsumers;
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 RepositoryContentConsumers consumers;
157 * @plexus.requirement
159 private ChecksumFile checksum;
162 * @plexus.requirement role-hint="sha1"
164 private Digester digestSha1;
167 * @plexus.requirement role-hint="md5";
169 private Digester digestMd5;
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 // handle browse requests for virtual repos
195 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
197 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
202 processRepositoryGroup( locator, request, archivaLocator, repoGroupConfig.getRepositories(),
203 activePrincipal, readMethod, resourcesInAbsolutePath );
208 ManagedRepositoryContent managedRepository = null;
212 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
214 catch ( RepositoryNotFoundException e )
216 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
217 + archivaLocator.getRepositoryId() );
219 catch ( RepositoryException e )
221 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
225 processRepository( locator, request, archivaLocator, readMethod, activePrincipal,
226 archivaLocator.getRepositoryId(), managedRepository );
228 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
229 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
232 String requestedResource = request.getRequestURI();
234 // MRM-872 : merge all available metadata
235 // merge metadata only when requested via the repo group
236 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) )
237 && repoGroupConfig != null )
239 // this should only be at the project level not version level!
240 if ( isProjectReference( requestedResource ) )
242 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
243 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
245 ArchivaDavResource res = (ArchivaDavResource) resource;
247 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
248 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
250 // for MRM-872 handle checksums of the merged metadata files
251 if ( repositoryRequest.isSupportFile( requestedResource ) )
253 File metadataChecksum =
254 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
255 if ( metadataChecksum.exists() )
257 LogicalResource logicalResource =
258 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
261 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
262 null, request.getRemoteAddr(), activePrincipal,
263 request.getDavSession(), archivaLocator, this, mimeTypes,
264 auditListeners, consumers );
269 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
271 // merge the metadata of all repos under group
272 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
273 for ( String resourceAbsPath : resourcesInAbsolutePath )
277 File metadataFile = new File( resourceAbsPath );
278 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
279 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
281 catch ( RepositoryMetadataException r )
283 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
284 "Error occurred while reading metadata file." );
290 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
292 LogicalResource logicalResource =
293 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
296 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
297 null, request.getRemoteAddr(), activePrincipal,
298 request.getDavSession(), archivaLocator, this, mimeTypes,
299 auditListeners, consumers );
301 catch ( RepositoryMetadataException r )
303 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
304 "Error occurred while writing metadata file." );
306 catch ( IOException ie )
308 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
309 "Error occurred while generating checksum files." );
311 catch ( DigesterException de )
313 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
314 "Error occurred while generating checksum files." );
321 setHeaders( response, locator, resource );
323 // compatibility with MRM-440 to ensure browsing the repository works ok
324 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
326 throw new BrowserRedirectException( resource.getHref() );
328 resource.addLockManager( lockManager );
332 private DavResource processRepositoryGroup( final DavResourceLocator locator, final DavServletRequest request,
333 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
334 String activePrincipal, boolean readMethod,
335 List<String> resourcesInAbsolutePath )
338 DavResource resource = null;
339 DavException storedException = null;
341 for ( String repositoryId : repositories )
343 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 resource1 =
361 processRepository( locator, request, archivaLocator, readMethod, activePrincipal, repositoryId,
363 if ( resource == null )
365 resource = resource1;
368 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
369 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
371 catch ( DavException e )
377 if ( resource == null )
379 if ( storedException != null )
381 throw storedException;
385 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
391 private DavResource processRepository( final DavResourceLocator locator, final DavServletRequest request,
392 ArchivaDavResourceLocator archivaLocator, boolean readMethod,
393 String activePrincipal, String repositoryId,
394 ManagedRepositoryContent managedRepository )
397 DavResource resource = null;
398 if ( isAuthorized( request, repositoryId ) )
400 LogicalResource logicalResource =
401 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
403 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
405 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
406 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
407 request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners,
412 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
414 // force a resource not found
415 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
419 if ( !resource.isCollection() )
421 boolean previouslyExisted = resourceFile.exists();
423 // Attempt to fetch the resource from any defined proxy.
424 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
426 // At this point the incoming request can either be in default or
427 // legacy layout format.
430 // Perform an adjustment of the resource to the managed
431 // repository expected path.
432 String localResourcePath =
433 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
434 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
436 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
437 managedRepository.getRepository(), request.getRemoteAddr(),
438 activePrincipal, request.getDavSession(), archivaLocator, this,
439 mimeTypes, auditListeners, consumers );
441 catch ( LayoutException e1 )
443 if ( !resourceFile.exists() )
445 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e1 );
451 String repositoryId1 = archivaLocator.getRepositoryId();
453 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
455 triggerAuditEvent( request.getRemoteAddr(), repositoryId1, logicalResource.getPath(),
456 event, activePrincipal );
459 if ( !resourceFile.exists() )
461 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
467 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
470 * Create parent directories that don't exist when writing a file This actually makes this
471 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
472 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
473 * create the collections themselves.
476 File rootDirectory = new File( managedRepository.getRepoRoot() );
477 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
479 if ( !destDir.exists() )
482 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
483 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath,
484 AuditEvent.CREATE_DIR, activePrincipal );
491 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
494 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
496 ManagedRepositoryContent managedRepository;
499 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
501 catch ( RepositoryNotFoundException e )
503 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
504 + archivaLocator.getRepositoryId() );
506 catch ( RepositoryException e )
508 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
511 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
512 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
513 DavResource resource =
514 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
515 davSession, archivaLocator, this, mimeTypes, auditListeners, consumers );
517 resource.addLockManager( lockManager );
521 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
522 LogicalResource resource )
525 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
527 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
529 return ( proxiedFile != null );
532 // Is it a Metadata resource?
533 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
535 return connectors.fetchMetatadaFromProxies( managedRepository, resource.getPath() ) != null;
538 // Not any of the above? Then it's gotta be an artifact reference.
541 // Get the artifact reference in a layout neutral way.
542 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
544 if ( artifact != null )
546 applyServerSideRelocation( managedRepository, artifact );
548 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
550 resource.setPath( managedRepository.toPath( artifact ) );
552 return ( proxiedFile != null );
555 catch ( LayoutException e )
559 catch ( ProxyDownloadException e )
561 log.error( e.getMessage(), e );
562 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
568 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
569 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
572 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
573 * metadatas and serving the expected artifact.
575 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
576 throws ProxyDownloadException
578 if ( "pom".equals( artifact.getType() ) )
583 // Build the artifact POM reference
584 ArtifactReference pomReference = new ArtifactReference();
585 pomReference.setGroupId( artifact.getGroupId() );
586 pomReference.setArtifactId( artifact.getArtifactId() );
587 pomReference.setVersion( artifact.getVersion() );
588 pomReference.setType( "pom" );
590 // Get the artifact POM from proxied repositories if needed
591 connectors.fetchFromProxies( managedRepository, pomReference );
593 // Open and read the POM from the managed repo
594 File pom = managedRepository.toFile( pomReference );
603 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
604 FileReader reader = new FileReader( pom );
608 model = new MavenXpp3Reader().read( reader );
612 if ( reader != null )
618 DistributionManagement dist = model.getDistributionManagement();
621 Relocation relocation = dist.getRelocation();
622 if ( relocation != null )
624 // artifact is relocated : update the repositoryPath
625 if ( relocation.getGroupId() != null )
627 artifact.setGroupId( relocation.getGroupId() );
629 if ( relocation.getArtifactId() != null )
631 artifact.setArtifactId( relocation.getArtifactId() );
633 if ( relocation.getVersion() != null )
635 artifact.setVersion( relocation.getVersion() );
640 catch ( FileNotFoundException e )
642 // Artifact has no POM in repo : ignore
644 catch ( IOException e )
646 // Unable to read POM : ignore.
648 catch ( XmlPullParserException e )
650 // Invalid POM : ignore
655 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
658 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
659 event.setRemoteIP( remoteIP );
661 for ( AuditListener listener : auditListeners )
663 listener.auditEvent( event );
667 public void addAuditListener( AuditListener listener )
669 this.auditListeners.add( listener );
672 public void clearAuditListeners()
674 this.auditListeners.clear();
677 public void removeAuditListener( AuditListener listener )
679 this.auditListeners.remove( listener );
682 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
684 // [MRM-503] - Metadata file need Pragma:no-cache response
686 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
688 response.addHeader( "Pragma", "no-cache" );
689 response.addHeader( "Cache-Control", "no-cache" );
692 // We need to specify this so connecting wagons can work correctly
693 response.addDateHeader( "last-modified", resource.getModificationTime() );
695 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
698 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
701 if ( !( locator instanceof ArchivaDavResourceLocator ) )
703 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
704 "Locator does not implement RepositoryLocator" );
708 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
710 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
713 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
715 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
716 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
718 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
720 return archivaLocator;
723 private static class LogicalResource
727 public LogicalResource( String path )
732 public String getPath()
737 public void setPath( String path )
743 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
748 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
749 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
751 return servletAuth.isAuthenticated( request, result )
752 && servletAuth.isAuthorized( request, securitySession, repositoryId,
753 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
755 catch ( AuthenticationException e )
757 // safety check for MRM-911
758 String guest = UserManager.GUEST_USERNAME;
761 if ( servletAuth.isAuthorized(
763 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
764 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
769 catch ( UnauthorizedException ae )
771 throw new UnauthorizedDavException( repositoryId,
772 "You are not authenticated and authorized to access any repository." );
775 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
777 catch ( MustChangePasswordException e )
779 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
781 catch ( AccountLockedException e )
783 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
785 catch ( AuthorizationException e )
787 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
788 "Fatal Authorization Subsystem Error." );
790 catch ( UnauthorizedException e )
792 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
796 private DavResource getResource( DavServletRequest request, List<String> repositories,
797 ArchivaDavResourceLocator locator )
800 List<File> mergedRepositoryContents = new ArrayList<File>();
801 LogicalResource logicalResource =
802 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
805 // if the current user logged in has permission to any of the repositories, allow user to
806 // browse the repo group but displaying only the repositories which the user has permission to access.
807 // otherwise, prompt for authentication.
809 String activePrincipal = getActivePrincipal( request );
811 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
815 for ( String repository : repositories )
817 ManagedRepositoryContent managedRepository = null;
821 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
823 catch ( RepositoryNotFoundException e )
825 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
826 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
828 catch ( RepositoryException e )
830 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
831 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
834 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
835 if ( resourceFile.exists() )
837 // for prompted authentication
838 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
842 if ( isAuthorized( request, repository ) )
844 mergedRepositoryContents.add( resourceFile );
847 catch ( DavException e )
849 // TODO: review exception handling
850 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
851 + "': " + e.getMessage() );
856 // for the current user logged in
859 if ( servletAuth.isAuthorized( activePrincipal, repository,
860 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
862 mergedRepositoryContents.add( resourceFile );
865 catch ( UnauthorizedException e )
867 // TODO: review exception handling
868 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
869 + "': " + e.getMessage() );
877 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
880 ArchivaVirtualDavResource resource =
881 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
884 // compatibility with MRM-440 to ensure browsing the repository group works ok
885 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
887 throw new BrowserRedirectException( resource.getHref() );
893 private String getActivePrincipal( DavServletRequest request )
895 User sessionUser = httpAuth.getSessionUser( request.getSession() );
896 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
900 * Check if the current user is authorized to access any of the repos
903 * @param repositories
904 * @param activePrincipal
907 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
909 boolean allow = false;
911 // if securitySession != null, it means that the user was prompted for authentication
912 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
914 for ( String repository : repositories )
918 if ( isAuthorized( request, repository ) )
924 catch ( DavException e )
932 for ( String repository : repositories )
936 if ( servletAuth.isAuthorized( activePrincipal, repository,
937 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
943 catch ( UnauthorizedException e )
953 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
954 throws RepositoryMetadataException, DigesterException, IOException
956 File outputFile = new File( outputFilename );
957 if ( outputFile.exists() )
959 FileUtils.deleteQuietly( outputFile );
962 outputFile.getParentFile().mkdirs();
963 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
965 createChecksumFile( outputFilename, digestSha1 );
966 createChecksumFile( outputFilename, digestMd5 );
971 private void createChecksumFile( String path, Digester digester )
972 throws DigesterException, IOException
974 File checksumFile = new File( path + digester.getFilenameExtension() );
975 if ( !checksumFile.exists() )
977 FileUtils.deleteQuietly( checksumFile );
978 checksum.createChecksum( new File( path ), digester );
980 else if ( !checksumFile.isFile() )
982 log.error( "Checksum file is not a file." );
986 private boolean isProjectReference( String requestedResource )
990 metadataTools.toVersionedReference( requestedResource );
993 catch ( RepositoryMetadataException re )
999 public void setServletAuth( ServletAuthenticator servletAuth )
1001 this.servletAuth = servletAuth;
1004 public void setHttpAuth( HttpAuthenticator httpAuth )
1006 this.httpAuth = httpAuth;