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.repository.ManagedRepositoryContent;
42 import org.apache.archiva.repository.RepositoryContentFactory;
43 import org.apache.archiva.repository.RepositoryException;
44 import org.apache.archiva.repository.RepositoryNotFoundException;
45 import org.apache.archiva.repository.content.LegacyPathParser;
46 import org.apache.archiva.repository.content.RepositoryRequest;
47 import org.apache.archiva.repository.layout.LayoutException;
48 import org.apache.archiva.repository.metadata.MetadataTools;
49 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
50 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
51 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
52 import org.apache.archiva.scheduler.repository.RepositoryArchivaTaskScheduler;
53 import org.apache.archiva.security.ServletAuthenticator;
54 import org.apache.archiva.webdav.util.MimeTypes;
55 import org.apache.archiva.webdav.util.RepositoryPathUtil;
56 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
57 import org.apache.archiva.webdav.util.WebdavMethodUtil;
58 import org.apache.archiva.xml.XMLException;
59 import org.apache.commons.io.FileUtils;
60 import org.apache.commons.io.FilenameUtils;
61 import org.apache.commons.lang.StringUtils;
62 import org.apache.jackrabbit.webdav.DavException;
63 import org.apache.jackrabbit.webdav.DavResource;
64 import org.apache.jackrabbit.webdav.DavResourceFactory;
65 import org.apache.jackrabbit.webdav.DavResourceLocator;
66 import org.apache.jackrabbit.webdav.DavServletRequest;
67 import org.apache.jackrabbit.webdav.DavServletResponse;
68 import org.apache.jackrabbit.webdav.DavSession;
69 import org.apache.jackrabbit.webdav.lock.LockManager;
70 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
71 import org.apache.maven.index.context.IndexingContext;
72 import org.apache.maven.model.DistributionManagement;
73 import org.apache.maven.model.Model;
74 import org.apache.maven.model.Relocation;
75 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
76 import org.codehaus.plexus.digest.ChecksumFile;
77 import org.codehaus.plexus.digest.Digester;
78 import org.codehaus.plexus.digest.DigesterException;
79 import org.apache.archiva.redback.authentication.AuthenticationException;
80 import org.apache.archiva.redback.authentication.AuthenticationResult;
81 import org.codehaus.plexus.redback.authorization.AuthorizationException;
82 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
83 import org.codehaus.plexus.redback.policy.AccountLockedException;
84 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
85 import org.codehaus.plexus.redback.system.SecuritySession;
86 import org.apache.archiva.redback.users.User;
87 import org.apache.archiva.redback.users.UserManager;
88 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
89 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
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 Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
129 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
135 private RepositoryContentFactory repositoryFactory;
140 private RepositoryRequest repositoryRequest;
146 @Named( value = "repositoryProxyConnectors#default" )
147 private RepositoryProxyConnectors connectors;
153 private MetadataTools metadataTools;
159 private MimeTypes mimeTypes;
164 private ArchivaConfiguration archivaConfiguration;
170 private ServletAuthenticator servletAuth;
176 @Named( value = "httpAuthenticator#basic" )
177 private HttpAuthenticator httpAuth;
180 private IndexMerger indexMerger;
183 private RepositorySearch repositorySearch;
186 * Lock Manager - use simple implementation from JackRabbit
188 private final LockManager lockManager = new SimpleLockManager();
193 private ChecksumFile checksum;
198 private Digester digestSha1;
203 private Digester digestMd5;
209 @Named( value = "archivaTaskScheduler#repository" )
210 private RepositoryArchivaTaskScheduler scheduler;
212 private ApplicationContext applicationContext;
215 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
216 ArchivaConfiguration archivaConfiguration )
217 throws PlexusSisuBridgeException
219 this.archivaConfiguration = archivaConfiguration;
220 this.applicationContext = applicationContext;
221 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
223 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
224 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
226 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
230 public void initialize()
235 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
236 final DavServletResponse response )
239 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
241 RepositoryGroupConfiguration repoGroupConfig =
242 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
244 String activePrincipal = getActivePrincipal( request );
246 List<String> resourcesInAbsolutePath = new ArrayList<String>();
248 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
249 DavResource resource;
250 if ( repoGroupConfig != null )
254 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
255 "Write method not allowed for repository groups." );
258 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
260 // handle browse requests for virtual repos
261 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
263 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator,
264 archivaLocator.getRepositoryId() );
268 // make a copy to avoid potential concurrent modifications (eg. by configuration)
269 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
271 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
272 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
273 resourcesInAbsolutePath, archivaLocator.getRepositoryId() );
278 ManagedRepositoryContent managedRepository = null;
282 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
284 catch ( RepositoryNotFoundException e )
286 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
287 "Invalid repository: " + archivaLocator.getRepositoryId() );
289 catch ( RepositoryException e )
291 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
294 log.debug( "Managed repository '{}' accessed by '{}'", managedRepository.getId(), activePrincipal );
296 resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
298 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
299 resourcesInAbsolutePath.add(
300 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
303 String requestedResource = request.getRequestURI();
305 // MRM-872 : merge all available metadata
306 // merge metadata only when requested via the repo group
307 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
308 requestedResource ) ) && repoGroupConfig != null )
310 // this should only be at the project level not version level!
311 if ( isProjectReference( requestedResource ) )
313 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
314 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
316 ArchivaDavResource res = (ArchivaDavResource) resource;
318 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
320 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
322 // for MRM-872 handle checksums of the merged metadata files
323 if ( repositoryRequest.isSupportFile( requestedResource ) )
325 File metadataChecksum =
326 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
327 if ( metadataChecksum.exists() )
329 LogicalResource logicalResource =
330 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
333 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
334 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
335 archivaLocator, this, mimeTypes, auditListeners, scheduler );
340 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
342 // merge the metadata of all repos under group
343 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
344 for ( String resourceAbsPath : resourcesInAbsolutePath )
348 File metadataFile = new File( resourceAbsPath );
349 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
350 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
352 catch ( XMLException e )
354 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
355 "Error occurred while reading metadata file." );
357 catch ( RepositoryMetadataException r )
359 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
360 "Error occurred while merging metadata file." );
366 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
368 LogicalResource logicalResource = new LogicalResource(
369 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
372 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
373 request.getRemoteAddr(), activePrincipal,
374 request.getDavSession(), archivaLocator, this, mimeTypes,
375 auditListeners, scheduler );
377 catch ( RepositoryMetadataException r )
379 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
380 "Error occurred while writing metadata file." );
382 catch ( IOException ie )
384 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
385 "Error occurred while generating checksum files." );
387 catch ( DigesterException de )
389 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
390 "Error occurred while generating checksum files." );
397 setHeaders( response, locator, resource );
399 // compatibility with MRM-440 to ensure browsing the repository works ok
400 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
402 throw new BrowserRedirectException( resource.getHref() );
404 resource.addLockManager( lockManager );
408 private DavResource processRepositoryGroup( final DavServletRequest request,
409 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
410 String activePrincipal, List<String> resourcesInAbsolutePath,
411 String repositoryGroupId )
414 DavResource resource = null;
415 List<DavException> storedExceptions = new ArrayList<DavException>();
417 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
419 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
421 if ( StringUtils.endsWith( rootPath, "/.indexer" ) )
423 // we are in the case of index file request
424 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
425 File temporaryIndexDirectory =
426 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupId );
428 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
429 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
430 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
431 archivaLocator, this, mimeTypes, auditListeners, scheduler );
436 for ( String repositoryId : repositories )
438 ManagedRepositoryContent managedRepository;
441 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
443 catch ( RepositoryNotFoundException e )
445 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
447 catch ( RepositoryException e )
449 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
454 DavResource updatedResource =
455 processRepository( request, archivaLocator, activePrincipal, managedRepository );
456 if ( resource == null )
458 resource = updatedResource;
461 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
462 if ( logicalResource.endsWith( "/" ) )
464 logicalResource = logicalResource.substring( 1 );
466 resourcesInAbsolutePath.add(
467 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
469 catch ( DavException e )
471 storedExceptions.add( e );
475 if ( resource == null )
477 if ( !storedExceptions.isEmpty() )
480 for ( DavException e : storedExceptions )
482 if ( 401 == e.getErrorCode() )
488 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
492 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
498 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
499 String activePrincipal, ManagedRepositoryContent managedRepository )
502 DavResource resource = null;
503 if ( isAuthorized( request, managedRepository.getId() ) )
505 String path = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
506 if ( path.startsWith( "/" ) )
508 path = path.substring( 1 );
510 LogicalResource logicalResource = new LogicalResource( path );
511 File resourceFile = new File( managedRepository.getRepoRoot(), path );
512 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepository.getRepository(),
513 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
514 archivaLocator, this, mimeTypes, auditListeners, scheduler );
516 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
518 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
520 // force a resource not found
521 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
525 if ( !resource.isCollection() )
527 boolean previouslyExisted = resourceFile.exists();
529 // Attempt to fetch the resource from any defined proxy.
530 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
532 // At this point the incoming request can either be in default or
533 // legacy layout format.
536 // Perform an adjustment of the resource to the managed
537 // repository expected path.
538 String localResourcePath =
539 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
540 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
542 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
543 managedRepository.getRepository(), request.getRemoteAddr(),
544 activePrincipal, request.getDavSession(), archivaLocator, this,
545 mimeTypes, auditListeners, scheduler );
547 catch ( LayoutException e )
549 if ( !resourceFile.exists() )
551 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
557 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
560 if ( log.isDebugEnabled() )
562 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
563 + managedRepository.getId() + "' (current user '" + activePrincipal
566 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
567 logicalResource.getPath(), event, activePrincipal );
570 if ( !resourceFile.exists() )
572 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
578 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
580 String resourcePath = logicalResource.getPath();
582 // check if target repo is enabled for releases
583 // we suppose that release-artifacts can be deployed only to repos enabled for releases
584 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
585 && !repositoryRequest.isSupportFile( resourcePath ) )
587 ArtifactReference artifact = null;
590 artifact = managedRepository.toArtifactReference( resourcePath );
592 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
594 // check if artifact already exists and if artifact re-deployment to the repository is allowed
595 if ( managedRepository.hasContent( artifact )
596 && managedRepository.getRepository().isBlockRedeployments() )
598 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
599 + "' is not allowed." );
600 throw new DavException( HttpServletResponse.SC_CONFLICT,
601 "Overwriting released artifacts is not allowed." );
605 catch ( LayoutException e )
607 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
612 * Create parent directories that don't exist when writing a file This actually makes this
613 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
614 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
615 * create the collections themselves.
618 File rootDirectory = new File( managedRepository.getRepoRoot() );
619 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
621 if ( !destDir.exists() )
624 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
626 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
629 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
630 AuditEvent.CREATE_DIR, activePrincipal );
637 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
640 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
642 ManagedRepositoryContent managedRepository;
645 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
647 catch ( RepositoryNotFoundException e )
649 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
650 "Invalid repository: " + archivaLocator.getRepositoryId() );
652 catch ( RepositoryException e )
654 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
657 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
658 if ( logicalResource.startsWith( "/" ) )
660 logicalResource = logicalResource.substring( 1 );
662 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
663 DavResource resource =
664 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
665 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
667 resource.addLockManager( lockManager );
671 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
672 LogicalResource resource )
675 String path = resource.getPath();
676 if ( repositoryRequest.isSupportFile( path ) )
678 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
680 return ( proxiedFile != null );
683 // Is it a Metadata resource?
684 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
686 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
689 // Not any of the above? Then it's gotta be an artifact reference.
692 // Get the artifact reference in a layout neutral way.
693 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
695 if ( artifact != null )
697 applyServerSideRelocation( managedRepository, artifact );
699 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
701 resource.setPath( managedRepository.toPath( artifact ) );
702 if ( log.isDebugEnabled() )
704 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
705 + artifact.getVersion() + "'" );
707 return ( proxiedFile != null );
710 catch ( LayoutException e )
714 catch ( ProxyDownloadException e )
716 log.error( e.getMessage(), e );
717 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
718 "Unable to fetch artifact resource." );
724 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
725 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
728 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
729 * metadatas and serving the expected artifact.
731 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
732 throws ProxyDownloadException
734 if ( "pom".equals( artifact.getType() ) )
739 // Build the artifact POM reference
740 ArtifactReference pomReference = new ArtifactReference();
741 pomReference.setGroupId( artifact.getGroupId() );
742 pomReference.setArtifactId( artifact.getArtifactId() );
743 pomReference.setVersion( artifact.getVersion() );
744 pomReference.setType( "pom" );
746 // Get the artifact POM from proxied repositories if needed
747 connectors.fetchFromProxies( managedRepository, pomReference );
749 // Open and read the POM from the managed repo
750 File pom = managedRepository.toFile( pomReference );
759 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
760 FileReader reader = new FileReader( pom );
764 model = new MavenXpp3Reader().read( reader );
768 if ( reader != null )
774 DistributionManagement dist = model.getDistributionManagement();
777 Relocation relocation = dist.getRelocation();
778 if ( relocation != null )
780 // artifact is relocated : update the repositoryPath
781 if ( relocation.getGroupId() != null )
783 artifact.setGroupId( relocation.getGroupId() );
785 if ( relocation.getArtifactId() != null )
787 artifact.setArtifactId( relocation.getArtifactId() );
789 if ( relocation.getVersion() != null )
791 artifact.setVersion( relocation.getVersion() );
796 catch ( FileNotFoundException e )
798 // Artifact has no POM in repo : ignore
800 catch ( IOException e )
802 // Unable to read POM : ignore.
804 catch ( XmlPullParserException e )
806 // Invalid POM : ignore
812 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
815 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
816 event.setRemoteIP( remoteIP );
818 for ( AuditListener listener : auditListeners )
820 listener.auditEvent( event );
824 public void addAuditListener( AuditListener listener )
826 this.auditListeners.add( listener );
829 public void clearAuditListeners()
831 this.auditListeners.clear();
834 public void removeAuditListener( AuditListener listener )
836 this.auditListeners.remove( listener );
839 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
841 // [MRM-503] - Metadata file need Pragma:no-cache response
843 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
845 response.addHeader( "Pragma", "no-cache" );
846 response.addHeader( "Cache-Control", "no-cache" );
849 // We need to specify this so connecting wagons can work correctly
850 response.addDateHeader( "last-modified", resource.getModificationTime() );
852 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
855 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
858 if ( !( locator instanceof ArchivaDavResourceLocator ) )
860 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
861 "Locator does not implement RepositoryLocator" );
865 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
867 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
870 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
872 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
873 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
875 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
877 return archivaLocator;
880 private static class LogicalResource
884 public LogicalResource( String path )
889 public String getPath()
894 public void setPath( String path )
900 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
905 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
906 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
908 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
910 WebdavMethodUtil.getMethodPermission(
911 request.getMethod() ) );
913 catch ( AuthenticationException e )
915 // safety check for MRM-911
916 String guest = UserManager.GUEST_USERNAME;
919 if ( servletAuth.isAuthorized( guest,
920 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
921 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
926 catch ( UnauthorizedException ae )
928 throw new UnauthorizedDavException( repositoryId,
929 "You are not authenticated and authorized to access any repository." );
932 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
934 catch ( MustChangePasswordException e )
936 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
938 catch ( AccountLockedException e )
940 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
942 catch ( AuthorizationException e )
944 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
945 "Fatal Authorization Subsystem Error." );
947 catch ( UnauthorizedException e )
949 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
953 private DavResource getResource( DavServletRequest request, List<String> repositories,
954 ArchivaDavResourceLocator locator, String groupId )
957 List<File> mergedRepositoryContents = new ArrayList<File>();
958 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
959 if ( path.startsWith( "/" ) )
961 path = path.substring( 1 );
963 LogicalResource logicalResource = new LogicalResource( path );
966 // if the current user logged in has permission to any of the repositories, allow user to
967 // browse the repo group but displaying only the repositories which the user has permission to access.
968 // otherwise, prompt for authentication.
970 String activePrincipal = getActivePrincipal( request );
972 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
978 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
979 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
981 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
982 mergedRepositoryContents.add( mergedRepoDir );
986 for ( String repository : repositories )
988 ManagedRepositoryContent managedRepository = null;
992 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
994 catch ( RepositoryNotFoundException e )
996 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
997 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
999 catch ( RepositoryException e )
1001 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1002 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1005 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1006 if ( resourceFile.exists() )
1008 // in case of group displaying index directory doesn't have sense !!
1009 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1010 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1012 if ( !new File( repoIndexDirectory ).isAbsolute() )
1014 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1015 StringUtils.isEmpty( repoIndexDirectory )
1017 : repoIndexDirectory ).getAbsolutePath();
1020 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1022 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1023 ".indexer" ).getAbsolutePath();
1026 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1027 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1029 // for prompted authentication
1030 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1034 if ( isAuthorized( request, repository ) )
1036 mergedRepositoryContents.add( resourceFile );
1037 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1040 catch ( DavException e )
1042 // TODO: review exception handling
1043 if ( log.isDebugEnabled() )
1045 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1046 + activePrincipal + "': " + e.getMessage() );
1053 // for the current user logged in
1056 if ( servletAuth.isAuthorized( activePrincipal, repository,
1057 WebdavMethodUtil.getMethodPermission(
1058 request.getMethod() ) ) )
1060 mergedRepositoryContents.add( resourceFile );
1061 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1064 catch ( UnauthorizedException e )
1066 // TODO: review exception handling
1067 if ( log.isDebugEnabled() )
1069 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1070 + activePrincipal + "': " + e.getMessage() );
1081 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1084 ArchivaVirtualDavResource resource =
1085 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1088 // compatibility with MRM-440 to ensure browsing the repository group works ok
1089 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1091 throw new BrowserRedirectException( resource.getHref() );
1097 protected String getActivePrincipal( DavServletRequest request )
1099 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1100 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1104 * Check if the current user is authorized to access any of the repos
1107 * @param repositories
1108 * @param activePrincipal
1111 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1113 boolean allow = false;
1115 // if securitySession != null, it means that the user was prompted for authentication
1116 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1118 for ( String repository : repositories )
1122 if ( isAuthorized( request, repository ) )
1128 catch ( DavException e )
1136 for ( String repository : repositories )
1140 if ( servletAuth.isAuthorized( activePrincipal, repository,
1141 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1147 catch ( UnauthorizedException e )
1157 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1158 throws RepositoryMetadataException, DigesterException, IOException
1160 File outputFile = new File( outputFilename );
1161 if ( outputFile.exists() )
1163 FileUtils.deleteQuietly( outputFile );
1166 outputFile.getParentFile().mkdirs();
1167 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1169 createChecksumFile( outputFilename, digestSha1 );
1170 createChecksumFile( outputFilename, digestMd5 );
1175 private void createChecksumFile( String path, Digester digester )
1176 throws DigesterException, IOException
1178 File checksumFile = new File( path + digester.getFilenameExtension() );
1179 if ( !checksumFile.exists() )
1181 FileUtils.deleteQuietly( checksumFile );
1182 checksum.createChecksum( new File( path ), digester );
1184 else if ( !checksumFile.isFile() )
1186 log.error( "Checksum file is not a file." );
1190 private boolean isProjectReference( String requestedResource )
1194 metadataTools.toVersionedReference( requestedResource );
1197 catch ( RepositoryMetadataException re )
1203 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1204 DavServletRequest request, String groupId )
1210 HttpSession session = request.getSession();
1212 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1213 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1214 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1215 if ( temporaryGroupIndexMap == null )
1217 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1220 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1222 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1224 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getDefaultGroupIndexTtl() * 60
1227 log.debug( "tmp group index is too old so delete it" );
1228 indexMerger.cleanTemporaryGroupIndex( tmp );
1232 return tmp.getDirectory();
1236 Set<String> authzRepos = new HashSet<String>();
1237 for ( String repository : repositories )
1241 if ( servletAuth.isAuthorized( activePrincipal, repository,
1242 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1244 authzRepos.add( repository );
1245 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1248 catch ( UnauthorizedException e )
1250 // TODO: review exception handling
1251 if ( log.isDebugEnabled() )
1253 log.debug( "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1258 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1259 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1260 TemporaryGroupIndex temporaryGroupIndex =
1261 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1262 new Date().getTime() );
1263 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1264 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1265 temporaryGroupIndexMap );
1266 return mergedRepoDir;
1268 catch ( RepositoryAdminException e )
1270 throw new DavException( 500, e );
1272 catch ( IndexMergerException e )
1274 throw new DavException( 500, e );
1279 public void setServletAuth( ServletAuthenticator servletAuth )
1281 this.servletAuth = servletAuth;
1284 public void setHttpAuth( HttpAuthenticator httpAuth )
1286 this.httpAuth = httpAuth;
1289 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1291 this.scheduler = scheduler;
1294 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1296 this.archivaConfiguration = archivaConfiguration;
1299 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1301 this.repositoryFactory = repositoryFactory;
1304 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1306 this.repositoryRequest = repositoryRequest;
1309 public void setConnectors( RepositoryProxyConnectors connectors )
1311 this.connectors = connectors;