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.HashMap;
28 import java.util.List;
31 import javax.servlet.http.HttpServletResponse;
33 import org.apache.commons.io.FileUtils;
34 import org.apache.commons.lang.StringUtils;
35 import org.apache.jackrabbit.webdav.DavException;
36 import org.apache.jackrabbit.webdav.DavResource;
37 import org.apache.jackrabbit.webdav.DavResourceFactory;
38 import org.apache.jackrabbit.webdav.DavResourceLocator;
39 import org.apache.jackrabbit.webdav.DavServletRequest;
40 import org.apache.jackrabbit.webdav.DavServletResponse;
41 import org.apache.jackrabbit.webdav.DavSession;
42 import org.apache.jackrabbit.webdav.lock.LockManager;
43 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
44 import org.apache.maven.archiva.common.utils.PathUtil;
45 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
46 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
47 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.maven.archiva.model.ArtifactReference;
49 import org.apache.maven.archiva.model.VersionedReference;
50 import org.apache.maven.archiva.policies.ProxyDownloadException;
51 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
52 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
53 import org.apache.maven.archiva.repository.RepositoryContentFactory;
54 import org.apache.maven.archiva.repository.RepositoryException;
55 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
56 import org.apache.maven.archiva.repository.audit.AuditEvent;
57 import org.apache.maven.archiva.repository.audit.AuditListener;
58 import org.apache.maven.archiva.repository.audit.Auditable;
59 import org.apache.maven.archiva.repository.content.RepositoryRequest;
60 import org.apache.maven.archiva.repository.layout.LayoutException;
61 import org.apache.maven.archiva.repository.metadata.MetadataTools;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
64 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
65 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
66 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
67 import org.apache.maven.archiva.security.ArchivaXworkUser;
68 import org.apache.maven.archiva.security.ServletAuthenticator;
69 import org.apache.maven.archiva.webdav.util.MimeTypes;
70 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
71 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
72 import org.apache.maven.model.DistributionManagement;
73 import org.apache.maven.model.Model;
74 import org.apache.maven.model.Relocation;
75 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
76 import org.codehaus.plexus.digest.ChecksumFile;
77 import org.codehaus.plexus.digest.Digester;
78 import org.codehaus.plexus.digest.DigesterException;
79 import org.codehaus.plexus.redback.authentication.AuthenticationException;
80 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
81 import org.codehaus.plexus.redback.authorization.AuthorizationException;
82 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
83 import org.codehaus.plexus.redback.policy.AccountLockedException;
84 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
85 import org.codehaus.plexus.redback.system.SecuritySession;
86 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
87 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
88 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
92 import com.opensymphony.xwork2.ActionContext;
95 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
97 public class ArchivaDavResourceFactory
98 implements DavResourceFactory, Auditable
100 private static final String PROXIED_SUFFIX = " (proxied)";
102 private static final String HTTP_PUT_METHOD = "PUT";
104 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
107 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
109 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
112 * @plexus.requirement
114 private RepositoryContentFactory repositoryFactory;
117 * @plexus.requirement
119 private RepositoryRequest repositoryRequest;
122 * @plexus.requirement role-hint="default"
124 private RepositoryProxyConnectors connectors;
127 * @plexus.requirement
129 private MetadataTools metadataTools;
132 * @plexus.requirement
134 private MimeTypes mimeTypes;
137 * @plexus.requirement
139 private ArchivaConfiguration archivaConfiguration;
142 * @plexus.requirement
144 private ServletAuthenticator servletAuth;
147 * @plexus.requirement role-hint="basic"
149 private HttpAuthenticator httpAuth;
152 * Lock Manager - use simple implementation from JackRabbit
154 private final LockManager lockManager = new SimpleLockManager();
157 * @plexus.requirement
159 private RepositoryContentConsumers consumers;
162 * @plexus.requirement
164 private ChecksumFile checksum;
167 * @plexus.requirement role-hint="sha1"
169 private Digester digestSha1;
172 * @plexus.requirement role-hint="md5";
174 private Digester digestMd5;
177 * @plexus.requirement
179 private ArchivaXworkUser archivaXworkUser;
181 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
182 final DavServletResponse response )
185 checkLocatorIsInstanceOfRepositoryLocator( locator );
186 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
188 RepositoryGroupConfiguration repoGroupConfig =
189 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
190 List<String> repositories = new ArrayList<String>();
192 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
193 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
195 if ( repoGroupConfig != null )
197 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
199 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
200 "Write method not allowed for repository groups." );
202 repositories.addAll( repoGroupConfig.getRepositories() );
204 // handle browse requests for virtual repos
205 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
207 return getResource( request, repositories, archivaLocator );
212 repositories.add( archivaLocator.getRepositoryId() );
215 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
216 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
218 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
221 List<DavResource> availableResources = new ArrayList<DavResource>();
222 List<String> resourcesInAbsolutePath = new ArrayList<String>();
223 DavException e = null;
225 for ( String repositoryId : repositories )
227 ManagedRepositoryContent managedRepository = null;
231 managedRepository = getManagedRepository( repositoryId );
233 catch ( DavException de )
235 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
236 repositoryId + ">" );
239 DavResource resource = null;
241 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
243 if ( managedRepository != null )
247 if( isAuthorized( request, repositoryId ) )
249 LogicalResource logicalResource =
250 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
254 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
259 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
263 catch ( DavException de )
269 if( resource == null )
271 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
275 availableResources.add( resource );
277 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
278 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
283 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
288 if ( availableResources.isEmpty() )
293 String requestedResource = request.getRequestURI();
295 // MRM-872 : merge all available metadata
296 // merge metadata only when requested via the repo group
297 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
298 repoGroupConfig != null )
300 // this should only be at the project level not version level!
301 if( isProjectReference( requestedResource ) )
303 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
304 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
306 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
307 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
308 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
310 // for MRM-872 handle checksums of the merged metadata files
311 if( repositoryRequest.isSupportFile( requestedResource ) )
313 File metadataChecksum = new File( filePath + "."
314 + StringUtils.substringAfterLast( requestedResource, "." ) );
315 if( metadataChecksum.exists() )
317 LogicalResource logicalResource =
318 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
320 ArchivaDavResource metadataChecksumResource =
321 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
322 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
323 mimeTypes, auditListeners, consumers, archivaXworkUser );
324 availableResources.add( 0, metadataChecksumResource );
328 { // merge the metadata of all repos under group
329 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
330 for ( String resourceAbsPath : resourcesInAbsolutePath )
334 File metadataFile = new File( resourceAbsPath );
335 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
336 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
338 catch ( RepositoryMetadataException r )
340 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
341 "Error occurred while reading metadata file." );
347 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
349 LogicalResource logicalResource =
350 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
352 ArchivaDavResource metadataResource =
353 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
354 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
355 mimeTypes, auditListeners, consumers, archivaXworkUser );
356 availableResources.add( 0, metadataResource );
358 catch ( RepositoryMetadataException r )
360 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
361 "Error occurred while writing metadata file." );
363 catch ( IOException ie )
365 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
366 "Error occurred while generating checksum files." );
368 catch ( DigesterException de )
370 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
371 "Error occurred while generating checksum files." );
377 DavResource resource = availableResources.get( 0 );
378 setHeaders(response, locator, resource );
380 // compatibility with MRM-440 to ensure browsing the repository works ok
381 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
383 throw new BrowserRedirectException( resource.getHref() );
385 resource.addLockManager(lockManager);
389 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
392 checkLocatorIsInstanceOfRepositoryLocator( locator );
393 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
395 DavResource resource = null;
396 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
398 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
399 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
400 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
402 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
403 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
404 auditListeners, consumers, archivaXworkUser );
406 resource.addLockManager(lockManager);
410 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
411 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
414 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
416 //MRM-893, dont send back a file when user intentionally wants a directory
417 if ( locator.getHref( false ).endsWith( "/" ) )
419 if ( ! resourceFile.isDirectory() )
421 //force a resource not found
426 ArchivaDavResource resource =
427 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
428 managedRepository.getRepository(), request.getRemoteAddr(),
429 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers, archivaXworkUser );
431 if ( !resource.isCollection() )
433 boolean previouslyExisted = resourceFile.exists();
435 // At this point the incoming request can either be in default or
436 // legacy layout format.
437 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
441 // Perform an adjustment of the resource to the managed
442 // repository expected path.
443 String localResourcePath =
444 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
445 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
447 catch ( LayoutException e )
449 if ( previouslyExisted )
453 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
456 // Attempt to fetch the resource from any defined proxy.
459 String repositoryId = locator.getRepositoryId();
460 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
461 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event );
464 if ( !resourceFile.exists() )
471 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
472 managedRepository.getRepository(), request.getRemoteAddr(),
473 request.getDavSession(), locator, this, mimeTypes, auditListeners,
474 consumers, archivaXworkUser );
480 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
481 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
485 * Create parent directories that don't exist when writing a file This actually makes this implementation not
486 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
487 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
490 File rootDirectory = new File( managedRepository.getRepoRoot() );
491 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
493 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
496 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
497 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
500 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
502 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
503 managedRepository.getRepository(), request.getRemoteAddr(),
504 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers, archivaXworkUser );
507 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
508 LogicalResource resource )
511 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
513 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
515 return ( proxiedFile != null );
518 // Is it a Metadata resource?
519 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
521 return connectors.fetchMetatadaFromProxies(managedRepository, resource.getPath()) != null;
524 // Not any of the above? Then it's gotta be an artifact reference.
527 // Get the artifact reference in a layout neutral way.
528 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
530 if ( artifact != null )
532 applyServerSideRelocation( managedRepository, artifact );
534 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
536 resource.setPath( managedRepository.toPath( artifact ) );
538 return ( proxiedFile != null );
541 catch ( LayoutException e )
545 catch ( ProxyDownloadException e )
547 log.error( e.getMessage(), e );
548 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
554 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
555 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
558 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
559 * metadatas and serving the expected artifact.
561 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
562 throws ProxyDownloadException
564 if ( "pom".equals( artifact.getType() ) )
569 // Build the artifact POM reference
570 ArtifactReference pomReference = new ArtifactReference();
571 pomReference.setGroupId( artifact.getGroupId() );
572 pomReference.setArtifactId( artifact.getArtifactId() );
573 pomReference.setVersion( artifact.getVersion() );
574 pomReference.setType( "pom" );
576 // Get the artifact POM from proxied repositories if needed
577 connectors.fetchFromProxies( managedRepository, pomReference );
579 // Open and read the POM from the managed repo
580 File pom = managedRepository.toFile( pomReference );
589 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
590 FileReader reader = new FileReader( pom );
594 model = new MavenXpp3Reader().read( reader );
604 DistributionManagement dist = model.getDistributionManagement();
607 Relocation relocation = dist.getRelocation();
608 if ( relocation != null )
610 // artifact is relocated : update the repositoryPath
611 if ( relocation.getGroupId() != null )
613 artifact.setGroupId( relocation.getGroupId() );
615 if ( relocation.getArtifactId() != null )
617 artifact.setArtifactId( relocation.getArtifactId() );
619 if ( relocation.getVersion() != null )
621 artifact.setVersion( relocation.getVersion() );
626 catch ( FileNotFoundException e )
628 // Artifact has no POM in repo : ignore
630 catch ( IOException e )
632 // Unable to read POM : ignore.
634 catch ( XmlPullParserException e )
636 // Invalid POM : ignore
641 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
643 String activePrincipal = archivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
644 AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
645 event.setRemoteIP( remoteIP );
647 for ( AuditListener listener : auditListeners )
649 listener.auditEvent( event );
653 public void addAuditListener( AuditListener listener )
655 this.auditListeners.add( listener );
658 public void clearAuditListeners()
660 this.auditListeners.clear();
663 public void removeAuditListener( AuditListener listener )
665 this.auditListeners.remove( listener );
668 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
670 // [MRM-503] - Metadata file need Pragma:no-cache response
672 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
674 response.addHeader( "Pragma", "no-cache" );
675 response.addHeader( "Cache-Control", "no-cache" );
678 //We need to specify this so connecting wagons can work correctly
679 response.addDateHeader("last-modified", resource.getModificationTime());
681 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
684 private ManagedRepositoryContent getManagedRepository( String respositoryId )
687 if ( respositoryId != null )
691 return repositoryFactory.getManagedRepositoryContent( respositoryId );
693 catch ( RepositoryNotFoundException e )
695 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
697 catch ( RepositoryException e )
699 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
705 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
708 if ( !( locator instanceof RepositoryLocator ) )
710 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
711 "Locator does not implement RepositoryLocator" );
715 class LogicalResource
719 public LogicalResource( String path )
724 public String getPath()
729 public void setPath( String path )
735 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
740 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
741 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
743 return servletAuth.isAuthenticated( request, result ) &&
744 servletAuth.isAuthorized( request, securitySession, repositoryId,
745 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
747 catch ( AuthenticationException e )
749 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
751 // safety check for MRM-911
752 String guest = archivaXworkUser.getGuest();
755 if( servletAuth.isAuthorized( guest,
756 ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId(), isPut ) )
761 catch ( UnauthorizedException ae )
763 throw new UnauthorizedDavException( repositoryId,
764 "You are not authenticated and authorized to access any repository." );
767 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
769 catch ( MustChangePasswordException e )
771 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
773 catch ( AccountLockedException e )
775 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
777 catch ( AuthorizationException e )
779 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
780 "Fatal Authorization Subsystem Error." );
782 catch ( UnauthorizedException e )
784 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
788 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
791 List<File> mergedRepositoryContents = new ArrayList<File>();
792 LogicalResource logicalResource =
793 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
796 // if the current user logged in has permission to any of the repositories, allow user to
797 // browse the repo group but displaying only the repositories which the user has permission to access.
798 // otherwise, prompt for authentication.
800 // put the current session in the session map which will be passed to ArchivaXworkUser
801 Map<String, Object> sessionMap = new HashMap<String, Object>();
802 if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
804 sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
805 request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
808 String activePrincipal = archivaXworkUser.getActivePrincipal( sessionMap );
809 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
813 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
815 for( String repository : repositories )
817 // for prompted authentication
818 if( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
822 if( isAuthorized( request, repository ) )
824 getResource( locator, mergedRepositoryContents, logicalResource, repository );
827 catch ( DavException e )
834 // for the current user logged in
837 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
839 getResource( locator, mergedRepositoryContents, logicalResource, repository );
842 catch ( UnauthorizedException e )
851 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
854 ArchivaVirtualDavResource resource =
855 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
857 // compatibility with MRM-440 to ensure browsing the repository group works ok
858 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
860 throw new BrowserRedirectException( resource.getHref() );
866 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
867 LogicalResource logicalResource, String repository )
870 ManagedRepositoryContent managedRepository = null;
874 managedRepository = getManagedRepository( repository );
876 catch ( DavException de )
878 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
882 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
884 if( managedRepository != null )
886 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
887 if( resourceFile.exists() )
889 mergedRepositoryContents.add( resourceFile );
896 * Check if the current user is authorized to access any of the repos
899 * @param repositories
900 * @param activePrincipal
903 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
905 boolean allow = false;
908 // if securitySession != null, it means that the user was prompted for authentication
909 if( httpAuth.getSecuritySession( request.getSession() ) != null )
911 for( String repository : repositories )
915 if( isAuthorized( request, repository ) )
921 catch( DavException e )
929 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
930 for( String repository : repositories )
934 if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
940 catch ( UnauthorizedException e )
950 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
951 throws RepositoryMetadataException, DigesterException, IOException
953 File outputFile = new File( outputFilename );
954 if( outputFile.exists() )
956 FileUtils.deleteQuietly( outputFile );
959 outputFile.getParentFile().mkdirs();
960 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
962 createChecksumFile( outputFilename, digestSha1 );
963 createChecksumFile( outputFilename, digestMd5 );
968 private void createChecksumFile( String path, Digester digester )
969 throws DigesterException, IOException
971 File checksumFile = new File( path + digester.getFilenameExtension() );
972 if ( !checksumFile.exists() )
974 FileUtils.deleteQuietly( checksumFile );
975 checksum.createChecksum( new File( path ), digester );
977 else if ( !checksumFile.isFile() )
979 log.error( "Checksum file is not a file." );
983 private boolean isProjectReference( String requestedResource )
987 VersionedReference versionRef = metadataTools.toVersionedReference( requestedResource );
990 catch ( RepositoryMetadataException re )
996 public void setServletAuth( ServletAuthenticator servletAuth )
998 this.servletAuth = servletAuth;
1001 public void setHttpAuth( HttpAuthenticator httpAuth )
1003 this.httpAuth = httpAuth;