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.admin.model.beans.RemoteRepository;
24 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
25 import org.apache.archiva.audit.AuditEvent;
26 import org.apache.archiva.audit.AuditListener;
27 import org.apache.archiva.audit.Auditable;
28 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
30 import org.apache.archiva.common.utils.PathUtil;
31 import org.apache.archiva.common.utils.VersionUtil;
32 import org.apache.archiva.configuration.ArchivaConfiguration;
33 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
34 import org.apache.archiva.indexer.merger.IndexMerger;
35 import org.apache.archiva.indexer.merger.IndexMergerException;
36 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
37 import org.apache.archiva.indexer.search.RepositorySearch;
38 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
39 import org.apache.archiva.model.ArchivaRepositoryMetadata;
40 import org.apache.archiva.model.ArtifactReference;
41 import org.apache.archiva.policies.ProxyDownloadException;
42 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
43 import org.apache.archiva.redback.authentication.AuthenticationException;
44 import org.apache.archiva.redback.authentication.AuthenticationResult;
45 import org.apache.archiva.redback.authorization.AuthorizationException;
46 import org.apache.archiva.redback.authorization.UnauthorizedException;
47 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
48 import org.apache.archiva.redback.policy.AccountLockedException;
49 import org.apache.archiva.redback.policy.MustChangePasswordException;
50 import org.apache.archiva.redback.system.SecuritySession;
51 import org.apache.archiva.redback.users.User;
52 import org.apache.archiva.redback.users.UserManager;
53 import org.apache.archiva.repository.ManagedRepositoryContent;
54 import org.apache.archiva.repository.RepositoryContentFactory;
55 import org.apache.archiva.repository.RepositoryException;
56 import org.apache.archiva.repository.RepositoryNotFoundException;
57 import org.apache.archiva.repository.content.LegacyPathParser;
58 import org.apache.archiva.repository.content.RepositoryRequest;
59 import org.apache.archiva.repository.layout.LayoutException;
60 import org.apache.archiva.repository.metadata.MetadataTools;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
63 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
64 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
65 import org.apache.archiva.security.ServletAuthenticator;
66 import org.apache.archiva.webdav.util.MimeTypes;
67 import org.apache.archiva.webdav.util.RepositoryPathUtil;
68 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
69 import org.apache.archiva.webdav.util.WebdavMethodUtil;
70 import org.apache.archiva.xml.XMLException;
71 import org.apache.commons.io.FileUtils;
72 import org.apache.commons.io.FilenameUtils;
73 import org.apache.commons.lang.StringUtils;
74 import org.apache.jackrabbit.webdav.DavException;
75 import org.apache.jackrabbit.webdav.DavResource;
76 import org.apache.jackrabbit.webdav.DavResourceFactory;
77 import org.apache.jackrabbit.webdav.DavResourceLocator;
78 import org.apache.jackrabbit.webdav.DavServletRequest;
79 import org.apache.jackrabbit.webdav.DavServletResponse;
80 import org.apache.jackrabbit.webdav.DavSession;
81 import org.apache.jackrabbit.webdav.lock.LockManager;
82 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
83 import org.apache.maven.index.context.IndexingContext;
84 import org.apache.maven.model.DistributionManagement;
85 import org.apache.maven.model.Model;
86 import org.apache.maven.model.Relocation;
87 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
88 import org.codehaus.plexus.digest.ChecksumFile;
89 import org.codehaus.plexus.digest.Digester;
90 import org.codehaus.plexus.digest.DigesterException;
91 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
94 import org.springframework.context.ApplicationContext;
95 import org.springframework.stereotype.Service;
97 import javax.annotation.PostConstruct;
98 import javax.inject.Inject;
99 import javax.inject.Named;
100 import javax.servlet.http.HttpServletResponse;
101 import javax.servlet.http.HttpSession;
103 import java.io.FileNotFoundException;
104 import java.io.FileReader;
105 import java.io.IOException;
106 import java.util.ArrayList;
107 import java.util.Date;
108 import java.util.HashMap;
109 import java.util.HashSet;
110 import java.util.List;
111 import java.util.Map;
112 import java.util.Set;
117 @Service ( "davResourceFactory#archiva" )
118 public class ArchivaDavResourceFactory
119 implements DavResourceFactory, Auditable
121 private static final String PROXIED_SUFFIX = " (proxied)";
123 private static final String HTTP_PUT_METHOD = "PUT";
125 private static final MavenXpp3Reader MAVEN_XPP_3_READER = new MavenXpp3Reader();
127 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
133 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
139 private RepositoryContentFactory repositoryFactory;
144 private RepositoryRequest repositoryRequest;
150 @Named ( value = "repositoryProxyConnectors#default" )
151 private RepositoryProxyConnectors connectors;
157 private MetadataTools metadataTools;
163 private MimeTypes mimeTypes;
168 private ArchivaConfiguration archivaConfiguration;
174 private ServletAuthenticator servletAuth;
180 @Named ( value = "httpAuthenticator#basic" )
181 private HttpAuthenticator httpAuth;
184 private RemoteRepositoryAdmin remoteRepositoryAdmin;
187 private IndexMerger indexMerger;
190 private RepositorySearch repositorySearch;
193 * Lock Manager - use simple implementation from JackRabbit
195 private final LockManager lockManager = new SimpleLockManager();
200 private ChecksumFile checksum;
205 private Digester digestSha1;
210 private Digester digestMd5;
216 @Named ( value = "archivaTaskScheduler#repository" )
217 private RepositoryArchivaTaskScheduler scheduler;
219 private ApplicationContext applicationContext;
222 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
223 ArchivaConfiguration archivaConfiguration )
224 throws PlexusSisuBridgeException
226 this.archivaConfiguration = archivaConfiguration;
227 this.applicationContext = applicationContext;
228 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
230 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
231 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
233 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
237 public void initialize()
242 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
243 final DavServletResponse response )
246 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
248 RepositoryGroupConfiguration repoGroupConfig =
249 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
251 String activePrincipal = getActivePrincipal( request );
253 List<String> resourcesInAbsolutePath = new ArrayList<String>();
255 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
256 DavResource resource;
257 if ( repoGroupConfig != null )
261 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
262 "Write method not allowed for repository groups." );
265 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
267 // handle browse requests for virtual repos
268 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
270 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
271 archivaLocator.getRepositoryId() );
275 // make a copy to avoid potential concurrent modifications (eg. by configuration)
276 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
278 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
279 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
280 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
288 RemoteRepository remoteRepository =
289 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
291 if ( remoteRepository != null )
293 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
294 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
295 File resourceFile = StringUtils.equals( logicalResource, "/" )
296 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
297 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
298 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
299 request.getRemoteAddr(), activePrincipal,
300 request.getDavSession(), archivaLocator, this, mimeTypes,
301 auditListeners, scheduler );
302 setHeaders( response, locator, resource );
306 catch ( RepositoryAdminException e )
308 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
309 archivaLocator.getRepositoryId(), e.getMessage() );
312 ManagedRepositoryContent managedRepository = null;
316 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
318 catch ( RepositoryNotFoundException e )
320 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
321 "Invalid repository: " + archivaLocator.getRepositoryId() );
323 catch ( RepositoryException e )
325 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
328 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
330 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
332 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
333 resourcesInAbsolutePath.add(
334 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
337 String requestedResource = request.getRequestURI();
339 // MRM-872 : merge all available metadata
340 // merge metadata only when requested via the repo group
341 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
342 requestedResource ) ) && repoGroupConfig != null )
344 // this should only be at the project level not version level!
345 if ( isProjectReference( requestedResource ) )
348 ArchivaDavResource res = (ArchivaDavResource) resource;
350 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
352 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
354 // for MRM-872 handle checksums of the merged metadata files
355 if ( repositoryRequest.isSupportFile( requestedResource ) )
357 File metadataChecksum =
358 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
359 if ( metadataChecksum.exists() )
361 LogicalResource logicalResource =
362 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
365 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
366 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
367 archivaLocator, this, mimeTypes, auditListeners, scheduler );
372 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
374 // merge the metadata of all repos under group
375 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
376 for ( String resourceAbsPath : resourcesInAbsolutePath )
380 File metadataFile = new File( resourceAbsPath );
381 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
382 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
384 catch ( XMLException e )
386 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
387 "Error occurred while reading metadata file." );
389 catch ( RepositoryMetadataException r )
391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
392 "Error occurred while merging metadata file." );
398 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
400 LogicalResource logicalResource = new LogicalResource(
401 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
404 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
405 request.getRemoteAddr(), activePrincipal,
406 request.getDavSession(), archivaLocator, this, mimeTypes,
407 auditListeners, scheduler );
409 catch ( RepositoryMetadataException r )
411 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
412 "Error occurred while writing metadata file." );
414 catch ( IOException ie )
416 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
417 "Error occurred while generating checksum files." );
419 catch ( DigesterException de )
421 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
422 "Error occurred while generating checksum files." );
429 setHeaders( response, locator, resource );
431 // compatibility with MRM-440 to ensure browsing the repository works ok
432 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
434 throw new BrowserRedirectException( resource.getHref() );
436 resource.addLockManager( lockManager );
440 private DavResource processRepositoryGroup( final DavServletRequest request,
441 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
442 String activePrincipal, List<String> resourcesInAbsolutePath,
443 String repositoryGroupId )
446 DavResource resource = null;
447 List<DavException> storedExceptions = new ArrayList<DavException>();
449 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
451 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
453 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
455 // we are in the case of index file request
456 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
457 File temporaryIndexDirectory =
458 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
460 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
461 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
462 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
463 archivaLocator, this, mimeTypes, auditListeners, scheduler );
468 for ( String repositoryId : repositories )
470 ManagedRepositoryContent managedRepository;
473 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
475 catch ( RepositoryNotFoundException e )
477 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
479 catch ( RepositoryException e )
481 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
486 DavResource updatedResource =
487 processRepository( request, archivaLocator, activePrincipal, managedRepository );
488 if ( resource == null )
490 resource = updatedResource;
493 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
494 if ( logicalResource.endsWith( "/" ) )
496 logicalResource = logicalResource.substring( 1 );
498 resourcesInAbsolutePath.add(
499 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
501 catch ( DavException e )
503 storedExceptions.add( e );
507 if ( resource == null )
509 if ( !storedExceptions.isEmpty() )
512 for ( DavException e : storedExceptions )
514 if ( 401 == e.getErrorCode() )
520 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
524 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
530 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
531 String activePrincipal, ManagedRepositoryContent managedRepository )
534 DavResource resource = null;
535 if ( isAuthorized( request, managedRepository.getId() ) )
537 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
538 if ( path.startsWith( "/" ) )
540 path = path.substring( 1 );
542 LogicalResource logicalResource = new LogicalResource( path );
543 File resourceFile = new File( managedRepository.getRepoRoot(), path );
544 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
545 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
546 archivaLocator, this, mimeTypes, auditListeners, scheduler );
548 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
550 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
552 // force a resource not found
553 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
557 if ( !resource.isCollection() )
559 boolean previouslyExisted = resourceFile.exists();
561 // Attempt to fetch the resource from any defined proxy.
562 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
564 // At this point the incoming request can either be in default or
565 // legacy layout format.
568 // Perform an adjustment of the resource to the managed
569 // repository expected path.
570 String localResourcePath =
571 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
572 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
574 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
575 managedRepository.getRepository(), request.getRemoteAddr(),
576 activePrincipal, request.getDavSession(), archivaLocator, this,
577 mimeTypes, auditListeners, scheduler );
579 catch ( LayoutException e )
581 if ( !resourceFile.exists() )
583 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
589 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
592 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
593 resourceFile.getName(), managedRepository.getId(), activePrincipal );
595 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
596 logicalResource.getPath(), event, activePrincipal );
599 if ( !resourceFile.exists() )
601 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
607 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
609 String resourcePath = logicalResource.getPath();
611 // check if target repo is enabled for releases
612 // we suppose that release-artifacts can be deployed only to repos enabled for releases
613 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
614 && !repositoryRequest.isSupportFile( resourcePath ) )
616 ArtifactReference artifact = null;
619 artifact = managedRepository.toArtifactReference( resourcePath );
621 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
623 // check if artifact already exists and if artifact re-deployment to the repository is allowed
624 if ( managedRepository.hasContent( artifact )
625 && managedRepository.getRepository().isBlockRedeployments() )
627 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
628 managedRepository.getId() );
629 throw new DavException( HttpServletResponse.SC_CONFLICT,
630 "Overwriting released artifacts is not allowed." );
634 catch ( LayoutException e )
636 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
641 * Create parent directories that don't exist when writing a file This actually makes this
642 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
643 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
644 * create the collections themselves.
647 File rootDirectory = new File( managedRepository.getRepoRoot() );
648 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
650 if ( !destDir.exists() )
653 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
655 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
658 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
659 AuditEvent.CREATE_DIR, activePrincipal );
666 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
669 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
671 ManagedRepositoryContent managedRepository;
674 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
676 catch ( RepositoryNotFoundException e )
678 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
679 "Invalid repository: " + archivaLocator.getRepositoryId() );
681 catch ( RepositoryException e )
683 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
686 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
687 if ( logicalResource.startsWith( "/" ) )
689 logicalResource = logicalResource.substring( 1 );
691 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
692 DavResource resource =
693 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
694 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
696 resource.addLockManager( lockManager );
700 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
701 LogicalResource resource )
704 String path = resource.getPath();
705 if ( repositoryRequest.isSupportFile( path ) )
707 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
709 return ( proxiedFile != null );
712 // Is it a Metadata resource?
713 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
715 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
718 // Is it an Archetype Catalog?
719 if ( repositoryRequest.isArchetypeCatalog( path ) )
721 // FIXME we must implement a merge of remote archetype catalog from remote servers.
722 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
724 return ( proxiedFile != null );
727 // Not any of the above? Then it's gotta be an artifact reference.
730 // Get the artifact reference in a layout neutral way.
731 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
733 if ( artifact != null )
735 applyServerSideRelocation( managedRepository, artifact );
737 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
739 resource.setPath( managedRepository.toPath( artifact ) );
741 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
742 artifact.getVersion() );
744 return ( proxiedFile != null );
747 catch ( LayoutException e )
751 catch ( ProxyDownloadException e )
753 log.error( e.getMessage(), e );
754 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
755 "Unable to fetch artifact resource." );
761 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
762 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
765 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
766 * metadatas and serving the expected artifact.
768 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
769 throws ProxyDownloadException
771 if ( "pom".equals( artifact.getType() ) )
776 // Build the artifact POM reference
777 ArtifactReference pomReference = new ArtifactReference();
778 pomReference.setGroupId( artifact.getGroupId() );
779 pomReference.setArtifactId( artifact.getArtifactId() );
780 pomReference.setVersion( artifact.getVersion() );
781 pomReference.setType( "pom" );
783 // Get the artifact POM from proxied repositories if needed
784 connectors.fetchFromProxies( managedRepository, pomReference );
786 // Open and read the POM from the managed repo
787 File pom = managedRepository.toFile( pomReference );
796 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
797 FileReader reader = new FileReader( pom );
801 model = MAVEN_XPP_3_READER.read( reader );
805 if ( reader != null )
811 DistributionManagement dist = model.getDistributionManagement();
814 Relocation relocation = dist.getRelocation();
815 if ( relocation != null )
817 // artifact is relocated : update the repositoryPath
818 if ( relocation.getGroupId() != null )
820 artifact.setGroupId( relocation.getGroupId() );
822 if ( relocation.getArtifactId() != null )
824 artifact.setArtifactId( relocation.getArtifactId() );
826 if ( relocation.getVersion() != null )
828 artifact.setVersion( relocation.getVersion() );
833 catch ( FileNotFoundException e )
835 // Artifact has no POM in repo : ignore
837 catch ( IOException e )
839 // Unable to read POM : ignore.
841 catch ( XmlPullParserException e )
843 // Invalid POM : ignore
849 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
852 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
853 event.setRemoteIP( remoteIP );
855 for ( AuditListener listener : auditListeners )
857 listener.auditEvent( event );
861 public void addAuditListener( AuditListener listener )
863 this.auditListeners.add( listener );
866 public void clearAuditListeners()
868 this.auditListeners.clear();
871 public void removeAuditListener( AuditListener listener )
873 this.auditListeners.remove( listener );
876 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
878 // [MRM-503] - Metadata file need Pragma:no-cache response
880 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
881 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
883 response.setHeader( "Pragma", "no-cache" );
884 response.setHeader( "Cache-Control", "no-cache" );
885 response.setDateHeader( "Last-Modified", new Date().getTime() );
887 // if the resource is a directory don't cache it as new groupId deployed will be available
888 // without need of refreshing browser
891 // We need to specify this so connecting wagons can work correctly
892 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
894 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
897 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
900 if ( !( locator instanceof ArchivaDavResourceLocator ) )
902 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
903 "Locator does not implement RepositoryLocator" );
907 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
909 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
912 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
914 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
915 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
917 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
919 return archivaLocator;
922 private static class LogicalResource
926 public LogicalResource( String path )
931 public String getPath()
936 public void setPath( String path )
942 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
947 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
948 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
950 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
952 WebdavMethodUtil.getMethodPermission(
953 request.getMethod() ) );
955 catch ( AuthenticationException e )
957 // safety check for MRM-911
958 String guest = UserManager.GUEST_USERNAME;
961 if ( servletAuth.isAuthorized( guest,
962 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
963 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
968 catch ( UnauthorizedException ae )
970 throw new UnauthorizedDavException( repositoryId,
971 "You are not authenticated and authorized to access any repository." );
974 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
976 catch ( MustChangePasswordException e )
978 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
980 catch ( AccountLockedException e )
982 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
984 catch ( AuthorizationException e )
986 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
987 "Fatal Authorization Subsystem Error." );
989 catch ( UnauthorizedException e )
991 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
995 private DavResource getResource( DavServletRequest request, List<String> repositories,
996 ArchivaDavResourceLocator locator, String groupId )
999 List<File> mergedRepositoryContents = new ArrayList<File>();
1000 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
1001 if ( path.startsWith( "/" ) )
1003 path = path.substring( 1 );
1005 LogicalResource logicalResource = new LogicalResource( path );
1008 // if the current user logged in has permission to any of the repositories, allow user to
1009 // browse the repo group but displaying only the repositories which the user has permission to access.
1010 // otherwise, prompt for authentication.
1012 String activePrincipal = getActivePrincipal( request );
1014 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1020 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1021 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
1023 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
1024 mergedRepositoryContents.add( mergedRepoDir );
1028 for ( String repository : repositories )
1030 ManagedRepositoryContent managedRepository = null;
1034 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1036 catch ( RepositoryNotFoundException e )
1038 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1039 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1041 catch ( RepositoryException e )
1043 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1044 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1047 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1048 if ( resourceFile.exists() )
1050 // in case of group displaying index directory doesn't have sense !!
1051 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1052 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1054 if ( !new File( repoIndexDirectory ).isAbsolute() )
1056 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1057 StringUtils.isEmpty( repoIndexDirectory )
1059 : repoIndexDirectory ).getAbsolutePath();
1062 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1064 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1065 ".indexer" ).getAbsolutePath();
1068 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1069 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1071 // for prompted authentication
1072 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1076 if ( isAuthorized( request, repository ) )
1078 mergedRepositoryContents.add( resourceFile );
1079 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1082 catch ( DavException e )
1084 // TODO: review exception handling
1086 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1087 activePrincipal, e.getMessage() );
1094 // for the current user logged in
1097 if ( servletAuth.isAuthorized( activePrincipal, repository,
1098 WebdavMethodUtil.getMethodPermission(
1099 request.getMethod() ) ) )
1101 mergedRepositoryContents.add( resourceFile );
1102 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1105 catch ( UnauthorizedException e )
1107 // TODO: review exception handling
1109 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1110 activePrincipal, e.getMessage() );
1121 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1124 ArchivaVirtualDavResource resource =
1125 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1128 // compatibility with MRM-440 to ensure browsing the repository group works ok
1129 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1131 throw new BrowserRedirectException( resource.getHref() );
1137 protected String getActivePrincipal( DavServletRequest request )
1139 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1140 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1144 * Check if the current user is authorized to access any of the repos
1147 * @param repositories
1148 * @param activePrincipal
1151 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1153 // when no repositories configured it's impossible to browse nothing !
1154 // at least make possible to see nothing :-)
1155 if ( repositories == null || repositories.isEmpty() )
1160 boolean allow = false;
1162 // if securitySession != null, it means that the user was prompted for authentication
1163 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1165 for ( String repository : repositories )
1169 if ( isAuthorized( request, repository ) )
1175 catch ( DavException e )
1183 for ( String repository : repositories )
1187 if ( servletAuth.isAuthorized( activePrincipal, repository,
1188 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1194 catch ( UnauthorizedException e )
1204 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1205 throws RepositoryMetadataException, DigesterException, IOException
1207 File outputFile = new File( outputFilename );
1208 if ( outputFile.exists() )
1210 FileUtils.deleteQuietly( outputFile );
1213 outputFile.getParentFile().mkdirs();
1214 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1216 createChecksumFile( outputFilename, digestSha1 );
1217 createChecksumFile( outputFilename, digestMd5 );
1222 private void createChecksumFile( String path, Digester digester )
1223 throws DigesterException, IOException
1225 File checksumFile = new File( path + digester.getFilenameExtension() );
1226 if ( !checksumFile.exists() )
1228 FileUtils.deleteQuietly( checksumFile );
1229 checksum.createChecksum( new File( path ), digester );
1231 else if ( !checksumFile.isFile() )
1233 log.error( "Checksum file is not a file." );
1237 private boolean isProjectReference( String requestedResource )
1241 metadataTools.toVersionedReference( requestedResource );
1244 catch ( RepositoryMetadataException re )
1250 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1251 DavServletRequest request, String groupId )
1257 HttpSession session = request.getSession();
1259 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1260 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1261 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1262 if ( temporaryGroupIndexMap == null )
1264 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1267 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1269 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1271 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getDefaultGroupIndexTtl() * 60
1274 log.debug( "tmp group index is too old so delete it" );
1275 indexMerger.cleanTemporaryGroupIndex( tmp );
1279 return tmp.getDirectory();
1283 Set<String> authzRepos = new HashSet<String>();
1284 for ( String repository : repositories )
1288 if ( servletAuth.isAuthorized( activePrincipal, repository,
1289 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1291 authzRepos.add( repository );
1292 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1295 catch ( UnauthorizedException e )
1297 // TODO: review exception handling
1299 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1303 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'", groupId,
1305 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1306 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1307 TemporaryGroupIndex temporaryGroupIndex =
1308 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1309 new Date().getTime() );
1310 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1311 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1312 temporaryGroupIndexMap );
1313 return mergedRepoDir;
1315 catch ( RepositoryAdminException e )
1317 throw new DavException( 500, e );
1319 catch ( IndexMergerException e )
1321 throw new DavException( 500, e );
1326 public void setServletAuth( ServletAuthenticator servletAuth )
1328 this.servletAuth = servletAuth;
1331 public void setHttpAuth( HttpAuthenticator httpAuth )
1333 this.httpAuth = httpAuth;
1336 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1338 this.scheduler = scheduler;
1341 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1343 this.archivaConfiguration = archivaConfiguration;
1346 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1348 this.repositoryFactory = repositoryFactory;
1351 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1353 this.repositoryRequest = repositoryRequest;
1356 public void setConnectors( RepositoryProxyConnectors connectors )
1358 this.connectors = connectors;
1361 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1363 return remoteRepositoryAdmin;
1366 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1368 this.remoteRepositoryAdmin = remoteRepositoryAdmin;