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 // handle browse requests for virtual repos
195 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
197 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
202 processRepositoryGroup( request, archivaLocator, repoGroupConfig.getRepositories(),
203 activePrincipal, 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 );
224 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
226 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
227 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
230 String requestedResource = request.getRequestURI();
232 // MRM-872 : merge all available metadata
233 // merge metadata only when requested via the repo group
234 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) )
235 && repoGroupConfig != null )
237 // this should only be at the project level not version level!
238 if ( isProjectReference( requestedResource ) )
240 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
241 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
243 ArchivaDavResource res = (ArchivaDavResource) resource;
245 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
246 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
248 // for MRM-872 handle checksums of the merged metadata files
249 if ( repositoryRequest.isSupportFile( requestedResource ) )
251 File metadataChecksum =
252 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
253 if ( metadataChecksum.exists() )
255 LogicalResource logicalResource =
256 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
259 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
260 null, request.getRemoteAddr(), activePrincipal,
261 request.getDavSession(), archivaLocator, this, mimeTypes,
262 auditListeners, scheduler );
267 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
269 // merge the metadata of all repos under group
270 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
271 for ( String resourceAbsPath : resourcesInAbsolutePath )
275 File metadataFile = new File( resourceAbsPath );
276 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
277 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
279 catch ( RepositoryMetadataException r )
281 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
282 "Error occurred while reading metadata file." );
288 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
290 LogicalResource logicalResource =
291 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
294 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
295 null, request.getRemoteAddr(), activePrincipal,
296 request.getDavSession(), archivaLocator, this, mimeTypes,
297 auditListeners, scheduler );
299 catch ( RepositoryMetadataException r )
301 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
302 "Error occurred while writing metadata file." );
304 catch ( IOException ie )
306 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
307 "Error occurred while generating checksum files." );
309 catch ( DigesterException de )
311 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
312 "Error occurred while generating checksum files." );
319 setHeaders( response, locator, resource );
321 // compatibility with MRM-440 to ensure browsing the repository works ok
322 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
324 throw new BrowserRedirectException( resource.getHref() );
326 resource.addLockManager( lockManager );
330 private DavResource processRepositoryGroup( final DavServletRequest request,
331 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
332 String activePrincipal, List<String> resourcesInAbsolutePath )
335 DavResource resource = null;
336 DavException storedException = null;
338 for ( String repositoryId : repositories )
340 ManagedRepositoryContent managedRepository = null;
344 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
346 catch ( RepositoryNotFoundException e )
348 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
350 catch ( RepositoryException e )
352 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
357 DavResource updatedResource =
358 processRepository( request, archivaLocator, activePrincipal, managedRepository );
359 if ( resource == null )
361 resource = updatedResource;
364 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
365 if ( logicalResource.endsWith( "/" ) )
367 logicalResource = logicalResource.substring( 1 );
369 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
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 DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
392 String activePrincipal, ManagedRepositoryContent managedRepository )
395 DavResource resource = null;
396 if ( isAuthorized( request, managedRepository.getId() ) )
398 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
399 if ( path.startsWith( "/" ) )
401 path = path.substring( 1 );
403 LogicalResource logicalResource = new LogicalResource( path );
405 File resourceFile = new File( managedRepository.getRepoRoot(), path );
407 new ArchivaDavResource( resourceFile.getAbsolutePath(), path,
408 managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
409 request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners,
412 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
414 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
416 // force a resource not found
417 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
421 if ( !resource.isCollection() )
423 boolean previouslyExisted = resourceFile.exists();
425 // Attempt to fetch the resource from any defined proxy.
426 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
428 // At this point the incoming request can either be in default or
429 // legacy layout format.
432 // Perform an adjustment of the resource to the managed
433 // repository expected path.
434 String localResourcePath =
435 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
436 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
438 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
439 managedRepository.getRepository(), request.getRemoteAddr(),
440 activePrincipal, request.getDavSession(), archivaLocator, this,
441 mimeTypes, auditListeners, scheduler );
443 catch ( LayoutException e )
445 if ( !resourceFile.exists() )
447 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
454 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
456 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
457 logicalResource.getPath(), event, activePrincipal );
460 if ( !resourceFile.exists() )
462 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
468 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
471 * Create parent directories that don't exist when writing a file This actually makes this
472 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
473 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
474 * create the collections themselves.
477 File rootDirectory = new File( managedRepository.getRepoRoot() );
478 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
480 if ( !destDir.exists() )
483 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
484 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath,
485 AuditEvent.CREATE_DIR, activePrincipal );
492 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
495 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
497 ManagedRepositoryContent managedRepository;
500 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
502 catch ( RepositoryNotFoundException e )
504 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
505 + archivaLocator.getRepositoryId() );
507 catch ( RepositoryException e )
509 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
512 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
513 if ( logicalResource.startsWith( "/" ) )
515 logicalResource = logicalResource.substring( 1 );
517 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
518 DavResource resource =
519 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
520 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
522 resource.addLockManager( lockManager );
526 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
527 LogicalResource resource )
530 String path = resource.getPath();
531 if ( repositoryRequest.isSupportFile( path ) )
533 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
535 return ( proxiedFile != null );
538 // Is it a Metadata resource?
539 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
541 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
544 // Not any of the above? Then it's gotta be an artifact reference.
547 // Get the artifact reference in a layout neutral way.
548 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
550 if ( artifact != null )
552 applyServerSideRelocation( managedRepository, artifact );
554 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
556 resource.setPath( managedRepository.toPath( artifact ) );
558 return ( proxiedFile != null );
561 catch ( LayoutException e )
565 catch ( ProxyDownloadException e )
567 log.error( e.getMessage(), e );
568 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
574 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
575 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
578 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
579 * metadatas and serving the expected artifact.
581 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
582 throws ProxyDownloadException
584 if ( "pom".equals( artifact.getType() ) )
589 // Build the artifact POM reference
590 ArtifactReference pomReference = new ArtifactReference();
591 pomReference.setGroupId( artifact.getGroupId() );
592 pomReference.setArtifactId( artifact.getArtifactId() );
593 pomReference.setVersion( artifact.getVersion() );
594 pomReference.setType( "pom" );
596 // Get the artifact POM from proxied repositories if needed
597 connectors.fetchFromProxies( managedRepository, pomReference );
599 // Open and read the POM from the managed repo
600 File pom = managedRepository.toFile( pomReference );
609 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
610 FileReader reader = new FileReader( pom );
614 model = new MavenXpp3Reader().read( reader );
618 if ( reader != null )
624 DistributionManagement dist = model.getDistributionManagement();
627 Relocation relocation = dist.getRelocation();
628 if ( relocation != null )
630 // artifact is relocated : update the repositoryPath
631 if ( relocation.getGroupId() != null )
633 artifact.setGroupId( relocation.getGroupId() );
635 if ( relocation.getArtifactId() != null )
637 artifact.setArtifactId( relocation.getArtifactId() );
639 if ( relocation.getVersion() != null )
641 artifact.setVersion( relocation.getVersion() );
646 catch ( FileNotFoundException e )
648 // Artifact has no POM in repo : ignore
650 catch ( IOException e )
652 // Unable to read POM : ignore.
654 catch ( XmlPullParserException e )
656 // Invalid POM : ignore
661 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
664 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
665 event.setRemoteIP( remoteIP );
667 for ( AuditListener listener : auditListeners )
669 listener.auditEvent( event );
673 public void addAuditListener( AuditListener listener )
675 this.auditListeners.add( listener );
678 public void clearAuditListeners()
680 this.auditListeners.clear();
683 public void removeAuditListener( AuditListener listener )
685 this.auditListeners.remove( listener );
688 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
690 // [MRM-503] - Metadata file need Pragma:no-cache response
692 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
694 response.addHeader( "Pragma", "no-cache" );
695 response.addHeader( "Cache-Control", "no-cache" );
698 // We need to specify this so connecting wagons can work correctly
699 response.addDateHeader( "last-modified", resource.getModificationTime() );
701 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
704 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
707 if ( !( locator instanceof ArchivaDavResourceLocator ) )
709 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
710 "Locator does not implement RepositoryLocator" );
714 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
716 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
719 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
721 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
722 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
724 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
726 return archivaLocator;
729 private static class LogicalResource
733 public LogicalResource( String path )
738 public String getPath()
743 public void setPath( String path )
749 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
754 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
755 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
757 return servletAuth.isAuthenticated( request, result )
758 && servletAuth.isAuthorized( request, securitySession, repositoryId,
759 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
761 catch ( AuthenticationException e )
763 // safety check for MRM-911
764 String guest = UserManager.GUEST_USERNAME;
767 if ( servletAuth.isAuthorized(
769 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
770 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
775 catch ( UnauthorizedException ae )
777 throw new UnauthorizedDavException( repositoryId,
778 "You are not authenticated and authorized to access any repository." );
781 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
783 catch ( MustChangePasswordException e )
785 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
787 catch ( AccountLockedException e )
789 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
791 catch ( AuthorizationException e )
793 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
794 "Fatal Authorization Subsystem Error." );
796 catch ( UnauthorizedException e )
798 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
802 private DavResource getResource( DavServletRequest request, List<String> repositories,
803 ArchivaDavResourceLocator locator )
806 List<File> mergedRepositoryContents = new ArrayList<File>();
807 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
808 if ( path.startsWith( "/" ) )
810 path = path.substring( 1 );
812 LogicalResource logicalResource = new LogicalResource( path );
815 // if the current user logged in has permission to any of the repositories, allow user to
816 // browse the repo group but displaying only the repositories which the user has permission to access.
817 // otherwise, prompt for authentication.
819 String activePrincipal = getActivePrincipal( request );
821 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
825 for ( String repository : repositories )
827 ManagedRepositoryContent managedRepository = null;
831 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
833 catch ( RepositoryNotFoundException e )
835 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
836 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
838 catch ( RepositoryException e )
840 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
841 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
844 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
845 if ( resourceFile.exists() )
847 // for prompted authentication
848 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
852 if ( isAuthorized( request, repository ) )
854 mergedRepositoryContents.add( resourceFile );
857 catch ( DavException e )
859 // TODO: review exception handling
860 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
861 + "': " + e.getMessage() );
866 // for the current user logged in
869 if ( servletAuth.isAuthorized( activePrincipal, repository,
870 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
872 mergedRepositoryContents.add( resourceFile );
875 catch ( UnauthorizedException e )
877 // TODO: review exception handling
878 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
879 + "': " + e.getMessage() );
887 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
890 ArchivaVirtualDavResource resource =
891 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
894 // compatibility with MRM-440 to ensure browsing the repository group works ok
895 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
897 throw new BrowserRedirectException( resource.getHref() );
903 private String getActivePrincipal( DavServletRequest request )
905 User sessionUser = httpAuth.getSessionUser( request.getSession() );
906 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
910 * Check if the current user is authorized to access any of the repos
913 * @param repositories
914 * @param activePrincipal
917 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
919 boolean allow = false;
921 // if securitySession != null, it means that the user was prompted for authentication
922 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
924 for ( String repository : repositories )
928 if ( isAuthorized( request, repository ) )
934 catch ( DavException e )
942 for ( String repository : repositories )
946 if ( servletAuth.isAuthorized( activePrincipal, repository,
947 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
953 catch ( UnauthorizedException e )
963 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
964 throws RepositoryMetadataException, DigesterException, IOException
966 File outputFile = new File( outputFilename );
967 if ( outputFile.exists() )
969 FileUtils.deleteQuietly( outputFile );
972 outputFile.getParentFile().mkdirs();
973 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
975 createChecksumFile( outputFilename, digestSha1 );
976 createChecksumFile( outputFilename, digestMd5 );
981 private void createChecksumFile( String path, Digester digester )
982 throws DigesterException, IOException
984 File checksumFile = new File( path + digester.getFilenameExtension() );
985 if ( !checksumFile.exists() )
987 FileUtils.deleteQuietly( checksumFile );
988 checksum.createChecksum( new File( path ), digester );
990 else if ( !checksumFile.isFile() )
992 log.error( "Checksum file is not a file." );
996 private boolean isProjectReference( String requestedResource )
1000 metadataTools.toVersionedReference( requestedResource );
1003 catch ( RepositoryMetadataException re )
1009 public void setServletAuth( ServletAuthenticator servletAuth )
1011 this.servletAuth = servletAuth;
1014 public void setHttpAuth( HttpAuthenticator httpAuth )
1016 this.httpAuth = httpAuth;
1019 public void setScheduler( ArchivaTaskScheduler scheduler )
1021 this.scheduler = scheduler;