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.merger.TemporaryGroupIndex;
35 import org.apache.archiva.indexer.search.RepositorySearch;
36 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
37 import org.apache.archiva.model.ArchivaRepositoryMetadata;
38 import org.apache.archiva.model.ArtifactReference;
39 import org.apache.archiva.policies.ProxyDownloadException;
40 import org.apache.archiva.proxy.RepositoryProxyConnectors;
41 import org.apache.archiva.redback.authentication.AuthenticationException;
42 import org.apache.archiva.redback.authentication.AuthenticationResult;
43 import org.apache.archiva.redback.authorization.AuthorizationException;
44 import org.apache.archiva.redback.authorization.UnauthorizedException;
45 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
46 import org.apache.archiva.redback.policy.AccountLockedException;
47 import org.apache.archiva.redback.policy.MustChangePasswordException;
48 import org.apache.archiva.redback.system.SecuritySession;
49 import org.apache.archiva.redback.users.User;
50 import org.apache.archiva.redback.users.UserManager;
51 import org.apache.archiva.repository.ManagedRepositoryContent;
52 import org.apache.archiva.repository.RepositoryContentFactory;
53 import org.apache.archiva.repository.RepositoryException;
54 import org.apache.archiva.repository.RepositoryNotFoundException;
55 import org.apache.archiva.repository.content.LegacyPathParser;
56 import org.apache.archiva.repository.content.RepositoryRequest;
57 import org.apache.archiva.repository.layout.LayoutException;
58 import org.apache.archiva.repository.metadata.MetadataTools;
59 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
61 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
62 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
63 import org.apache.archiva.security.ServletAuthenticator;
64 import org.apache.archiva.webdav.util.MimeTypes;
65 import org.apache.archiva.webdav.util.RepositoryPathUtil;
66 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
67 import org.apache.archiva.webdav.util.WebdavMethodUtil;
68 import org.apache.archiva.xml.XMLException;
69 import org.apache.commons.io.FileUtils;
70 import org.apache.commons.io.FilenameUtils;
71 import org.apache.commons.lang.StringUtils;
72 import org.apache.jackrabbit.webdav.DavException;
73 import org.apache.jackrabbit.webdav.DavResource;
74 import org.apache.jackrabbit.webdav.DavResourceFactory;
75 import org.apache.jackrabbit.webdav.DavResourceLocator;
76 import org.apache.jackrabbit.webdav.DavServletRequest;
77 import org.apache.jackrabbit.webdav.DavServletResponse;
78 import org.apache.jackrabbit.webdav.DavSession;
79 import org.apache.jackrabbit.webdav.lock.LockManager;
80 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
81 import org.apache.maven.index.context.IndexingContext;
82 import org.apache.maven.model.DistributionManagement;
83 import org.apache.maven.model.Model;
84 import org.apache.maven.model.Relocation;
85 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
86 import org.codehaus.plexus.digest.ChecksumFile;
87 import org.codehaus.plexus.digest.Digester;
88 import org.codehaus.plexus.digest.DigesterException;
89 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92 import org.springframework.context.ApplicationContext;
93 import org.springframework.stereotype.Service;
95 import javax.annotation.PostConstruct;
96 import javax.inject.Inject;
97 import javax.inject.Named;
98 import javax.servlet.http.HttpServletResponse;
99 import javax.servlet.http.HttpSession;
101 import java.io.FileNotFoundException;
102 import java.io.FileReader;
103 import java.io.IOException;
104 import java.util.ArrayList;
105 import java.util.Date;
106 import java.util.HashMap;
107 import java.util.HashSet;
108 import java.util.List;
109 import java.util.Map;
110 import java.util.Set;
115 @Service ( "davResourceFactory#archiva" )
116 public class ArchivaDavResourceFactory
117 implements DavResourceFactory, Auditable
119 private static final String PROXIED_SUFFIX = " (proxied)";
121 private static final String HTTP_PUT_METHOD = "PUT";
123 private static final MavenXpp3Reader MAVEN_XPP_3_READER = new MavenXpp3Reader();
125 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
131 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
137 private RepositoryContentFactory repositoryFactory;
142 private RepositoryRequest repositoryRequest;
148 @Named ( value = "repositoryProxyConnectors#default" )
149 private RepositoryProxyConnectors connectors;
155 private MetadataTools metadataTools;
161 private MimeTypes mimeTypes;
166 private ArchivaConfiguration archivaConfiguration;
172 private ServletAuthenticator servletAuth;
178 @Named ( value = "httpAuthenticator#basic" )
179 private HttpAuthenticator httpAuth;
182 private IndexMerger indexMerger;
185 private RepositorySearch repositorySearch;
188 * Lock Manager - use simple implementation from JackRabbit
190 private final LockManager lockManager = new SimpleLockManager();
195 private ChecksumFile checksum;
200 private Digester digestSha1;
205 private Digester digestMd5;
211 @Named ( value = "archivaTaskScheduler#repository" )
212 private RepositoryArchivaTaskScheduler scheduler;
214 private ApplicationContext applicationContext;
217 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
218 ArchivaConfiguration archivaConfiguration )
219 throws PlexusSisuBridgeException
221 this.archivaConfiguration = archivaConfiguration;
222 this.applicationContext = applicationContext;
223 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
225 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
226 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
228 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
232 public void initialize()
237 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
238 final DavServletResponse response )
241 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
243 RepositoryGroupConfiguration repoGroupConfig =
244 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
246 String activePrincipal = getActivePrincipal( request );
248 List<String> resourcesInAbsolutePath = new ArrayList<String>();
250 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
251 DavResource resource;
252 if ( repoGroupConfig != null )
256 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
257 "Write method not allowed for repository groups." );
260 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
262 // handle browse requests for virtual repos
263 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
265 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
266 archivaLocator.getRepositoryId() );
270 // make a copy to avoid potential concurrent modifications (eg. by configuration)
271 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
273 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
274 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
275 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
280 ManagedRepositoryContent managedRepository = null;
284 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
286 catch ( RepositoryNotFoundException e )
288 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
289 "Invalid repository: " + archivaLocator.getRepositoryId() );
291 catch ( RepositoryException e )
293 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
296 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
298 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
300 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
301 resourcesInAbsolutePath.add(
302 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
305 String requestedResource = request.getRequestURI();
307 // MRM-872 : merge all available metadata
308 // merge metadata only when requested via the repo group
309 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
310 requestedResource ) ) && repoGroupConfig != null )
312 // this should only be at the project level not version level!
313 if ( isProjectReference( requestedResource ) )
315 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
316 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
318 ArchivaDavResource res = (ArchivaDavResource) resource;
320 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
322 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
324 // for MRM-872 handle checksums of the merged metadata files
325 if ( repositoryRequest.isSupportFile( requestedResource ) )
327 File metadataChecksum =
328 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
329 if ( metadataChecksum.exists() )
331 LogicalResource logicalResource =
332 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
335 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
336 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
337 archivaLocator, this, mimeTypes, auditListeners, scheduler );
342 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
344 // merge the metadata of all repos under group
345 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
346 for ( String resourceAbsPath : resourcesInAbsolutePath )
350 File metadataFile = new File( resourceAbsPath );
351 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
352 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
354 catch ( XMLException e )
356 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
357 "Error occurred while reading metadata file." );
359 catch ( RepositoryMetadataException r )
361 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
362 "Error occurred while merging metadata file." );
368 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
370 LogicalResource logicalResource = new LogicalResource(
371 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
374 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
375 request.getRemoteAddr(), activePrincipal,
376 request.getDavSession(), archivaLocator, this, mimeTypes,
377 auditListeners, scheduler );
379 catch ( RepositoryMetadataException r )
381 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
382 "Error occurred while writing metadata file." );
384 catch ( IOException ie )
386 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
387 "Error occurred while generating checksum files." );
389 catch ( DigesterException de )
391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
392 "Error occurred while generating checksum files." );
399 setHeaders( response, locator, resource );
401 // compatibility with MRM-440 to ensure browsing the repository works ok
402 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
404 throw new BrowserRedirectException( resource.getHref() );
406 resource.addLockManager( lockManager );
410 private DavResource processRepositoryGroup( final DavServletRequest request,
411 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
412 String activePrincipal, List<String> resourcesInAbsolutePath,
413 String repositoryGroupId )
416 DavResource resource = null;
417 List<DavException> storedExceptions = new ArrayList<DavException>();
419 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
421 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
423 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
425 // we are in the case of index file request
426 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
427 File temporaryIndexDirectory =
428 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
430 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
431 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
432 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
433 archivaLocator, this, mimeTypes, auditListeners, scheduler );
438 for ( String repositoryId : repositories )
440 ManagedRepositoryContent managedRepository;
443 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
445 catch ( RepositoryNotFoundException e )
447 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
449 catch ( RepositoryException e )
451 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
456 DavResource updatedResource =
457 processRepository( request, archivaLocator, activePrincipal, managedRepository );
458 if ( resource == null )
460 resource = updatedResource;
463 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
464 if ( logicalResource.endsWith( "/" ) )
466 logicalResource = logicalResource.substring( 1 );
468 resourcesInAbsolutePath.add(
469 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
471 catch ( DavException e )
473 storedExceptions.add( e );
477 if ( resource == null )
479 if ( !storedExceptions.isEmpty() )
482 for ( DavException e : storedExceptions )
484 if ( 401 == e.getErrorCode() )
490 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
494 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
500 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
501 String activePrincipal, ManagedRepositoryContent managedRepository )
504 DavResource resource = null;
505 if ( isAuthorized( request, managedRepository.getId() ) )
507 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
508 if ( path.startsWith( "/" ) )
510 path = path.substring( 1 );
512 LogicalResource logicalResource = new LogicalResource( path );
513 File resourceFile = new File( managedRepository.getRepoRoot(), path );
514 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
515 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
516 archivaLocator, this, mimeTypes, auditListeners, scheduler );
518 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
520 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
522 // force a resource not found
523 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
527 if ( !resource.isCollection() )
529 boolean previouslyExisted = resourceFile.exists();
531 // Attempt to fetch the resource from any defined proxy.
532 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
534 // At this point the incoming request can either be in default or
535 // legacy layout format.
538 // Perform an adjustment of the resource to the managed
539 // repository expected path.
540 String localResourcePath =
541 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
542 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
544 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
545 managedRepository.getRepository(), request.getRemoteAddr(),
546 activePrincipal, request.getDavSession(), archivaLocator, this,
547 mimeTypes, auditListeners, scheduler );
549 catch ( LayoutException e )
551 if ( !resourceFile.exists() )
553 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
559 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
562 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
563 resourceFile.getName(), managedRepository.getId(), activePrincipal );
565 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
566 logicalResource.getPath(), event, activePrincipal );
569 if ( !resourceFile.exists() )
571 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
577 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
579 String resourcePath = logicalResource.getPath();
581 // check if target repo is enabled for releases
582 // we suppose that release-artifacts can be deployed only to repos enabled for releases
583 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
584 && !repositoryRequest.isSupportFile( resourcePath ) )
586 ArtifactReference artifact = null;
589 artifact = managedRepository.toArtifactReference( resourcePath );
591 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
593 // check if artifact already exists and if artifact re-deployment to the repository is allowed
594 if ( managedRepository.hasContent( artifact )
595 && managedRepository.getRepository().isBlockRedeployments() )
597 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
598 + "' is not allowed." );
599 throw new DavException( HttpServletResponse.SC_CONFLICT,
600 "Overwriting released artifacts is not allowed." );
604 catch ( LayoutException e )
606 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
611 * Create parent directories that don't exist when writing a file This actually makes this
612 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
613 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
614 * create the collections themselves.
617 File rootDirectory = new File( managedRepository.getRepoRoot() );
618 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
620 if ( !destDir.exists() )
623 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
625 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
628 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
629 AuditEvent.CREATE_DIR, activePrincipal );
636 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
639 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
641 ManagedRepositoryContent managedRepository;
644 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
646 catch ( RepositoryNotFoundException e )
648 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
649 "Invalid repository: " + archivaLocator.getRepositoryId() );
651 catch ( RepositoryException e )
653 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
656 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
657 if ( logicalResource.startsWith( "/" ) )
659 logicalResource = logicalResource.substring( 1 );
661 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
662 DavResource resource =
663 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
664 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
666 resource.addLockManager( lockManager );
670 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
671 LogicalResource resource )
674 String path = resource.getPath();
675 if ( repositoryRequest.isSupportFile( path ) )
677 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
679 return ( proxiedFile != null );
682 // Is it a Metadata resource?
683 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
685 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
688 // Is it an Archetype Catalog?
689 if ( repositoryRequest.isArchetypeCatalog( path ) )
691 // FIXME we must implement a merge of remote archetype catalog from remote servers.
692 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
694 return ( proxiedFile != null );
697 // Not any of the above? Then it's gotta be an artifact reference.
700 // Get the artifact reference in a layout neutral way.
701 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
703 if ( artifact != null )
705 applyServerSideRelocation( managedRepository, artifact );
707 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
709 resource.setPath( managedRepository.toPath( artifact ) );
711 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
712 artifact.getVersion() );
714 return ( proxiedFile != null );
717 catch ( LayoutException e )
721 catch ( ProxyDownloadException e )
723 log.error( e.getMessage(), e );
724 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
725 "Unable to fetch artifact resource." );
731 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
732 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
735 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
736 * metadatas and serving the expected artifact.
738 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
739 throws ProxyDownloadException
741 if ( "pom".equals( artifact.getType() ) )
746 // Build the artifact POM reference
747 ArtifactReference pomReference = new ArtifactReference();
748 pomReference.setGroupId( artifact.getGroupId() );
749 pomReference.setArtifactId( artifact.getArtifactId() );
750 pomReference.setVersion( artifact.getVersion() );
751 pomReference.setType( "pom" );
753 // Get the artifact POM from proxied repositories if needed
754 connectors.fetchFromProxies( managedRepository, pomReference );
756 // Open and read the POM from the managed repo
757 File pom = managedRepository.toFile( pomReference );
766 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
767 FileReader reader = new FileReader( pom );
771 model = MAVEN_XPP_3_READER.read( reader );
775 if ( reader != null )
781 DistributionManagement dist = model.getDistributionManagement();
784 Relocation relocation = dist.getRelocation();
785 if ( relocation != null )
787 // artifact is relocated : update the repositoryPath
788 if ( relocation.getGroupId() != null )
790 artifact.setGroupId( relocation.getGroupId() );
792 if ( relocation.getArtifactId() != null )
794 artifact.setArtifactId( relocation.getArtifactId() );
796 if ( relocation.getVersion() != null )
798 artifact.setVersion( relocation.getVersion() );
803 catch ( FileNotFoundException e )
805 // Artifact has no POM in repo : ignore
807 catch ( IOException e )
809 // Unable to read POM : ignore.
811 catch ( XmlPullParserException e )
813 // Invalid POM : ignore
819 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
822 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
823 event.setRemoteIP( remoteIP );
825 for ( AuditListener listener : auditListeners )
827 listener.auditEvent( event );
831 public void addAuditListener( AuditListener listener )
833 this.auditListeners.add( listener );
836 public void clearAuditListeners()
838 this.auditListeners.clear();
841 public void removeAuditListener( AuditListener listener )
843 this.auditListeners.remove( listener );
846 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
848 // [MRM-503] - Metadata file need Pragma:no-cache response
850 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
851 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
853 response.setHeader( "Pragma", "no-cache" );
854 response.setHeader( "Cache-Control", "no-cache" );
855 response.setDateHeader( "Last-Modified", new Date().getTime() );
857 // if the resource is a directory don't cache it as new groupId deployed will be available
858 // without need of refreshing browser
861 // We need to specify this so connecting wagons can work correctly
862 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
864 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
867 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
870 if ( !( locator instanceof ArchivaDavResourceLocator ) )
872 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
873 "Locator does not implement RepositoryLocator" );
877 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
879 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
882 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
884 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
885 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
887 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
889 return archivaLocator;
892 private static class LogicalResource
896 public LogicalResource( String path )
901 public String getPath()
906 public void setPath( String path )
912 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
917 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
918 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
920 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
922 WebdavMethodUtil.getMethodPermission(
923 request.getMethod() ) );
925 catch ( AuthenticationException e )
927 // safety check for MRM-911
928 String guest = UserManager.GUEST_USERNAME;
931 if ( servletAuth.isAuthorized( guest,
932 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
933 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
938 catch ( UnauthorizedException ae )
940 throw new UnauthorizedDavException( repositoryId,
941 "You are not authenticated and authorized to access any repository." );
944 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
946 catch ( MustChangePasswordException e )
948 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
950 catch ( AccountLockedException e )
952 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
954 catch ( AuthorizationException e )
956 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
957 "Fatal Authorization Subsystem Error." );
959 catch ( UnauthorizedException e )
961 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
965 private DavResource getResource( DavServletRequest request, List<String> repositories,
966 ArchivaDavResourceLocator locator, String groupId )
969 List<File> mergedRepositoryContents = new ArrayList<File>();
970 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
971 if ( path.startsWith( "/" ) )
973 path = path.substring( 1 );
975 LogicalResource logicalResource = new LogicalResource( path );
978 // if the current user logged in has permission to any of the repositories, allow user to
979 // browse the repo group but displaying only the repositories which the user has permission to access.
980 // otherwise, prompt for authentication.
982 String activePrincipal = getActivePrincipal( request );
984 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
990 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
991 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
993 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
994 mergedRepositoryContents.add( mergedRepoDir );
998 for ( String repository : repositories )
1000 ManagedRepositoryContent managedRepository = null;
1004 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1006 catch ( RepositoryNotFoundException e )
1008 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1009 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1011 catch ( RepositoryException e )
1013 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1014 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1017 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1018 if ( resourceFile.exists() )
1020 // in case of group displaying index directory doesn't have sense !!
1021 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1022 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1024 if ( !new File( repoIndexDirectory ).isAbsolute() )
1026 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1027 StringUtils.isEmpty( repoIndexDirectory )
1029 : repoIndexDirectory ).getAbsolutePath();
1032 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1034 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1035 ".indexer" ).getAbsolutePath();
1038 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1039 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1041 // for prompted authentication
1042 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1046 if ( isAuthorized( request, repository ) )
1048 mergedRepositoryContents.add( resourceFile );
1049 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1052 catch ( DavException e )
1054 // TODO: review exception handling
1056 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1057 activePrincipal, e.getMessage() );
1064 // for the current user logged in
1067 if ( servletAuth.isAuthorized( activePrincipal, repository,
1068 WebdavMethodUtil.getMethodPermission(
1069 request.getMethod() ) ) )
1071 mergedRepositoryContents.add( resourceFile );
1072 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1075 catch ( UnauthorizedException e )
1077 // TODO: review exception handling
1079 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1080 activePrincipal, e.getMessage() );
1091 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1094 ArchivaVirtualDavResource resource =
1095 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1098 // compatibility with MRM-440 to ensure browsing the repository group works ok
1099 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1101 throw new BrowserRedirectException( resource.getHref() );
1107 protected String getActivePrincipal( DavServletRequest request )
1109 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1110 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1114 * Check if the current user is authorized to access any of the repos
1117 * @param repositories
1118 * @param activePrincipal
1121 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1123 boolean allow = false;
1125 // if securitySession != null, it means that the user was prompted for authentication
1126 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1128 for ( String repository : repositories )
1132 if ( isAuthorized( request, repository ) )
1138 catch ( DavException e )
1146 for ( String repository : repositories )
1150 if ( servletAuth.isAuthorized( activePrincipal, repository,
1151 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1157 catch ( UnauthorizedException e )
1167 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1168 throws RepositoryMetadataException, DigesterException, IOException
1170 File outputFile = new File( outputFilename );
1171 if ( outputFile.exists() )
1173 FileUtils.deleteQuietly( outputFile );
1176 outputFile.getParentFile().mkdirs();
1177 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1179 createChecksumFile( outputFilename, digestSha1 );
1180 createChecksumFile( outputFilename, digestMd5 );
1185 private void createChecksumFile( String path, Digester digester )
1186 throws DigesterException, IOException
1188 File checksumFile = new File( path + digester.getFilenameExtension() );
1189 if ( !checksumFile.exists() )
1191 FileUtils.deleteQuietly( checksumFile );
1192 checksum.createChecksum( new File( path ), digester );
1194 else if ( !checksumFile.isFile() )
1196 log.error( "Checksum file is not a file." );
1200 private boolean isProjectReference( String requestedResource )
1204 metadataTools.toVersionedReference( requestedResource );
1207 catch ( RepositoryMetadataException re )
1213 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1214 DavServletRequest request, String groupId )
1220 HttpSession session = request.getSession();
1222 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1223 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1224 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1225 if ( temporaryGroupIndexMap == null )
1227 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1230 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1232 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1234 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getDefaultGroupIndexTtl() * 60
1237 log.debug( "tmp group index is too old so delete it" );
1238 indexMerger.cleanTemporaryGroupIndex( tmp );
1242 return tmp.getDirectory();
1246 Set<String> authzRepos = new HashSet<String>();
1247 for ( String repository : repositories )
1251 if ( servletAuth.isAuthorized( activePrincipal, repository,
1252 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1254 authzRepos.add( repository );
1255 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1258 catch ( UnauthorizedException e )
1260 // TODO: review exception handling
1262 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1266 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1267 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1268 TemporaryGroupIndex temporaryGroupIndex =
1269 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1270 new Date().getTime() );
1271 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1272 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1273 temporaryGroupIndexMap );
1274 return mergedRepoDir;
1276 catch ( RepositoryAdminException e )
1278 throw new DavException( 500, e );
1280 catch ( IndexMergerException e )
1282 throw new DavException( 500, e );
1287 public void setServletAuth( ServletAuthenticator servletAuth )
1289 this.servletAuth = servletAuth;
1292 public void setHttpAuth( HttpAuthenticator httpAuth )
1294 this.httpAuth = httpAuth;
1297 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1299 this.scheduler = scheduler;
1302 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1304 this.archivaConfiguration = archivaConfiguration;
1307 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1309 this.repositoryFactory = repositoryFactory;
1312 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1314 this.repositoryRequest = repositoryRequest;
1317 public void setConnectors( RepositoryProxyConnectors connectors )
1319 this.connectors = connectors;