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.common.utils.VersionUtil;
44 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
45 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
46 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.maven.archiva.model.ArtifactReference;
48 import org.apache.maven.archiva.policies.ProxyDownloadException;
49 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
50 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
51 import org.apache.maven.archiva.repository.RepositoryContentFactory;
52 import org.apache.maven.archiva.repository.RepositoryException;
53 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
54 import org.apache.maven.archiva.repository.audit.AuditEvent;
55 import org.apache.maven.archiva.repository.audit.AuditListener;
56 import org.apache.maven.archiva.repository.audit.Auditable;
57 import org.apache.maven.archiva.repository.content.RepositoryRequest;
58 import org.apache.maven.archiva.repository.layout.LayoutException;
59 import org.apache.maven.archiva.repository.metadata.MetadataTools;
60 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
64 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
65 import org.apache.maven.archiva.security.ServletAuthenticator;
66 import org.apache.maven.archiva.webdav.util.MimeTypes;
67 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
68 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
69 import org.apache.maven.model.DistributionManagement;
70 import org.apache.maven.model.Model;
71 import org.apache.maven.model.Relocation;
72 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
73 import org.codehaus.plexus.digest.ChecksumFile;
74 import org.codehaus.plexus.digest.Digester;
75 import org.codehaus.plexus.digest.DigesterException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationException;
77 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
78 import org.codehaus.plexus.redback.authorization.AuthorizationException;
79 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
80 import org.codehaus.plexus.redback.policy.AccountLockedException;
81 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
82 import org.codehaus.plexus.redback.system.SecuritySession;
83 import org.codehaus.plexus.redback.users.User;
84 import org.codehaus.plexus.redback.users.UserManager;
85 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
86 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
91 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
93 public class ArchivaDavResourceFactory
94 implements DavResourceFactory, Auditable
96 private static final String PROXIED_SUFFIX = " (proxied)";
98 private static final String HTTP_PUT_METHOD = "PUT";
100 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
103 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
105 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
108 * @plexus.requirement
110 private RepositoryContentFactory repositoryFactory;
113 * @plexus.requirement
115 private RepositoryRequest repositoryRequest;
118 * @plexus.requirement role-hint="default"
120 private RepositoryProxyConnectors connectors;
123 * @plexus.requirement
125 private MetadataTools metadataTools;
128 * @plexus.requirement
130 private MimeTypes mimeTypes;
133 * @plexus.requirement
135 private ArchivaConfiguration archivaConfiguration;
138 * @plexus.requirement
140 private ServletAuthenticator servletAuth;
143 * @plexus.requirement role-hint="basic"
145 private HttpAuthenticator httpAuth;
148 * Lock Manager - use simple implementation from JackRabbit
150 private final LockManager lockManager = new SimpleLockManager();
153 * @plexus.requirement
155 private ChecksumFile checksum;
158 * @plexus.requirement role-hint="sha1"
160 private Digester digestSha1;
163 * @plexus.requirement role-hint="md5";
165 private Digester digestMd5;
168 * @plexus.requirement
170 private ArchivaTaskScheduler scheduler;
172 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
173 final DavServletResponse response )
176 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
178 RepositoryGroupConfiguration repoGroupConfig =
179 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
181 String activePrincipal = getActivePrincipal( request );
183 List<String> resourcesInAbsolutePath = new ArrayList<String>();
185 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
186 DavResource resource;
187 if ( repoGroupConfig != null )
191 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
192 "Write method not allowed for repository groups." );
195 log.debug( "Repository group '" + repoGroupConfig.getId() + "' accessed by '" + activePrincipal + "'" );
197 // handle browse requests for virtual repos
198 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
200 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
205 processRepositoryGroup( request, archivaLocator, repoGroupConfig.getRepositories(),
206 activePrincipal, resourcesInAbsolutePath );
211 ManagedRepositoryContent managedRepository = null;
215 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
217 catch ( RepositoryNotFoundException e )
219 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " +
220 archivaLocator.getRepositoryId() );
222 catch ( RepositoryException e )
224 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
227 log.debug( "Managed repository '" + managedRepository.getId() + "' accessed by '" + activePrincipal + "'" );
229 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
231 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
232 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
235 String requestedResource = request.getRequestURI();
237 // MRM-872 : merge all available metadata
238 // merge metadata only when requested via the repo group
239 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile( requestedResource ) ) &&
240 repoGroupConfig != null )
242 // this should only be at the project level not version level!
243 if ( isProjectReference( requestedResource ) )
245 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
246 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
248 ArchivaDavResource res = (ArchivaDavResource) resource;
250 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
251 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
253 // for MRM-872 handle checksums of the merged metadata files
254 if ( repositoryRequest.isSupportFile( requestedResource ) )
256 File metadataChecksum =
257 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
258 if ( metadataChecksum.exists() )
260 LogicalResource logicalResource =
261 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
264 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
265 null, request.getRemoteAddr(), activePrincipal,
266 request.getDavSession(), archivaLocator, this, mimeTypes,
267 auditListeners, scheduler );
272 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
274 // merge the metadata of all repos under group
275 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
276 for ( String resourceAbsPath : resourcesInAbsolutePath )
280 File metadataFile = new File( resourceAbsPath );
281 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
282 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
284 catch ( RepositoryMetadataException r )
286 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
287 "Error occurred while reading metadata file." );
293 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
295 LogicalResource logicalResource =
296 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
299 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
300 null, request.getRemoteAddr(), activePrincipal,
301 request.getDavSession(), archivaLocator, this, mimeTypes,
302 auditListeners, scheduler );
304 catch ( RepositoryMetadataException r )
306 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
307 "Error occurred while writing metadata file." );
309 catch ( IOException ie )
311 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
312 "Error occurred while generating checksum files." );
314 catch ( DigesterException de )
316 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
317 "Error occurred while generating checksum files." );
324 setHeaders( response, locator, resource );
326 // compatibility with MRM-440 to ensure browsing the repository works ok
327 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
329 throw new BrowserRedirectException( resource.getHref() );
331 resource.addLockManager( lockManager );
335 private DavResource processRepositoryGroup( final DavServletRequest request,
336 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
337 String activePrincipal, List<String> resourcesInAbsolutePath )
340 DavResource resource = null;
341 List<DavException> storedExceptions = new ArrayList<DavException>();
343 for ( String repositoryId : repositories )
345 ManagedRepositoryContent managedRepository = null;
348 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
350 catch ( RepositoryNotFoundException e )
352 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
354 catch ( RepositoryException e )
356 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
361 DavResource updatedResource =
362 processRepository( request, archivaLocator, activePrincipal, managedRepository );
363 if ( resource == null )
365 resource = updatedResource;
368 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
369 if ( logicalResource.endsWith( "/" ) )
371 logicalResource = logicalResource.substring( 1 );
373 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
375 catch ( DavException e )
377 storedExceptions.add( e );
381 if ( resource == null )
383 if ( !storedExceptions.isEmpty() )
386 for ( DavException e : storedExceptions )
388 if ( 401 == e.getErrorCode() )
394 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
398 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
404 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
405 String activePrincipal, ManagedRepositoryContent managedRepository )
408 DavResource resource = null;
409 if ( isAuthorized( request, managedRepository.getId() ) )
411 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
412 if ( path.startsWith( "/" ) )
414 path = path.substring( 1 );
416 LogicalResource logicalResource = new LogicalResource( path );
417 File resourceFile = new File( managedRepository.getRepoRoot(), path );
419 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
420 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
421 archivaLocator, this, mimeTypes, auditListeners, scheduler );
423 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
425 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
427 // force a resource not found
428 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
432 if ( !resource.isCollection() )
434 boolean previouslyExisted = resourceFile.exists();
436 // Attempt to fetch the resource from any defined proxy.
437 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
439 // At this point the incoming request can either be in default or
440 // legacy layout format.
443 // Perform an adjustment of the resource to the managed
444 // repository expected path.
445 String localResourcePath =
446 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
447 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
449 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
450 managedRepository.getRepository(), request.getRemoteAddr(),
451 activePrincipal, request.getDavSession(), archivaLocator, this,
452 mimeTypes, auditListeners, scheduler );
454 catch ( LayoutException e )
456 if ( !resourceFile.exists() )
458 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
465 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) +
468 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '" +
469 managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
471 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
472 logicalResource.getPath(), event, activePrincipal );
475 if ( !resourceFile.exists() )
477 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
483 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
485 String resourcePath = logicalResource.getPath();
487 // check if target repo is enabled for releases
488 // we suppose that release-artifacts can be deployed only to repos enabled for releases
489 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath ) &&
490 !repositoryRequest.isSupportFile( resourcePath ) )
492 ArtifactReference artifact = null;
495 artifact = managedRepository.toArtifactReference( resourcePath );
497 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
499 // check if artifact already exists and if artifact re-deployment to the repository is allowed
500 if ( managedRepository.hasContent( artifact ) && managedRepository.getRepository().isBlockRedeployments() )
502 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId() + "' is not allowed." );
503 throw new DavException( HttpServletResponse.SC_CONFLICT,
504 "Overwriting released artifacts is not allowed." );
508 catch ( LayoutException e )
510 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
515 * Create parent directories that don't exist when writing a file This actually makes this
516 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
517 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
518 * create the collections themselves.
521 File rootDirectory = new File( managedRepository.getRepoRoot() );
522 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
524 if ( !destDir.exists() )
527 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
529 log.debug( "Creating destination directory '" + destDir.getName() + "' (current user '" +
530 activePrincipal + "')" );
532 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath,
533 AuditEvent.CREATE_DIR, activePrincipal );
540 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
543 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
545 ManagedRepositoryContent managedRepository;
548 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
550 catch ( RepositoryNotFoundException e )
552 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " +
553 archivaLocator.getRepositoryId() );
555 catch ( RepositoryException e )
557 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
560 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
561 if ( logicalResource.startsWith( "/" ) )
563 logicalResource = logicalResource.substring( 1 );
565 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
566 DavResource resource =
567 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
568 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
570 resource.addLockManager( lockManager );
574 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
575 LogicalResource resource )
578 String path = resource.getPath();
579 if ( repositoryRequest.isSupportFile( path ) )
581 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
583 return ( proxiedFile != null );
586 // Is it a Metadata resource?
587 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
589 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
592 // Not any of the above? Then it's gotta be an artifact reference.
595 // Get the artifact reference in a layout neutral way.
596 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
598 if ( artifact != null )
600 applyServerSideRelocation( managedRepository, artifact );
602 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
604 resource.setPath( managedRepository.toPath( artifact ) );
606 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" +
607 artifact.getVersion() + "'" );
609 return ( proxiedFile != null );
612 catch ( LayoutException e )
616 catch ( ProxyDownloadException e )
618 log.error( e.getMessage(), e );
619 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
625 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
626 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
629 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
630 * metadatas and serving the expected artifact.
632 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
633 throws ProxyDownloadException
635 if ( "pom".equals( artifact.getType() ) )
640 // Build the artifact POM reference
641 ArtifactReference pomReference = new ArtifactReference();
642 pomReference.setGroupId( artifact.getGroupId() );
643 pomReference.setArtifactId( artifact.getArtifactId() );
644 pomReference.setVersion( artifact.getVersion() );
645 pomReference.setType( "pom" );
647 // Get the artifact POM from proxied repositories if needed
648 connectors.fetchFromProxies( managedRepository, pomReference );
650 // Open and read the POM from the managed repo
651 File pom = managedRepository.toFile( pomReference );
660 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
661 FileReader reader = new FileReader( pom );
665 model = new MavenXpp3Reader().read( reader );
669 if ( reader != null )
675 DistributionManagement dist = model.getDistributionManagement();
678 Relocation relocation = dist.getRelocation();
679 if ( relocation != null )
681 // artifact is relocated : update the repositoryPath
682 if ( relocation.getGroupId() != null )
684 artifact.setGroupId( relocation.getGroupId() );
686 if ( relocation.getArtifactId() != null )
688 artifact.setArtifactId( relocation.getArtifactId() );
690 if ( relocation.getVersion() != null )
692 artifact.setVersion( relocation.getVersion() );
697 catch ( FileNotFoundException e )
699 // Artifact has no POM in repo : ignore
701 catch ( IOException e )
703 // Unable to read POM : ignore.
705 catch ( XmlPullParserException e )
707 // Invalid POM : ignore
712 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
715 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
716 event.setRemoteIP( remoteIP );
718 for ( AuditListener listener : auditListeners )
720 listener.auditEvent( event );
724 public void addAuditListener( AuditListener listener )
726 this.auditListeners.add( listener );
729 public void clearAuditListeners()
731 this.auditListeners.clear();
734 public void removeAuditListener( AuditListener listener )
736 this.auditListeners.remove( listener );
739 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
741 // [MRM-503] - Metadata file need Pragma:no-cache response
743 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
745 response.addHeader( "Pragma", "no-cache" );
746 response.addHeader( "Cache-Control", "no-cache" );
749 // We need to specify this so connecting wagons can work correctly
750 response.addDateHeader( "last-modified", resource.getModificationTime() );
752 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
755 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
758 if ( !( locator instanceof ArchivaDavResourceLocator ) )
760 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
761 "Locator does not implement RepositoryLocator" );
765 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
767 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
770 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
772 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
773 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
775 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
777 return archivaLocator;
780 private static class LogicalResource
784 public LogicalResource( String path )
789 public String getPath()
794 public void setPath( String path )
800 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
805 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
806 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
808 return servletAuth.isAuthenticated( request, result ) &&
809 servletAuth.isAuthorized( request, securitySession, repositoryId,
810 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
812 catch ( AuthenticationException e )
814 // safety check for MRM-911
815 String guest = UserManager.GUEST_USERNAME;
818 if ( servletAuth.isAuthorized(
820 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
821 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
826 catch ( UnauthorizedException ae )
828 throw new UnauthorizedDavException( repositoryId,
829 "You are not authenticated and authorized to access any repository." );
832 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
834 catch ( MustChangePasswordException e )
836 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
838 catch ( AccountLockedException e )
840 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
842 catch ( AuthorizationException e )
844 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
845 "Fatal Authorization Subsystem Error." );
847 catch ( UnauthorizedException e )
849 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
853 private DavResource getResource( DavServletRequest request, List<String> repositories,
854 ArchivaDavResourceLocator locator )
857 List<File> mergedRepositoryContents = new ArrayList<File>();
858 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
859 if ( path.startsWith( "/" ) )
861 path = path.substring( 1 );
863 LogicalResource logicalResource = new LogicalResource( path );
866 // if the current user logged in has permission to any of the repositories, allow user to
867 // browse the repo group but displaying only the repositories which the user has permission to access.
868 // otherwise, prompt for authentication.
870 String activePrincipal = getActivePrincipal( request );
872 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
876 for ( String repository : repositories )
878 ManagedRepositoryContent managedRepository = null;
882 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
884 catch ( RepositoryNotFoundException e )
886 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
887 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
889 catch ( RepositoryException e )
891 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
892 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
895 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
896 if ( resourceFile.exists() )
898 // for prompted authentication
899 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
903 if ( isAuthorized( request, repository ) )
905 mergedRepositoryContents.add( resourceFile );
906 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
909 catch ( DavException e )
911 // TODO: review exception handling
912 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal +
913 "': " + e.getMessage() );
918 // for the current user logged in
921 if ( servletAuth.isAuthorized( activePrincipal, repository,
922 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
924 mergedRepositoryContents.add( resourceFile );
925 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
928 catch ( UnauthorizedException e )
930 // TODO: review exception handling
931 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal +
932 "': " + e.getMessage() );
940 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
943 ArchivaVirtualDavResource resource =
944 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
947 // compatibility with MRM-440 to ensure browsing the repository group works ok
948 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
950 throw new BrowserRedirectException( resource.getHref() );
956 protected String getActivePrincipal( DavServletRequest request )
958 User sessionUser = httpAuth.getSessionUser( request.getSession() );
959 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
963 * Check if the current user is authorized to access any of the repos
966 * @param repositories
967 * @param activePrincipal
970 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
972 boolean allow = false;
974 // if securitySession != null, it means that the user was prompted for authentication
975 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
977 for ( String repository : repositories )
981 if ( isAuthorized( request, repository ) )
987 catch ( DavException e )
995 for ( String repository : repositories )
999 if ( servletAuth.isAuthorized( activePrincipal, repository,
1000 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1006 catch ( UnauthorizedException e )
1016 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1017 throws RepositoryMetadataException, DigesterException, IOException
1019 File outputFile = new File( outputFilename );
1020 if ( outputFile.exists() )
1022 FileUtils.deleteQuietly( outputFile );
1025 outputFile.getParentFile().mkdirs();
1026 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1028 createChecksumFile( outputFilename, digestSha1 );
1029 createChecksumFile( outputFilename, digestMd5 );
1034 private void createChecksumFile( String path, Digester digester )
1035 throws DigesterException, IOException
1037 File checksumFile = new File( path + digester.getFilenameExtension() );
1038 if ( !checksumFile.exists() )
1040 FileUtils.deleteQuietly( checksumFile );
1041 checksum.createChecksum( new File( path ), digester );
1043 else if ( !checksumFile.isFile() )
1045 log.error( "Checksum file is not a file." );
1049 private boolean isProjectReference( String requestedResource )
1053 metadataTools.toVersionedReference( requestedResource );
1056 catch ( RepositoryMetadataException re )
1062 public void setServletAuth( ServletAuthenticator servletAuth )
1064 this.servletAuth = servletAuth;
1067 public void setHttpAuth( HttpAuthenticator httpAuth )
1069 this.httpAuth = httpAuth;
1072 public void setScheduler( ArchivaTaskScheduler scheduler )
1074 this.scheduler = scheduler;
1077 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1079 this.archivaConfiguration = archivaConfiguration;
1082 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1084 this.repositoryFactory = repositoryFactory;
1087 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1089 this.repositoryRequest = repositoryRequest;
1092 public void setConnectors( RepositoryProxyConnectors connectors )
1094 this.connectors = connectors;