1 package org.apache.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
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.audit.AuditEvent;
24 import org.apache.archiva.audit.AuditListener;
25 import org.apache.archiva.audit.Auditable;
26 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
27 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
28 import org.apache.archiva.common.utils.PathUtil;
29 import org.apache.archiva.common.utils.VersionUtil;
30 import org.apache.archiva.configuration.ArchivaConfiguration;
31 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
32 import org.apache.archiva.indexer.merger.IndexMerger;
33 import org.apache.archiva.indexer.merger.IndexMergerException;
34 import org.apache.archiva.indexer.search.RepositorySearch;
35 import org.apache.archiva.model.ArchivaRepositoryMetadata;
36 import org.apache.archiva.model.ArtifactReference;
37 import org.apache.archiva.policies.ProxyDownloadException;
38 import org.apache.archiva.proxy.RepositoryProxyConnectors;
39 import org.apache.archiva.repository.ManagedRepositoryContent;
40 import org.apache.archiva.repository.RepositoryContentFactory;
41 import org.apache.archiva.repository.RepositoryException;
42 import org.apache.archiva.repository.RepositoryNotFoundException;
43 import org.apache.archiva.repository.content.LegacyPathParser;
44 import org.apache.archiva.repository.content.RepositoryRequest;
45 import org.apache.archiva.repository.layout.LayoutException;
46 import org.apache.archiva.repository.metadata.MetadataTools;
47 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
48 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
49 import org.apache.archiva.repository.metadata.RepositoryMetadataReader;
50 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
51 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
52 import org.apache.archiva.security.ServletAuthenticator;
53 import org.apache.archiva.webdav.util.MimeTypes;
54 import org.apache.archiva.webdav.util.RepositoryPathUtil;
55 import org.apache.archiva.webdav.util.WebdavMethodUtil;
56 import org.apache.commons.io.FileUtils;
57 import org.apache.commons.io.FilenameUtils;
58 import org.apache.commons.lang.StringUtils;
59 import org.apache.jackrabbit.webdav.DavException;
60 import org.apache.jackrabbit.webdav.DavResource;
61 import org.apache.jackrabbit.webdav.DavResourceFactory;
62 import org.apache.jackrabbit.webdav.DavResourceLocator;
63 import org.apache.jackrabbit.webdav.DavServletRequest;
64 import org.apache.jackrabbit.webdav.DavServletResponse;
65 import org.apache.jackrabbit.webdav.DavSession;
66 import org.apache.jackrabbit.webdav.lock.LockManager;
67 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.Relocation;
71 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
72 import org.codehaus.plexus.digest.ChecksumFile;
73 import org.codehaus.plexus.digest.Digester;
74 import org.codehaus.plexus.digest.DigesterException;
75 import org.codehaus.plexus.redback.authentication.AuthenticationException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
77 import org.codehaus.plexus.redback.authorization.AuthorizationException;
78 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
79 import org.codehaus.plexus.redback.policy.AccountLockedException;
80 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
81 import org.codehaus.plexus.redback.system.SecuritySession;
82 import org.codehaus.plexus.redback.users.User;
83 import org.codehaus.plexus.redback.users.UserManager;
84 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
85 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.springframework.context.ApplicationContext;
89 import org.springframework.stereotype.Service;
91 import javax.annotation.PostConstruct;
92 import javax.inject.Inject;
93 import javax.inject.Named;
94 import javax.servlet.http.HttpServletResponse;
95 import javax.servlet.http.HttpSession;
97 import java.io.FileNotFoundException;
98 import java.io.FileReader;
99 import java.io.IOException;
100 import java.util.ArrayList;
101 import java.util.HashMap;
102 import java.util.HashSet;
103 import java.util.List;
104 import java.util.Map;
105 import java.util.Set;
110 @Service( "davResourceFactory#archiva" )
111 public class ArchivaDavResourceFactory
112 implements DavResourceFactory, Auditable
114 private static final String PROXIED_SUFFIX = " (proxied)";
116 private static final String HTTP_PUT_METHOD = "PUT";
118 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
124 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
130 private RepositoryContentFactory repositoryFactory;
135 private RepositoryRequest repositoryRequest;
141 @Named( value = "repositoryProxyConnectors#default" )
142 private RepositoryProxyConnectors connectors;
148 private MetadataTools metadataTools;
154 private MimeTypes mimeTypes;
159 private ArchivaConfiguration archivaConfiguration;
165 private ServletAuthenticator servletAuth;
171 @Named( value = "httpAuthenticator#basic" )
172 private HttpAuthenticator httpAuth;
175 private IndexMerger indexMerger;
178 private RepositorySearch repositorySearch;
181 * Lock Manager - use simple implementation from JackRabbit
183 private final LockManager lockManager = new SimpleLockManager();
188 private ChecksumFile checksum;
193 private Digester digestSha1;
198 private Digester digestMd5;
204 @Named( value = "archivaTaskScheduler#repository" )
205 private RepositoryArchivaTaskScheduler scheduler;
207 private ApplicationContext applicationContext;
210 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
211 ArchivaConfiguration archivaConfiguration )
212 throws PlexusSisuBridgeException
214 this.archivaConfiguration = archivaConfiguration;
215 this.applicationContext = applicationContext;
216 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
218 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
219 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
221 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
225 public void initialize()
230 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
231 final DavServletResponse response )
234 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
236 RepositoryGroupConfiguration repoGroupConfig =
237 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
239 String activePrincipal = getActivePrincipal( request );
241 List<String> resourcesInAbsolutePath = new ArrayList<String>();
243 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
244 DavResource resource;
245 if ( repoGroupConfig != null )
249 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
250 "Write method not allowed for repository groups." );
253 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
255 // handle browse requests for virtual repos
256 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
258 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
259 archivaLocator.getRepositoryId() );
263 // make a copy to avoid potential concurrent modifications (eg. by configuration)
264 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
266 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
267 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
268 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
273 ManagedRepositoryContent managedRepository = null;
277 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
279 catch ( RepositoryNotFoundException e )
281 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
282 "Invalid repository: " + archivaLocator.getRepositoryId() );
284 catch ( RepositoryException e )
286 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
289 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
291 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
293 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
294 resourcesInAbsolutePath.add(
295 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
298 String requestedResource = request.getRequestURI();
300 // MRM-872 : merge all available metadata
301 // merge metadata only when requested via the repo group
302 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
303 requestedResource ) ) && repoGroupConfig != null )
305 // this should only be at the project level not version level!
306 if ( isProjectReference( requestedResource ) )
308 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
309 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
311 ArchivaDavResource res = (ArchivaDavResource) resource;
313 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
315 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
317 // for MRM-872 handle checksums of the merged metadata files
318 if ( repositoryRequest.isSupportFile( requestedResource ) )
320 File metadataChecksum =
321 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
322 if ( metadataChecksum.exists() )
324 LogicalResource logicalResource =
325 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
328 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
329 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
330 archivaLocator, this, mimeTypes, auditListeners, scheduler );
335 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
337 // merge the metadata of all repos under group
338 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
339 for ( String resourceAbsPath : resourcesInAbsolutePath )
343 File metadataFile = new File( resourceAbsPath );
344 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
345 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
347 catch ( RepositoryMetadataException r )
349 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
350 "Error occurred while reading metadata file." );
356 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
358 LogicalResource logicalResource = new LogicalResource(
359 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
362 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
363 request.getRemoteAddr(), activePrincipal,
364 request.getDavSession(), archivaLocator, this, mimeTypes,
365 auditListeners, scheduler );
367 catch ( RepositoryMetadataException r )
369 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
370 "Error occurred while writing metadata file." );
372 catch ( IOException ie )
374 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
375 "Error occurred while generating checksum files." );
377 catch ( DigesterException de )
379 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
380 "Error occurred while generating checksum files." );
387 setHeaders( response, locator, resource );
389 // compatibility with MRM-440 to ensure browsing the repository works ok
390 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
392 throw new BrowserRedirectException( resource.getHref() );
394 resource.addLockManager( lockManager );
398 private DavResource processRepositoryGroup( final DavServletRequest request,
399 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
400 String activePrincipal, List<String> resourcesInAbsolutePath,
401 String repositoryGroupId )
404 DavResource resource = null;
405 List<DavException> storedExceptions = new ArrayList<DavException>();
407 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
409 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
411 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
413 // we are in the case of index file request
414 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
415 File temporaryIndexDirectory =
416 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
418 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
419 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
420 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
421 archivaLocator, this, mimeTypes, auditListeners, scheduler );
426 for ( String repositoryId : repositories )
428 ManagedRepositoryContent managedRepository;
431 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
433 catch ( RepositoryNotFoundException e )
435 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
437 catch ( RepositoryException e )
439 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
444 DavResource updatedResource =
445 processRepository( request, archivaLocator, activePrincipal, managedRepository );
446 if ( resource == null )
448 resource = updatedResource;
451 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
452 if ( logicalResource.endsWith( "/" ) )
454 logicalResource = logicalResource.substring( 1 );
456 resourcesInAbsolutePath.add(
457 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
459 catch ( DavException e )
461 storedExceptions.add( e );
465 if ( resource == null )
467 if ( !storedExceptions.isEmpty() )
470 for ( DavException e : storedExceptions )
472 if ( 401 == e.getErrorCode() )
478 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
482 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
488 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
489 String activePrincipal, ManagedRepositoryContent managedRepository )
492 DavResource resource = null;
493 if ( isAuthorized( request, managedRepository.getId() ) )
495 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
496 if ( path.startsWith( "/" ) )
498 path = path.substring( 1 );
500 LogicalResource logicalResource = new LogicalResource( path );
501 File resourceFile = new File( managedRepository.getRepoRoot(), path );
502 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
503 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
504 archivaLocator, this, mimeTypes, auditListeners, scheduler );
506 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
508 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
510 // force a resource not found
511 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
515 if ( !resource.isCollection() )
517 boolean previouslyExisted = resourceFile.exists();
519 // Attempt to fetch the resource from any defined proxy.
520 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
522 // At this point the incoming request can either be in default or
523 // legacy layout format.
526 // Perform an adjustment of the resource to the managed
527 // repository expected path.
528 String localResourcePath =
529 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
530 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
532 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
533 managedRepository.getRepository(), request.getRemoteAddr(),
534 activePrincipal, request.getDavSession(), archivaLocator, this,
535 mimeTypes, auditListeners, scheduler );
537 catch ( LayoutException e )
539 if ( !resourceFile.exists() )
541 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
547 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
550 if ( log.isDebugEnabled() )
552 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
553 + managedRepository.getId() + "' (current user '" + activePrincipal
556 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
557 logicalResource.getPath(), event, activePrincipal );
560 if ( !resourceFile.exists() )
562 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
568 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
570 String resourcePath = logicalResource.getPath();
572 // check if target repo is enabled for releases
573 // we suppose that release-artifacts can be deployed only to repos enabled for releases
574 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
575 && !repositoryRequest.isSupportFile( resourcePath ) )
577 ArtifactReference artifact = null;
580 artifact = managedRepository.toArtifactReference( resourcePath );
582 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
584 // check if artifact already exists and if artifact re-deployment to the repository is allowed
585 if ( managedRepository.hasContent( artifact )
586 && managedRepository.getRepository().isBlockRedeployments() )
588 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
589 + "' is not allowed." );
590 throw new DavException( HttpServletResponse.SC_CONFLICT,
591 "Overwriting released artifacts is not allowed." );
595 catch ( LayoutException e )
597 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
602 * Create parent directories that don't exist when writing a file This actually makes this
603 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
604 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
605 * create the collections themselves.
608 File rootDirectory = new File( managedRepository.getRepoRoot() );
609 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
611 if ( !destDir.exists() )
614 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
616 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
619 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
620 AuditEvent.CREATE_DIR, activePrincipal );
627 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
630 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
632 ManagedRepositoryContent managedRepository;
635 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
637 catch ( RepositoryNotFoundException e )
639 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
640 "Invalid repository: " + archivaLocator.getRepositoryId() );
642 catch ( RepositoryException e )
644 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
647 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
648 if ( logicalResource.startsWith( "/" ) )
650 logicalResource = logicalResource.substring( 1 );
652 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
653 DavResource resource =
654 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
655 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
657 resource.addLockManager( lockManager );
661 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
662 LogicalResource resource )
665 String path = resource.getPath();
666 if ( repositoryRequest.isSupportFile( path ) )
668 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
670 return ( proxiedFile != null );
673 // Is it a Metadata resource?
674 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
676 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
679 // Not any of the above? Then it's gotta be an artifact reference.
682 // Get the artifact reference in a layout neutral way.
683 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
685 if ( artifact != null )
687 applyServerSideRelocation( managedRepository, artifact );
689 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
691 resource.setPath( managedRepository.toPath( artifact ) );
692 if ( log.isDebugEnabled() )
694 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
695 + artifact.getVersion() + "'" );
697 return ( proxiedFile != null );
700 catch ( LayoutException e )
704 catch ( ProxyDownloadException e )
706 log.error( e.getMessage(), e );
707 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
708 "Unable to fetch artifact resource." );
714 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
715 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
718 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
719 * metadatas and serving the expected artifact.
721 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
722 throws ProxyDownloadException
724 if ( "pom".equals( artifact.getType() ) )
729 // Build the artifact POM reference
730 ArtifactReference pomReference = new ArtifactReference();
731 pomReference.setGroupId( artifact.getGroupId() );
732 pomReference.setArtifactId( artifact.getArtifactId() );
733 pomReference.setVersion( artifact.getVersion() );
734 pomReference.setType( "pom" );
736 // Get the artifact POM from proxied repositories if needed
737 connectors.fetchFromProxies( managedRepository, pomReference );
739 // Open and read the POM from the managed repo
740 File pom = managedRepository.toFile( pomReference );
749 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
750 FileReader reader = new FileReader( pom );
754 model = new MavenXpp3Reader().read( reader );
758 if ( reader != null )
764 DistributionManagement dist = model.getDistributionManagement();
767 Relocation relocation = dist.getRelocation();
768 if ( relocation != null )
770 // artifact is relocated : update the repositoryPath
771 if ( relocation.getGroupId() != null )
773 artifact.setGroupId( relocation.getGroupId() );
775 if ( relocation.getArtifactId() != null )
777 artifact.setArtifactId( relocation.getArtifactId() );
779 if ( relocation.getVersion() != null )
781 artifact.setVersion( relocation.getVersion() );
786 catch ( FileNotFoundException e )
788 // Artifact has no POM in repo : ignore
790 catch ( IOException e )
792 // Unable to read POM : ignore.
794 catch ( XmlPullParserException e )
796 // Invalid POM : ignore
802 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
805 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
806 event.setRemoteIP( remoteIP );
808 for ( AuditListener listener : auditListeners )
810 listener.auditEvent( event );
814 public void addAuditListener( AuditListener listener )
816 this.auditListeners.add( listener );
819 public void clearAuditListeners()
821 this.auditListeners.clear();
824 public void removeAuditListener( AuditListener listener )
826 this.auditListeners.remove( listener );
829 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
831 // [MRM-503] - Metadata file need Pragma:no-cache response
833 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
835 response.addHeader( "Pragma", "no-cache" );
836 response.addHeader( "Cache-Control", "no-cache" );
839 // We need to specify this so connecting wagons can work correctly
840 response.addDateHeader( "last-modified", resource.getModificationTime() );
842 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
845 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
848 if ( !( locator instanceof ArchivaDavResourceLocator ) )
850 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
851 "Locator does not implement RepositoryLocator" );
855 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
857 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
860 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
862 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
863 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
865 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
867 return archivaLocator;
870 private static class LogicalResource
874 public LogicalResource( String path )
879 public String getPath()
884 public void setPath( String path )
890 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
895 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
896 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
898 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
900 WebdavMethodUtil.getMethodPermission(
901 request.getMethod() ) );
903 catch ( AuthenticationException e )
905 // safety check for MRM-911
906 String guest = UserManager.GUEST_USERNAME;
909 if ( servletAuth.isAuthorized( guest,
910 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
911 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
916 catch ( UnauthorizedException ae )
918 throw new UnauthorizedDavException( repositoryId,
919 "You are not authenticated and authorized to access any repository." );
922 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
924 catch ( MustChangePasswordException e )
926 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
928 catch ( AccountLockedException e )
930 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
932 catch ( AuthorizationException e )
934 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
935 "Fatal Authorization Subsystem Error." );
937 catch ( UnauthorizedException e )
939 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
943 private DavResource getResource( DavServletRequest request, List<String> repositories,
944 ArchivaDavResourceLocator locator, String groupId )
947 List<File> mergedRepositoryContents = new ArrayList<File>();
948 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
949 if ( path.startsWith( "/" ) )
951 path = path.substring( 1 );
953 LogicalResource logicalResource = new LogicalResource( path );
956 // if the current user logged in has permission to any of the repositories, allow user to
957 // browse the repo group but displaying only the repositories which the user has permission to access.
958 // otherwise, prompt for authentication.
960 String activePrincipal = getActivePrincipal( request );
962 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
968 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
969 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
971 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
972 mergedRepositoryContents.add( mergedRepoDir );
976 for ( String repository : repositories )
978 ManagedRepositoryContent managedRepository = null;
982 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
984 catch ( RepositoryNotFoundException e )
986 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
987 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
989 catch ( RepositoryException e )
991 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
992 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
995 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
996 if ( resourceFile.exists() )
998 // in case of group displaying index directory doesn't have sense !!
999 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1000 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1002 if ( !new File( repoIndexDirectory ).isAbsolute() )
1004 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1005 StringUtils.isEmpty( repoIndexDirectory )
1007 : repoIndexDirectory ).getAbsolutePath();
1010 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1012 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1013 ".indexer" ).getAbsolutePath();
1016 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1017 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1019 // for prompted authentication
1020 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1024 if ( isAuthorized( request, repository ) )
1026 mergedRepositoryContents.add( resourceFile );
1027 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1030 catch ( DavException e )
1032 // TODO: review exception handling
1033 if ( log.isDebugEnabled() )
1035 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1036 + activePrincipal + "': " + e.getMessage() );
1043 // for the current user logged in
1046 if ( servletAuth.isAuthorized( activePrincipal, repository,
1047 WebdavMethodUtil.getMethodPermission(
1048 request.getMethod() ) ) )
1050 mergedRepositoryContents.add( resourceFile );
1051 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1054 catch ( UnauthorizedException e )
1056 // TODO: review exception handling
1057 if ( log.isDebugEnabled() )
1059 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1060 + activePrincipal + "': " + e.getMessage() );
1071 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1074 ArchivaVirtualDavResource resource =
1075 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1078 // compatibility with MRM-440 to ensure browsing the repository group works ok
1079 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1081 throw new BrowserRedirectException( resource.getHref() );
1087 protected String getActivePrincipal( DavServletRequest request )
1089 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1090 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1094 * Check if the current user is authorized to access any of the repos
1097 * @param repositories
1098 * @param activePrincipal
1101 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1103 boolean allow = false;
1105 // if securitySession != null, it means that the user was prompted for authentication
1106 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1108 for ( String repository : repositories )
1112 if ( isAuthorized( request, repository ) )
1118 catch ( DavException e )
1126 for ( String repository : repositories )
1130 if ( servletAuth.isAuthorized( activePrincipal, repository,
1131 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1137 catch ( UnauthorizedException e )
1147 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1148 throws RepositoryMetadataException, DigesterException, IOException
1150 File outputFile = new File( outputFilename );
1151 if ( outputFile.exists() )
1153 FileUtils.deleteQuietly( outputFile );
1156 outputFile.getParentFile().mkdirs();
1157 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1159 createChecksumFile( outputFilename, digestSha1 );
1160 createChecksumFile( outputFilename, digestMd5 );
1165 private void createChecksumFile( String path, Digester digester )
1166 throws DigesterException, IOException
1168 File checksumFile = new File( path + digester.getFilenameExtension() );
1169 if ( !checksumFile.exists() )
1171 FileUtils.deleteQuietly( checksumFile );
1172 checksum.createChecksum( new File( path ), digester );
1174 else if ( !checksumFile.isFile() )
1176 log.error( "Checksum file is not a file." );
1180 private boolean isProjectReference( String requestedResource )
1184 metadataTools.toVersionedReference( requestedResource );
1187 catch ( RepositoryMetadataException re )
1193 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1194 DavServletRequest request, String groupId )
1200 HttpSession session = request.getSession();
1201 Map<String, File> testValue = (Map<String, File>) session.getAttribute( "TMP_GROUP_INDEXES" );
1202 if ( testValue == null )
1204 testValue = new HashMap<String, File>();
1207 File tmp = testValue.get( groupId );
1213 Set<String> authzRepos = new HashSet<String>();
1214 for ( String repository : repositories )
1218 if ( servletAuth.isAuthorized( activePrincipal, repository,
1219 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1221 authzRepos.add( repository );
1222 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1225 catch ( UnauthorizedException e )
1227 // TODO: review exception handling
1228 if ( log.isDebugEnabled() )
1230 log.debug( "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1236 File mergedRepoDir = indexMerger.buildMergedIndex( authzRepos, true );
1237 testValue.put( groupId, mergedRepoDir );
1238 session.setAttribute( "TMP_GROUP_INDEXES", testValue );
1239 return mergedRepoDir;
1241 catch ( RepositoryAdminException e )
1243 throw new DavException( 500, e );
1245 catch ( IndexMergerException e )
1247 throw new DavException( 500, e );
1252 public void setServletAuth( ServletAuthenticator servletAuth )
1254 this.servletAuth = servletAuth;
1257 public void setHttpAuth( HttpAuthenticator httpAuth )
1259 this.httpAuth = httpAuth;
1262 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1264 this.scheduler = scheduler;
1267 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1269 this.archivaConfiguration = archivaConfiguration;
1272 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1274 this.repositoryFactory = repositoryFactory;
1277 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1279 this.repositoryRequest = repositoryRequest;
1282 public void setConnectors( RepositoryProxyConnectors connectors )
1284 this.connectors = connectors;