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.ProjectReference;
50 import org.apache.maven.archiva.model.VersionedReference;
51 import org.apache.maven.archiva.policies.ProxyDownloadException;
52 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
53 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
54 import org.apache.maven.archiva.repository.RepositoryContentFactory;
55 import org.apache.maven.archiva.repository.RepositoryException;
56 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
57 import org.apache.maven.archiva.repository.audit.AuditEvent;
58 import org.apache.maven.archiva.repository.audit.AuditListener;
59 import org.apache.maven.archiva.repository.audit.Auditable;
60 import org.apache.maven.archiva.repository.content.RepositoryRequest;
61 import org.apache.maven.archiva.repository.layout.LayoutException;
62 import org.apache.maven.archiva.repository.metadata.MetadataTools;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
64 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
65 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
66 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
67 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
68 import org.apache.maven.archiva.security.ArchivaXworkUser;
69 import org.apache.maven.archiva.security.ServletAuthenticator;
70 import org.apache.maven.archiva.webdav.util.MimeTypes;
71 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
72 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
73 import org.apache.maven.model.DistributionManagement;
74 import org.apache.maven.model.Model;
75 import org.apache.maven.model.Relocation;
76 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
77 import org.codehaus.plexus.digest.ChecksumFile;
78 import org.codehaus.plexus.digest.Digester;
79 import org.codehaus.plexus.digest.DigesterException;
80 import org.codehaus.plexus.redback.authentication.AuthenticationException;
81 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
82 import org.codehaus.plexus.redback.authorization.AuthorizationException;
83 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
84 import org.codehaus.plexus.redback.policy.AccountLockedException;
85 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
86 import org.codehaus.plexus.redback.system.SecuritySession;
87 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
88 import org.codehaus.plexus.redback.struts2.filter.authentication.HttpAuthenticator;
89 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
93 import com.opensymphony.xwork2.ActionContext;
96 * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
97 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
99 public class ArchivaDavResourceFactory
100 implements DavResourceFactory, Auditable
102 private static final String PROXIED_SUFFIX = " (proxied)";
104 private static final String HTTP_PUT_METHOD = "PUT";
106 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
109 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
111 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
114 * @plexus.requirement
116 private RepositoryContentFactory repositoryFactory;
119 * @plexus.requirement
121 private RepositoryRequest repositoryRequest;
124 * @plexus.requirement role-hint="default"
126 private RepositoryProxyConnectors connectors;
129 * @plexus.requirement
131 private MetadataTools metadataTools;
134 * @plexus.requirement
136 private MimeTypes mimeTypes;
139 * @plexus.requirement
141 private ArchivaConfiguration archivaConfiguration;
144 * @plexus.requirement
146 private ServletAuthenticator servletAuth;
149 * @plexus.requirement role-hint="basic"
151 private HttpAuthenticator httpAuth;
154 * Lock Manager - use simple implementation from JackRabbit
156 private final LockManager lockManager = new SimpleLockManager();
159 * @plexus.requirement
161 private RepositoryContentConsumers consumers;
164 * @plexus.requirement
166 private ChecksumFile checksum;
169 * @plexus.requirement role-hint="sha1"
171 private Digester digestSha1;
174 * @plexus.requirement role-hint="md5";
176 private Digester digestMd5;
179 * @plexus.requirement
181 private ArchivaXworkUser archivaXworkUser;
183 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
184 final DavServletResponse response )
187 checkLocatorIsInstanceOfRepositoryLocator( locator );
188 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
190 RepositoryGroupConfiguration repoGroupConfig =
191 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
192 List<String> repositories = new ArrayList<String>();
194 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
195 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
197 if ( repoGroupConfig != null )
199 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
201 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
202 "Write method not allowed for repository groups." );
204 repositories.addAll( repoGroupConfig.getRepositories() );
206 // handle browse requests for virtual repos
207 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
209 return getResource( request, repositories, archivaLocator );
214 repositories.add( archivaLocator.getRepositoryId() );
217 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
218 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
220 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
223 List<DavResource> availableResources = new ArrayList<DavResource>();
224 List<String> resourcesInAbsolutePath = new ArrayList<String>();
225 DavException e = null;
227 for ( String repositoryId : repositories )
229 ManagedRepositoryContent managedRepository = null;
233 managedRepository = getManagedRepository( repositoryId );
235 catch ( DavException de )
237 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
238 repositoryId + ">" );
241 DavResource resource = null;
243 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
245 if ( managedRepository != null )
249 if( isAuthorized( request, repositoryId ) )
251 LogicalResource logicalResource =
252 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
256 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
261 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
265 catch ( DavException de )
271 if( resource == null )
273 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
277 availableResources.add( resource );
279 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
280 resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
285 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
290 if ( availableResources.isEmpty() )
295 String requestedResource = request.getRequestURI();
297 // MRM-872 : merge all available metadata
298 // merge metadata only when requested via the repo group
299 if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) ) &&
300 repoGroupConfig != null )
302 // this should only be at the project level not version level!
303 if( isProjectReference( requestedResource ) )
305 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
306 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
308 ArchivaDavResource res = ( ArchivaDavResource ) availableResources.get( 0 );
309 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
310 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
312 // for MRM-872 handle checksums of the merged metadata files
313 if( repositoryRequest.isSupportFile( requestedResource ) )
315 File metadataChecksum = new File( filePath + "."
316 + StringUtils.substringAfterLast( requestedResource, "." ) );
317 if( metadataChecksum.exists() )
319 LogicalResource logicalResource =
320 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
322 ArchivaDavResource metadataChecksumResource =
323 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
324 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
325 mimeTypes, auditListeners, consumers, archivaXworkUser );
326 availableResources.add( 0, metadataChecksumResource );
330 { // merge the metadata of all repos under group
331 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
332 for ( String resourceAbsPath : resourcesInAbsolutePath )
336 File metadataFile = new File( resourceAbsPath );
337 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
338 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
340 catch ( RepositoryMetadataException r )
342 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
343 "Error occurred while reading metadata file." );
349 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
351 LogicalResource logicalResource =
352 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
354 ArchivaDavResource metadataResource =
355 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
356 request.getRemoteAddr(), request.getDavSession(), archivaLocator, this,
357 mimeTypes, auditListeners, consumers, archivaXworkUser );
358 availableResources.add( 0, metadataResource );
360 catch ( RepositoryMetadataException r )
362 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
363 "Error occurred while writing metadata file." );
365 catch ( IOException ie )
367 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
368 "Error occurred while generating checksum files." );
370 catch ( DigesterException de )
372 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
373 "Error occurred while generating checksum files." );
379 DavResource resource = availableResources.get( 0 );
380 setHeaders(response, locator, resource );
382 // compatibility with MRM-440 to ensure browsing the repository works ok
383 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
385 throw new BrowserRedirectException( resource.getHref() );
387 resource.addLockManager(lockManager);
391 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
394 checkLocatorIsInstanceOfRepositoryLocator( locator );
395 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
397 DavResource resource = null;
398 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
400 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
401 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
402 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
404 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
405 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
406 auditListeners, consumers, archivaXworkUser );
408 resource.addLockManager(lockManager);
412 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
413 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
416 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
418 //MRM-893, dont send back a file when user intentionally wants a directory
419 if ( locator.getHref( false ).endsWith( "/" ) )
421 if ( ! resourceFile.isDirectory() )
423 //force a resource not found
428 ArchivaDavResource resource =
429 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
430 managedRepository.getRepository(), request.getRemoteAddr(),
431 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers, archivaXworkUser );
433 if ( !resource.isCollection() )
435 boolean previouslyExisted = resourceFile.exists();
437 // At this point the incoming request can either be in default or
438 // legacy layout format.
439 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
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 catch ( LayoutException e )
451 if ( previouslyExisted )
455 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
458 // Attempt to fetch the resource from any defined proxy.
461 String repositoryId = locator.getRepositoryId();
462 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
463 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event );
466 if ( !resourceFile.exists() )
473 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
474 managedRepository.getRepository(), request.getRemoteAddr(),
475 request.getDavSession(), locator, this, mimeTypes, auditListeners,
476 consumers, archivaXworkUser );
482 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
483 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
487 * Create parent directories that don't exist when writing a file This actually makes this implementation not
488 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
489 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
492 File rootDirectory = new File( managedRepository.getRepoRoot() );
493 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
494 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
497 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
498 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
501 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
503 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
504 managedRepository.getRepository(), request.getRemoteAddr(),
505 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers, archivaXworkUser );
508 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
509 LogicalResource resource )
512 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
514 File proxiedFile = connectors.fetchFromProxies( managedRepository, resource.getPath() );
516 return ( proxiedFile != null );
519 // Is it a Metadata resource?
520 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
522 return connectors.fetchMetatadaFromProxies(managedRepository, resource.getPath()) != null;
525 // Not any of the above? Then it's gotta be an artifact reference.
528 // Get the artifact reference in a layout neutral way.
529 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
531 if ( artifact != null )
533 applyServerSideRelocation( managedRepository, artifact );
535 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
537 resource.setPath( managedRepository.toPath( artifact ) );
539 return ( proxiedFile != null );
542 catch ( LayoutException e )
546 catch ( ProxyDownloadException e )
548 log.error( e.getMessage(), e );
549 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
555 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
556 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
559 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
560 * metadatas and serving the expected artifact.
562 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
563 throws ProxyDownloadException
565 if ( "pom".equals( artifact.getType() ) )
570 // Build the artifact POM reference
571 ArtifactReference pomReference = new ArtifactReference();
572 pomReference.setGroupId( artifact.getGroupId() );
573 pomReference.setArtifactId( artifact.getArtifactId() );
574 pomReference.setVersion( artifact.getVersion() );
575 pomReference.setType( "pom" );
577 // Get the artifact POM from proxied repositories if needed
578 connectors.fetchFromProxies( managedRepository, pomReference );
580 // Open and read the POM from the managed repo
581 File pom = managedRepository.toFile( pomReference );
590 Model model = new MavenXpp3Reader().read( new FileReader( pom ) );
591 DistributionManagement dist = model.getDistributionManagement();
594 Relocation relocation = dist.getRelocation();
595 if ( relocation != null )
597 // artifact is relocated : update the repositoryPath
598 if ( relocation.getGroupId() != null )
600 artifact.setGroupId( relocation.getGroupId() );
602 if ( relocation.getArtifactId() != null )
604 artifact.setArtifactId( relocation.getArtifactId() );
606 if ( relocation.getVersion() != null )
608 artifact.setVersion( relocation.getVersion() );
613 catch ( FileNotFoundException e )
615 // Artifact has no POM in repo : ignore
617 catch ( IOException e )
619 // Unable to read POM : ignore.
621 catch ( XmlPullParserException e )
623 // Invalid POM : ignore
628 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
630 String activePrincipal = archivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
631 AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
632 event.setRemoteIP( remoteIP );
634 for ( AuditListener listener : auditListeners )
636 listener.auditEvent( event );
640 public void addAuditListener( AuditListener listener )
642 this.auditListeners.add( listener );
645 public void clearAuditListeners()
647 this.auditListeners.clear();
650 public void removeAuditListener( AuditListener listener )
652 this.auditListeners.remove( listener );
655 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
657 // [MRM-503] - Metadata file need Pragma:no-cache response
659 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
661 response.addHeader( "Pragma", "no-cache" );
662 response.addHeader( "Cache-Control", "no-cache" );
665 //We need to specify this so connecting wagons can work correctly
666 response.addDateHeader("last-modified", resource.getModificationTime());
668 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
671 private ManagedRepositoryContent getManagedRepository( String respositoryId )
674 if ( respositoryId != null )
678 return repositoryFactory.getManagedRepositoryContent( respositoryId );
680 catch ( RepositoryNotFoundException e )
682 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
684 catch ( RepositoryException e )
686 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
692 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
695 if ( !( locator instanceof RepositoryLocator ) )
697 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
698 "Locator does not implement RepositoryLocator" );
702 class LogicalResource
706 public LogicalResource( String path )
711 public String getPath()
716 public void setPath( String path )
722 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
727 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
728 SecuritySession securitySession = httpAuth.getSecuritySession();
730 return servletAuth.isAuthenticated( request, result ) &&
731 servletAuth.isAuthorized( request, securitySession, repositoryId,
732 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
734 catch ( AuthenticationException e )
736 // safety check for MRM-911
737 String guest = archivaXworkUser.getGuest();
740 if( servletAuth.isAuthorized( guest,
741 ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId() ) )
746 catch ( UnauthorizedException ae )
748 throw new UnauthorizedDavException( repositoryId,
749 "You are not authenticated and authorized to access any repository." );
752 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
754 catch ( MustChangePasswordException e )
756 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
758 catch ( AccountLockedException e )
760 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
762 catch ( AuthorizationException e )
764 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
765 "Fatal Authorization Subsystem Error." );
767 catch ( UnauthorizedException e )
769 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
773 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
776 List<File> mergedRepositoryContents = new ArrayList<File>();
777 LogicalResource logicalResource =
778 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
781 // if the current user logged in has permission to any of the repositories, allow user to
782 // browse the repo group but displaying only the repositories which the user has permission to access.
783 // otherwise, prompt for authentication.
785 // put the current session in the session map which will be passed to ArchivaXworkUser
786 Map<String, Object> sessionMap = new HashMap<String, Object>();
787 if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
789 sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
790 request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
793 String activePrincipal = archivaXworkUser.getActivePrincipal( sessionMap );
794 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
798 for( String repository : repositories )
800 // for prompted authentication
801 if( httpAuth.getSecuritySession() != null )
805 if( isAuthorized( request, repository ) )
807 getResource( locator, mergedRepositoryContents, logicalResource, repository );
810 catch ( DavException e )
817 // for the current user logged in
820 if( servletAuth.isAuthorized( activePrincipal, repository ) )
822 getResource( locator, mergedRepositoryContents, logicalResource, repository );
825 catch ( UnauthorizedException e )
834 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
837 ArchivaVirtualDavResource resource =
838 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
840 // compatibility with MRM-440 to ensure browsing the repository group works ok
841 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
843 throw new BrowserRedirectException( resource.getHref() );
849 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
850 LogicalResource logicalResource, String repository )
853 ManagedRepositoryContent managedRepository = null;
857 managedRepository = getManagedRepository( repository );
859 catch ( DavException de )
861 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
865 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
867 if( managedRepository != null )
869 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
870 if( resourceFile.exists() )
872 mergedRepositoryContents.add( resourceFile );
879 * Check if the current user is authorized to access any of the repos
882 * @param repositories
883 * @param activePrincipal
886 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
888 boolean allow = false;
891 // if securitySession != null, it means that the user was prompted for authentication
892 if( httpAuth.getSecuritySession() != null )
894 for( String repository : repositories )
898 if( isAuthorized( request, repository ) )
904 catch( DavException e )
912 for( String repository : repositories )
916 if( servletAuth.isAuthorized( activePrincipal, repository ) )
922 catch ( UnauthorizedException e )
932 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
933 throws RepositoryMetadataException, DigesterException, IOException
935 File outputFile = new File( outputFilename );
936 if( outputFile.exists() )
938 FileUtils.deleteQuietly( outputFile );
941 outputFile.getParentFile().mkdirs();
942 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
944 createChecksumFile( outputFilename, digestSha1 );
945 createChecksumFile( outputFilename, digestMd5 );
950 private void createChecksumFile( String path, Digester digester )
951 throws DigesterException, IOException
953 File checksumFile = new File( path + digester.getFilenameExtension() );
954 if ( !checksumFile.exists() )
956 FileUtils.deleteQuietly( checksumFile );
957 checksum.createChecksum( new File( path ), digester );
959 else if ( !checksumFile.isFile() )
961 log.error( "Checksum file is not a file." );
965 private boolean isProjectReference( String requestedResource )
969 VersionedReference versionRef = metadataTools.toVersionedReference( requestedResource );
972 catch ( RepositoryMetadataException re )