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 import java.io.FileNotFoundException;
93 import java.io.FileReader;
94 import java.io.IOException;
95 import java.util.ArrayList;
96 import java.util.List;
97 import javax.servlet.http.HttpServletResponse;
100 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
102 public class ArchivaDavResourceFactory
103 implements DavResourceFactory, Auditable
105 private static final String PROXIED_SUFFIX = " (proxied)";
107 private static final String HTTP_PUT_METHOD = "PUT";
109 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
112 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
114 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
117 * @plexus.requirement
119 private RepositoryContentFactory repositoryFactory;
122 * @plexus.requirement
124 private RepositoryRequest repositoryRequest;
127 * @plexus.requirement role-hint="default"
129 private RepositoryProxyConnectors connectors;
132 * @plexus.requirement
134 private MetadataTools metadataTools;
137 * @plexus.requirement
139 private MimeTypes mimeTypes;
142 * @plexus.requirement
144 private ArchivaConfiguration archivaConfiguration;
147 * @plexus.requirement
149 private ServletAuthenticator servletAuth;
152 * @plexus.requirement role-hint="basic"
154 private HttpAuthenticator httpAuth;
157 * Lock Manager - use simple implementation from JackRabbit
159 private final LockManager lockManager = new SimpleLockManager();
162 * @plexus.requirement
164 private ChecksumFile checksum;
167 * @plexus.requirement role-hint="sha1"
169 private Digester digestSha1;
172 * @plexus.requirement role-hint="md5";
174 private Digester digestMd5;
177 * @plexus.requirement
179 private ArchivaTaskScheduler scheduler;
182 * @plexus.requirement role-hint="jdo"
184 private ArchivaAuditLogsDao auditLogsDao;
186 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
187 final DavServletResponse response )
190 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
192 RepositoryGroupConfiguration repoGroupConfig =
193 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
195 String activePrincipal = getActivePrincipal( request );
197 List<String> resourcesInAbsolutePath = new ArrayList<String>();
199 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
200 DavResource resource;
201 if ( repoGroupConfig != null )
205 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
206 "Write method not allowed for repository groups." );
209 log.debug( "Repository group '" + repoGroupConfig.getId() + "' accessed by '" + activePrincipal + "'" );
211 // handle browse requests for virtual repos
212 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
214 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
218 // make a copy to avoid potential concurrent modifications (eg. by configuration)
219 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
221 ArrayList<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
222 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
223 resourcesInAbsolutePath );
228 ManagedRepositoryContent managedRepository = null;
232 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
234 catch ( RepositoryNotFoundException e )
236 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
237 "Invalid repository: " + archivaLocator.getRepositoryId() );
239 catch ( RepositoryException e )
241 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
244 log.debug( "Managed repository '" + managedRepository.getId() + "' accessed by '" + activePrincipal + "'" );
246 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
248 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
249 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(),
250 logicalResource ).getAbsolutePath() );
253 String requestedResource = request.getRequestURI();
255 // MRM-872 : merge all available metadata
256 // merge metadata only when requested via the repo group
257 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
258 requestedResource ) ) && repoGroupConfig != null )
260 // this should only be at the project level not version level!
261 if ( isProjectReference( requestedResource ) )
263 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
264 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
266 ArchivaDavResource res = (ArchivaDavResource) resource;
267 String filePath = StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace(
269 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
271 // for MRM-872 handle checksums of the merged metadata files
272 if ( repositoryRequest.isSupportFile( requestedResource ) )
274 File metadataChecksum = new File( filePath + "." + StringUtils.substringAfterLast(
275 requestedResource, "." ) );
276 if ( metadataChecksum.exists() )
278 LogicalResource logicalResource = new LogicalResource( RepositoryPathUtil.getLogicalResource(
279 locator.getResourcePath() ) );
282 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
283 null, request.getRemoteAddr(), activePrincipal,
284 request.getDavSession(), archivaLocator, this, mimeTypes,
285 auditListeners, scheduler, auditLogsDao );
290 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
292 // merge the metadata of all repos under group
293 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
294 for ( String resourceAbsPath : resourcesInAbsolutePath )
298 File metadataFile = new File( resourceAbsPath );
299 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
300 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
302 catch ( RepositoryMetadataException r )
304 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
305 "Error occurred while reading metadata file." );
311 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
313 LogicalResource logicalResource = new LogicalResource(
314 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
317 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
318 null, request.getRemoteAddr(), activePrincipal,
319 request.getDavSession(), archivaLocator, this, mimeTypes,
320 auditListeners, scheduler, auditLogsDao );
322 catch ( RepositoryMetadataException r )
324 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
325 "Error occurred while writing metadata file." );
327 catch ( IOException ie )
329 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
330 "Error occurred while generating checksum files." );
332 catch ( DigesterException de )
334 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
335 "Error occurred while generating checksum files." );
342 setHeaders( response, locator, resource );
344 // compatibility with MRM-440 to ensure browsing the repository works ok
345 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
347 throw new BrowserRedirectException( resource.getHref() );
349 resource.addLockManager( lockManager );
353 private DavResource processRepositoryGroup( final DavServletRequest request,
354 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
355 String activePrincipal, List<String> resourcesInAbsolutePath )
358 DavResource resource = null;
359 List<DavException> storedExceptions = new ArrayList<DavException>();
361 for ( String repositoryId : repositories )
363 ManagedRepositoryContent managedRepository;
366 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
368 catch ( RepositoryNotFoundException e )
370 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
372 catch ( RepositoryException e )
374 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
379 DavResource updatedResource = processRepository( request, archivaLocator, activePrincipal,
381 if ( resource == null )
383 resource = updatedResource;
386 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
387 if ( logicalResource.endsWith( "/" ) )
389 logicalResource = logicalResource.substring( 1 );
391 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(),
392 logicalResource ).getAbsolutePath() );
394 catch ( DavException e )
396 storedExceptions.add( e );
400 if ( resource == null )
402 if ( !storedExceptions.isEmpty() )
405 for ( DavException e : storedExceptions )
407 if ( 401 == e.getErrorCode() )
413 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
417 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
423 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
424 String activePrincipal, ManagedRepositoryContent managedRepository )
427 DavResource resource = null;
428 if ( isAuthorized( request, managedRepository.getId() ) )
430 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
431 if ( path.startsWith( "/" ) )
433 path = path.substring( 1 );
435 LogicalResource logicalResource = new LogicalResource( path );
436 File resourceFile = new File( managedRepository.getRepoRoot(), path );
438 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
439 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
440 archivaLocator, this, mimeTypes, auditListeners, scheduler, auditLogsDao );
442 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
444 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
446 // force a resource not found
447 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
451 if ( !resource.isCollection() )
453 boolean previouslyExisted = resourceFile.exists();
455 // Attempt to fetch the resource from any defined proxy.
456 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
458 // At this point the incoming request can either be in default or
459 // legacy layout format.
462 // Perform an adjustment of the resource to the managed
463 // repository expected path.
464 String localResourcePath = repositoryRequest.toNativePath( logicalResource.getPath(),
466 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
468 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
469 managedRepository.getRepository(), request.getRemoteAddr(),
470 activePrincipal, request.getDavSession(), archivaLocator, this,
471 mimeTypes, auditListeners, scheduler, auditLogsDao );
473 catch ( LayoutException e )
475 if ( !resourceFile.exists() )
477 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
483 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) +
486 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '" +
487 managedRepository.getId() + "' (current user '" + activePrincipal + "')" );
489 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
490 logicalResource.getPath(), event, activePrincipal );
493 if ( !resourceFile.exists() )
495 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
501 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
503 String resourcePath = logicalResource.getPath();
505 // check if target repo is enabled for releases
506 // we suppose that release-artifacts can be deployed only to repos enabled for releases
507 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath ) &&
508 !repositoryRequest.isSupportFile( resourcePath ) )
510 ArtifactReference artifact = null;
513 artifact = managedRepository.toArtifactReference( resourcePath );
515 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
517 // check if artifact already exists and if artifact re-deployment to the repository is allowed
518 if ( managedRepository.hasContent( artifact ) &&
519 managedRepository.getRepository().isBlockRedeployments() )
521 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId() +
522 "' is not allowed." );
523 throw new DavException( HttpServletResponse.SC_CONFLICT,
524 "Overwriting released artifacts is not allowed." );
528 catch ( LayoutException e )
530 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
535 * Create parent directories that don't exist when writing a file This actually makes this
536 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
537 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
538 * create the collections themselves.
541 File rootDirectory = new File( managedRepository.getRepoRoot() );
542 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
544 if ( !destDir.exists() )
547 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
550 "Creating destination directory '" + destDir.getName() + "' (current user '" + activePrincipal +
553 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
554 AuditEvent.CREATE_DIR, activePrincipal );
561 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
564 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
566 ManagedRepositoryContent managedRepository;
569 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
571 catch ( RepositoryNotFoundException e )
573 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
574 "Invalid repository: " + archivaLocator.getRepositoryId() );
576 catch ( RepositoryException e )
578 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
581 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
582 if ( logicalResource.startsWith( "/" ) )
584 logicalResource = logicalResource.substring( 1 );
586 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
587 DavResource resource =
588 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
589 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler, auditLogsDao );
591 resource.addLockManager( lockManager );
595 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
596 LogicalResource resource )
599 String path = resource.getPath();
600 if ( repositoryRequest.isSupportFile( path ) )
602 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
604 return ( proxiedFile != null );
607 // Is it a Metadata resource?
608 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
610 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
613 // Not any of the above? Then it's gotta be an artifact reference.
616 // Get the artifact reference in a layout neutral way.
617 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
619 if ( artifact != null )
621 applyServerSideRelocation( managedRepository, artifact );
623 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
625 resource.setPath( managedRepository.toPath( artifact ) );
627 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" +
628 artifact.getVersion() + "'" );
630 return ( proxiedFile != null );
633 catch ( LayoutException e )
637 catch ( ProxyDownloadException e )
639 log.error( e.getMessage(), e );
640 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
641 "Unable to fetch artifact resource." );
647 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
648 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
651 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
652 * metadatas and serving the expected artifact.
654 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
655 throws ProxyDownloadException
657 if ( "pom".equals( artifact.getType() ) )
662 // Build the artifact POM reference
663 ArtifactReference pomReference = new ArtifactReference();
664 pomReference.setGroupId( artifact.getGroupId() );
665 pomReference.setArtifactId( artifact.getArtifactId() );
666 pomReference.setVersion( artifact.getVersion() );
667 pomReference.setType( "pom" );
669 // Get the artifact POM from proxied repositories if needed
670 connectors.fetchFromProxies( managedRepository, pomReference );
672 // Open and read the POM from the managed repo
673 File pom = managedRepository.toFile( pomReference );
682 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
683 FileReader reader = new FileReader( pom );
687 model = new MavenXpp3Reader().read( reader );
691 if ( reader != null )
697 DistributionManagement dist = model.getDistributionManagement();
700 Relocation relocation = dist.getRelocation();
701 if ( relocation != null )
703 // artifact is relocated : update the repositoryPath
704 if ( relocation.getGroupId() != null )
706 artifact.setGroupId( relocation.getGroupId() );
708 if ( relocation.getArtifactId() != null )
710 artifact.setArtifactId( relocation.getArtifactId() );
712 if ( relocation.getVersion() != null )
714 artifact.setVersion( relocation.getVersion() );
719 catch ( FileNotFoundException e )
721 // Artifact has no POM in repo : ignore
723 catch ( IOException e )
725 // Unable to read POM : ignore.
727 catch ( XmlPullParserException e )
729 // Invalid POM : ignore
735 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
738 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
739 event.setRemoteIP( remoteIP );
741 for ( AuditListener listener : auditListeners )
743 listener.auditEvent( event );
747 public void addAuditListener( AuditListener listener )
749 this.auditListeners.add( listener );
752 public void clearAuditListeners()
754 this.auditListeners.clear();
757 public void removeAuditListener( AuditListener listener )
759 this.auditListeners.remove( listener );
762 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
764 // [MRM-503] - Metadata file need Pragma:no-cache response
766 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
768 response.addHeader( "Pragma", "no-cache" );
769 response.addHeader( "Cache-Control", "no-cache" );
772 // We need to specify this so connecting wagons can work correctly
773 response.addDateHeader( "last-modified", resource.getModificationTime() );
775 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
778 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
781 if ( !( locator instanceof ArchivaDavResourceLocator ) )
783 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
784 "Locator does not implement RepositoryLocator" );
788 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
790 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
793 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
795 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
796 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
798 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
800 return archivaLocator;
803 private static class LogicalResource
807 public LogicalResource( String path )
812 public String getPath()
817 public void setPath( String path )
823 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
828 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
829 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
831 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
833 WebdavMethodUtil.getMethodPermission(
834 request.getMethod() ) );
836 catch ( AuthenticationException e )
838 // safety check for MRM-911
839 String guest = UserManager.GUEST_USERNAME;
842 if ( servletAuth.isAuthorized( guest,
843 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
844 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
849 catch ( UnauthorizedException ae )
851 throw new UnauthorizedDavException( repositoryId,
852 "You are not authenticated and authorized to access any repository." );
855 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
857 catch ( MustChangePasswordException e )
859 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
861 catch ( AccountLockedException e )
863 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
865 catch ( AuthorizationException e )
867 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
868 "Fatal Authorization Subsystem Error." );
870 catch ( UnauthorizedException e )
872 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
876 private DavResource getResource( DavServletRequest request, List<String> repositories,
877 ArchivaDavResourceLocator locator )
880 List<File> mergedRepositoryContents = new ArrayList<File>();
881 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
882 if ( path.startsWith( "/" ) )
884 path = path.substring( 1 );
886 LogicalResource logicalResource = new LogicalResource( path );
889 // if the current user logged in has permission to any of the repositories, allow user to
890 // browse the repo group but displaying only the repositories which the user has permission to access.
891 // otherwise, prompt for authentication.
893 String activePrincipal = getActivePrincipal( request );
895 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
899 for ( String repository : repositories )
901 ManagedRepositoryContent managedRepository = null;
905 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
907 catch ( RepositoryNotFoundException e )
909 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
910 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
912 catch ( RepositoryException e )
914 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
915 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
918 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
919 if ( resourceFile.exists() )
921 // for prompted authentication
922 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
926 if ( isAuthorized( request, repository ) )
928 mergedRepositoryContents.add( resourceFile );
929 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
932 catch ( DavException e )
934 // TODO: review exception handling
936 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': " +
942 // for the current user logged in
945 if ( servletAuth.isAuthorized( activePrincipal, repository,
946 WebdavMethodUtil.getMethodPermission(
947 request.getMethod() ) ) )
949 mergedRepositoryContents.add( resourceFile );
950 log.debug( "Repository '" + repository + "' accessed by '" + activePrincipal + "'" );
953 catch ( UnauthorizedException e )
955 // TODO: review exception handling
957 "Skipping repository '" + managedRepository + "' for user '" + activePrincipal + "': " +
966 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
969 ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource( mergedRepositoryContents,
970 logicalResource.getPath(), mimeTypes,
973 // compatibility with MRM-440 to ensure browsing the repository group works ok
974 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
976 throw new BrowserRedirectException( resource.getHref() );
982 protected String getActivePrincipal( DavServletRequest request )
984 User sessionUser = httpAuth.getSessionUser( request.getSession() );
985 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
989 * Check if the current user is authorized to access any of the repos
992 * @param repositories
993 * @param activePrincipal
996 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
998 boolean allow = false;
1000 // if securitySession != null, it means that the user was prompted for authentication
1001 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1003 for ( String repository : repositories )
1007 if ( isAuthorized( request, repository ) )
1013 catch ( DavException e )
1021 for ( String repository : repositories )
1025 if ( servletAuth.isAuthorized( activePrincipal, repository, WebdavMethodUtil.getMethodPermission(
1026 request.getMethod() ) ) )
1032 catch ( UnauthorizedException e )
1042 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1043 throws RepositoryMetadataException, DigesterException, IOException
1045 File outputFile = new File( outputFilename );
1046 if ( outputFile.exists() )
1048 FileUtils.deleteQuietly( outputFile );
1051 outputFile.getParentFile().mkdirs();
1052 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1054 createChecksumFile( outputFilename, digestSha1 );
1055 createChecksumFile( outputFilename, digestMd5 );
1060 private void createChecksumFile( String path, Digester digester )
1061 throws DigesterException, IOException
1063 File checksumFile = new File( path + digester.getFilenameExtension() );
1064 if ( !checksumFile.exists() )
1066 FileUtils.deleteQuietly( checksumFile );
1067 checksum.createChecksum( new File( path ), digester );
1069 else if ( !checksumFile.isFile() )
1071 log.error( "Checksum file is not a file." );
1075 private boolean isProjectReference( String requestedResource )
1079 metadataTools.toVersionedReference( requestedResource );
1082 catch ( RepositoryMetadataException re )
1088 public void setServletAuth( ServletAuthenticator servletAuth )
1090 this.servletAuth = servletAuth;
1093 public void setHttpAuth( HttpAuthenticator httpAuth )
1095 this.httpAuth = httpAuth;
1098 public void setScheduler( ArchivaTaskScheduler scheduler )
1100 this.scheduler = scheduler;
1103 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1105 this.archivaConfiguration = archivaConfiguration;
1108 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1110 this.repositoryFactory = repositoryFactory;
1113 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1115 this.repositoryRequest = repositoryRequest;
1118 public void setConnectors( RepositoryProxyConnectors connectors )
1120 this.connectors = connectors;
1123 public void setAuditLogsDao( ArchivaAuditLogsDao auditLogsDao )
1125 this.auditLogsDao = auditLogsDao;