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.database.ArchivaAuditLogsDao;
47 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.maven.archiva.model.ArtifactReference;
49 import org.apache.maven.archiva.policies.ProxyDownloadException;
50 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
51 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
52 import org.apache.maven.archiva.repository.RepositoryContentFactory;
53 import org.apache.maven.archiva.repository.RepositoryException;
54 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
55 import org.apache.maven.archiva.repository.audit.AuditEvent;
56 import org.apache.maven.archiva.repository.audit.AuditListener;
57 import org.apache.maven.archiva.repository.audit.Auditable;
58 import org.apache.maven.archiva.repository.content.RepositoryRequest;
59 import org.apache.maven.archiva.repository.layout.LayoutException;
60 import org.apache.maven.archiva.repository.metadata.MetadataTools;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
63 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
64 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
65 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
66 import org.apache.maven.archiva.security.ServletAuthenticator;
67 import org.apache.maven.archiva.webdav.util.MimeTypes;
68 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
69 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
70 import org.apache.maven.model.DistributionManagement;
71 import org.apache.maven.model.Model;
72 import org.apache.maven.model.Relocation;
73 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
74 import org.codehaus.plexus.digest.ChecksumFile;
75 import org.codehaus.plexus.digest.Digester;
76 import org.codehaus.plexus.digest.DigesterException;
77 import org.codehaus.plexus.redback.authentication.AuthenticationException;
78 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
79 import org.codehaus.plexus.redback.authorization.AuthorizationException;
80 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
81 import org.codehaus.plexus.redback.policy.AccountLockedException;
82 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
83 import org.codehaus.plexus.redback.system.SecuritySession;
84 import org.codehaus.plexus.redback.users.User;
85 import org.codehaus.plexus.redback.users.UserManager;
86 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
87 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
94 public class ArchivaDavResourceFactory
95 implements DavResourceFactory, Auditable
97 private static final String PROXIED_SUFFIX = " (proxied)";
99 private static final String HTTP_PUT_METHOD = "PUT";
101 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
104 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
106 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
109 * @plexus.requirement
111 private RepositoryContentFactory repositoryFactory;
114 * @plexus.requirement
116 private RepositoryRequest repositoryRequest;
119 * @plexus.requirement role-hint="default"
121 private RepositoryProxyConnectors connectors;
124 * @plexus.requirement
126 private MetadataTools metadataTools;
129 * @plexus.requirement
131 private MimeTypes mimeTypes;
134 * @plexus.requirement
136 private ArchivaConfiguration archivaConfiguration;
139 * @plexus.requirement
141 private ServletAuthenticator servletAuth;
144 * @plexus.requirement role-hint="basic"
146 private HttpAuthenticator httpAuth;
149 * Lock Manager - use simple implementation from JackRabbit
151 private final LockManager lockManager = new SimpleLockManager();
154 * @plexus.requirement
156 private ChecksumFile checksum;
159 * @plexus.requirement role-hint="sha1"
161 private Digester digestSha1;
164 * @plexus.requirement role-hint="md5";
166 private Digester digestMd5;
169 * @plexus.requirement
171 private ArchivaTaskScheduler scheduler;
174 * @plexus.requirement role-hint="jdo"
176 private ArchivaAuditLogsDao auditLogsDao;
178 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
179 final DavServletResponse response )
182 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
184 RepositoryGroupConfiguration repoGroupConfig =
185 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
187 String activePrincipal = getActivePrincipal( request );
189 List<String> resourcesInAbsolutePath = new ArrayList<String>();
191 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
192 DavResource resource;
193 if ( repoGroupConfig != null )
197 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
198 "Write method not allowed for repository groups." );
201 log.debug( "Repository group '" + repoGroupConfig.getId() + "' accessed by '" + activePrincipal + "'" );
203 // handle browse requests for virtual repos
204 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
206 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
211 processRepositoryGroup( request, archivaLocator, repoGroupConfig.getRepositories(),
212 activePrincipal, resourcesInAbsolutePath );
217 ManagedRepositoryContent managedRepository = null;
221 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
223 catch ( RepositoryNotFoundException e )
225 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " +
226 archivaLocator.getRepositoryId() );
228 catch ( RepositoryException e )
230 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
233 log.debug( "Managed repository '" + managedRepository.getId() + "' accessed by '" + activePrincipal + "'" );
235 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
237 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
238 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
241 String requestedResource = request.getRequestURI();
243 // MRM-872 : merge all available metadata
244 // merge metadata only when requested via the repo group
245 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile( requestedResource ) ) &&
246 repoGroupConfig != null )
248 // this should only be at the project level not version level!
249 if ( isProjectReference( requestedResource ) )
251 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
252 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
254 ArchivaDavResource res = (ArchivaDavResource) resource;
256 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
257 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
259 // for MRM-872 handle checksums of the merged metadata files
260 if ( repositoryRequest.isSupportFile( requestedResource ) )
262 File metadataChecksum =
263 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
264 if ( metadataChecksum.exists() )
266 LogicalResource logicalResource =
267 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
270 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
271 null, request.getRemoteAddr(), activePrincipal,
272 request.getDavSession(), archivaLocator, this, mimeTypes,
273 auditListeners, scheduler, auditLogsDao );
278 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
280 // merge the metadata of all repos under group
281 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
282 for ( String resourceAbsPath : resourcesInAbsolutePath )
286 File metadataFile = new File( resourceAbsPath );
287 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
288 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
290 catch ( RepositoryMetadataException r )
292 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
293 "Error occurred while reading metadata file." );
299 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
301 LogicalResource logicalResource =
302 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
305 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
306 null, request.getRemoteAddr(), activePrincipal,
307 request.getDavSession(), archivaLocator, this, mimeTypes,
308 auditListeners, scheduler, auditLogsDao );
310 catch ( RepositoryMetadataException r )
312 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
313 "Error occurred while writing metadata file." );
315 catch ( IOException ie )
317 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
318 "Error occurred while generating checksum files." );
320 catch ( DigesterException de )
322 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
323 "Error occurred while generating checksum files." );
330 setHeaders( response, locator, resource );
332 // compatibility with MRM-440 to ensure browsing the repository works ok
333 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
335 throw new BrowserRedirectException( resource.getHref() );
337 resource.addLockManager( lockManager );
341 private DavResource processRepositoryGroup( final DavServletRequest request,
342 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
343 String activePrincipal, List<String> resourcesInAbsolutePath )
346 DavResource resource = null;
347 List<DavException> storedExceptions = new ArrayList<DavException>();
349 for ( String repositoryId : repositories )
351 ManagedRepositoryContent managedRepository = null;
354 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
356 catch ( RepositoryNotFoundException e )
358 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
360 catch ( RepositoryException e )
362 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
367 DavResource updatedResource =
368 processRepository( request, archivaLocator, activePrincipal, managedRepository );
369 if ( resource == null )
371 resource = updatedResource;
374 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
375 if ( logicalResource.endsWith( "/" ) )
377 logicalResource = logicalResource.substring( 1 );
379 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
381 catch ( DavException e )
383 storedExceptions.add( e );
387 if ( resource == null )
389 if ( !storedExceptions.isEmpty() )
392 for ( DavException e : storedExceptions )
394 if ( 401 == e.getErrorCode() )
400 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
404 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
410 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
411 String activePrincipal, ManagedRepositoryContent managedRepository )
414 DavResource resource = null;
415 if ( isAuthorized( request, managedRepository.getId() ) )
417 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
418 if ( path.startsWith( "/" ) )
420 path = path.substring( 1 );
422 LogicalResource logicalResource = new LogicalResource( path );
423 File resourceFile = new File( managedRepository.getRepoRoot(), path );
425 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
426 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
427 archivaLocator, this, mimeTypes, auditListeners, scheduler, auditLogsDao );
429 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
431 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
433 // force a resource not found
434 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
438 if ( !resource.isCollection() )
440 boolean previouslyExisted = resourceFile.exists();
442 // Attempt to fetch the resource from any defined proxy.
443 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
445 // At this point the incoming request can either be in default or
446 // legacy layout format.
449 // Perform an adjustment of the resource to the managed
450 // repository expected path.
451 String localResourcePath =
452 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
453 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
455 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
456 managedRepository.getRepository(), request.getRemoteAddr(),
457 activePrincipal, request.getDavSession(), archivaLocator, this,
458 mimeTypes, auditListeners, scheduler, auditLogsDao );
460 catch ( LayoutException e )
462 if ( !resourceFile.exists() )
464 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
471 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) +
474 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '" +
475 managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
477 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
478 logicalResource.getPath(), event, activePrincipal );
481 if ( !resourceFile.exists() )
483 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
489 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
491 String resourcePath = logicalResource.getPath();
493 // check if target repo is enabled for releases
494 // we suppose that release-artifacts can be deployed only to repos enabled for releases
495 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath ) &&
496 !repositoryRequest.isSupportFile( resourcePath ) )
498 ArtifactReference artifact = null;
501 artifact = managedRepository.toArtifactReference( resourcePath );
503 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
505 // check if artifact already exists and if artifact re-deployment to the repository is allowed
506 if ( managedRepository.hasContent( artifact ) && managedRepository.getRepository().isBlockRedeployments() )
508 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId() + "' is not allowed." );
509 throw new DavException( HttpServletResponse.SC_CONFLICT,
510 "Overwriting released artifacts is not allowed." );
514 catch ( LayoutException e )
516 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
521 * Create parent directories that don't exist when writing a file This actually makes this
522 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
523 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
524 * create the collections themselves.
527 File rootDirectory = new File( managedRepository.getRepoRoot() );
528 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
530 if ( !destDir.exists() )
533 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
535 log.debug( "Creating destination directory '" + destDir.getName() + "' (current user '" +
536 activePrincipal + "')" );
538 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
539 AuditEvent.CREATE_DIR, activePrincipal );
546 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
549 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
551 ManagedRepositoryContent managedRepository;
554 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
556 catch ( RepositoryNotFoundException e )
558 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: " +
559 archivaLocator.getRepositoryId() );
561 catch ( RepositoryException e )
563 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
566 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
567 if ( logicalResource.startsWith( "/" ) )
569 logicalResource = logicalResource.substring( 1 );
571 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
572 DavResource resource =
573 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
574 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler, auditLogsDao );
576 resource.addLockManager( lockManager );
580 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
581 LogicalResource resource )
584 String path = resource.getPath();
585 if ( repositoryRequest.isSupportFile( path ) )
587 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
589 return ( proxiedFile != null );
592 // Is it a Metadata resource?
593 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
595 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
598 // Not any of the above? Then it's gotta be an artifact reference.
601 // Get the artifact reference in a layout neutral way.
602 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
604 if ( artifact != null )
606 applyServerSideRelocation( managedRepository, artifact );
608 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
610 resource.setPath( managedRepository.toPath( artifact ) );
612 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" +
613 artifact.getVersion() + "'" );
615 return ( proxiedFile != null );
618 catch ( LayoutException e )
622 catch ( ProxyDownloadException e )
624 log.error( e.getMessage(), e );
625 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
631 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
632 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
635 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
636 * metadatas and serving the expected artifact.
638 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
639 throws ProxyDownloadException
641 if ( "pom".equals( artifact.getType() ) )
646 // Build the artifact POM reference
647 ArtifactReference pomReference = new ArtifactReference();
648 pomReference.setGroupId( artifact.getGroupId() );
649 pomReference.setArtifactId( artifact.getArtifactId() );
650 pomReference.setVersion( artifact.getVersion() );
651 pomReference.setType( "pom" );
653 // Get the artifact POM from proxied repositories if needed
654 connectors.fetchFromProxies( managedRepository, pomReference );
656 // Open and read the POM from the managed repo
657 File pom = managedRepository.toFile( pomReference );
666 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
667 FileReader reader = new FileReader( pom );
671 model = new MavenXpp3Reader().read( reader );
675 if ( reader != null )
681 DistributionManagement dist = model.getDistributionManagement();
684 Relocation relocation = dist.getRelocation();
685 if ( relocation != null )
687 // artifact is relocated : update the repositoryPath
688 if ( relocation.getGroupId() != null )
690 artifact.setGroupId( relocation.getGroupId() );
692 if ( relocation.getArtifactId() != null )
694 artifact.setArtifactId( relocation.getArtifactId() );
696 if ( relocation.getVersion() != null )
698 artifact.setVersion( relocation.getVersion() );
703 catch ( FileNotFoundException e )
705 // Artifact has no POM in repo : ignore
707 catch ( IOException e )
709 // Unable to read POM : ignore.
711 catch ( XmlPullParserException e )
713 // Invalid POM : ignore
718 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
721 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
722 event.setRemoteIP( remoteIP );
724 for ( AuditListener listener : auditListeners )
726 listener.auditEvent( event );
730 public void addAuditListener( AuditListener listener )
732 this.auditListeners.add( listener );
735 public void clearAuditListeners()
737 this.auditListeners.clear();
740 public void removeAuditListener( AuditListener listener )
742 this.auditListeners.remove( listener );
745 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
747 // [MRM-503] - Metadata file need Pragma:no-cache response
749 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
751 response.addHeader( "Pragma", "no-cache" );
752 response.addHeader( "Cache-Control", "no-cache" );
755 // We need to specify this so connecting wagons can work correctly
756 response.addDateHeader( "last-modified", resource.getModificationTime() );
758 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
761 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
764 if ( !( locator instanceof ArchivaDavResourceLocator ) )
766 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
767 "Locator does not implement RepositoryLocator" );
771 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
773 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
776 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
778 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
779 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
781 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
783 return archivaLocator;
786 private static class LogicalResource
790 public LogicalResource( String path )
795 public String getPath()
800 public void setPath( String path )
806 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
811 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
812 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
814 return servletAuth.isAuthenticated( request, result ) &&
815 servletAuth.isAuthorized( request, securitySession, repositoryId,
816 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
818 catch ( AuthenticationException e )
820 // safety check for MRM-911
821 String guest = UserManager.GUEST_USERNAME;
824 if ( servletAuth.isAuthorized(
826 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
827 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
832 catch ( UnauthorizedException ae )
834 throw new UnauthorizedDavException( repositoryId,
835 "You are not authenticated and authorized to access any repository." );
838 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
840 catch ( MustChangePasswordException e )
842 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
844 catch ( AccountLockedException e )
846 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
848 catch ( AuthorizationException e )
850 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
851 "Fatal Authorization Subsystem Error." );
853 catch ( UnauthorizedException e )
855 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
859 private DavResource getResource( DavServletRequest request, List<String> repositories,
860 ArchivaDavResourceLocator locator )
863 List<File> mergedRepositoryContents = new ArrayList<File>();
864 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
865 if ( path.startsWith( "/" ) )
867 path = path.substring( 1 );
869 LogicalResource logicalResource = new LogicalResource( path );
872 // if the current user logged in has permission to any of the repositories, allow user to
873 // browse the repo group but displaying only the repositories which the user has permission to access.
874 // otherwise, prompt for authentication.
876 String activePrincipal = getActivePrincipal( request );
878 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
882 for ( String repository : repositories )
884 ManagedRepositoryContent managedRepository = null;
888 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
890 catch ( RepositoryNotFoundException e )
892 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
893 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
895 catch ( RepositoryException e )
897 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
898 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
901 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
902 if ( resourceFile.exists() )
904 // for prompted authentication
905 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
909 if ( isAuthorized( request, repository ) )
911 mergedRepositoryContents.add( resourceFile );
912 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
915 catch ( DavException e )
917 // TODO: review exception handling
918 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal +
919 "': " + e.getMessage() );
924 // for the current user logged in
927 if ( servletAuth.isAuthorized( activePrincipal, repository,
928 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
930 mergedRepositoryContents.add( resourceFile );
931 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
934 catch ( UnauthorizedException e )
936 // TODO: review exception handling
937 log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal +
938 "': " + e.getMessage() );
946 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
949 ArchivaVirtualDavResource resource =
950 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
953 // compatibility with MRM-440 to ensure browsing the repository group works ok
954 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
956 throw new BrowserRedirectException( resource.getHref() );
962 protected String getActivePrincipal( DavServletRequest request )
964 User sessionUser = httpAuth.getSessionUser( request.getSession() );
965 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
969 * Check if the current user is authorized to access any of the repos
972 * @param repositories
973 * @param activePrincipal
976 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
978 boolean allow = false;
980 // if securitySession != null, it means that the user was prompted for authentication
981 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
983 for ( String repository : repositories )
987 if ( isAuthorized( request, repository ) )
993 catch ( DavException e )
1001 for ( String repository : repositories )
1005 if ( servletAuth.isAuthorized( activePrincipal, repository,
1006 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1012 catch ( UnauthorizedException e )
1022 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1023 throws RepositoryMetadataException, DigesterException, IOException
1025 File outputFile = new File( outputFilename );
1026 if ( outputFile.exists() )
1028 FileUtils.deleteQuietly( outputFile );
1031 outputFile.getParentFile().mkdirs();
1032 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1034 createChecksumFile( outputFilename, digestSha1 );
1035 createChecksumFile( outputFilename, digestMd5 );
1040 private void createChecksumFile( String path, Digester digester )
1041 throws DigesterException, IOException
1043 File checksumFile = new File( path + digester.getFilenameExtension() );
1044 if ( !checksumFile.exists() )
1046 FileUtils.deleteQuietly( checksumFile );
1047 checksum.createChecksum( new File( path ), digester );
1049 else if ( !checksumFile.isFile() )
1051 log.error( "Checksum file is not a file." );
1055 private boolean isProjectReference( String requestedResource )
1059 metadataTools.toVersionedReference( requestedResource );
1062 catch ( RepositoryMetadataException re )
1068 public void setServletAuth( ServletAuthenticator servletAuth )
1070 this.servletAuth = servletAuth;
1073 public void setHttpAuth( HttpAuthenticator httpAuth )
1075 this.httpAuth = httpAuth;
1078 public void setScheduler( ArchivaTaskScheduler scheduler )
1080 this.scheduler = scheduler;
1083 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1085 this.archivaConfiguration = archivaConfiguration;
1088 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1090 this.repositoryFactory = repositoryFactory;
1093 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1095 this.repositoryRequest = repositoryRequest;
1098 public void setConnectors( RepositoryProxyConnectors connectors )
1100 this.connectors = connectors;
1103 public void setAuditLogsDao( ArchivaAuditLogsDao auditLogsDao )
1105 this.auditLogsDao = auditLogsDao;