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.apache.archiva.redback.authorization.AuthorizationException;
82 import org.apache.archiva.redback.authorization.UnauthorizedException;
83 import org.apache.archiva.redback.policy.AccountLockedException;
84 import org.apache.archiva.redback.policy.MustChangePasswordException;
85 import org.apache.archiva.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.apache.archiva.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 static final MavenXpp3Reader mavenXpp3Reader = 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 if ( log.isDebugEnabled() )
564 log.debug( "Proxied artifact '" + resourceFile.getName() + "' in repository '"
565 + managedRepository.getId() + "' (current user '" + activePrincipal
568 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
569 logicalResource.getPath(), event, activePrincipal );
572 if ( !resourceFile.exists() )
574 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
580 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
582 String resourcePath = logicalResource.getPath();
584 // check if target repo is enabled for releases
585 // we suppose that release-artifacts can be deployed only to repos enabled for releases
586 if ( managedRepository.getRepository().isReleases() && !repositoryRequest.isMetadata( resourcePath )
587 && !repositoryRequest.isSupportFile( resourcePath ) )
589 ArtifactReference artifact = null;
592 artifact = managedRepository.toArtifactReference( resourcePath );
594 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
596 // check if artifact already exists and if artifact re-deployment to the repository is allowed
597 if ( managedRepository.hasContent( artifact )
598 && managedRepository.getRepository().isBlockRedeployments() )
600 log.warn( "Overwriting released artifacts in repository '" + managedRepository.getId()
601 + "' is not allowed." );
602 throw new DavException( HttpServletResponse.SC_CONFLICT,
603 "Overwriting released artifacts is not allowed." );
607 catch ( LayoutException e )
609 log.warn( "Artifact path '" + resourcePath + "' is invalid." );
614 * Create parent directories that don't exist when writing a file This actually makes this
615 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
616 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
617 * create the collections themselves.
620 File rootDirectory = new File( managedRepository.getRepoRoot() );
621 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
623 if ( !destDir.exists() )
626 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
628 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
631 triggerAuditEvent( request.getRemoteAddr(), managedRepository.getId(), relPath,
632 AuditEvent.CREATE_DIR, activePrincipal );
639 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
642 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
644 ManagedRepositoryContent managedRepository;
647 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
649 catch ( RepositoryNotFoundException e )
651 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
652 "Invalid repository: " + archivaLocator.getRepositoryId() );
654 catch ( RepositoryException e )
656 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
659 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
660 if ( logicalResource.startsWith( "/" ) )
662 logicalResource = logicalResource.substring( 1 );
664 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
665 DavResource resource =
666 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
667 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
669 resource.addLockManager( lockManager );
673 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
674 LogicalResource resource )
677 String path = resource.getPath();
678 if ( repositoryRequest.isSupportFile( path ) )
680 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
682 return ( proxiedFile != null );
685 // Is it a Metadata resource?
686 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
688 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
691 // Not any of the above? Then it's gotta be an artifact reference.
694 // Get the artifact reference in a layout neutral way.
695 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
697 if ( artifact != null )
699 applyServerSideRelocation( managedRepository, artifact );
701 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
703 resource.setPath( managedRepository.toPath( artifact ) );
704 if ( log.isDebugEnabled() )
706 log.debug( "Proxied artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
707 + artifact.getVersion() + "'" );
709 return ( proxiedFile != null );
712 catch ( LayoutException e )
716 catch ( ProxyDownloadException e )
718 log.error( e.getMessage(), e );
719 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
720 "Unable to fetch artifact resource." );
726 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
727 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
730 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
731 * metadatas and serving the expected artifact.
733 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
734 throws ProxyDownloadException
736 if ( "pom".equals( artifact.getType() ) )
741 // Build the artifact POM reference
742 ArtifactReference pomReference = new ArtifactReference();
743 pomReference.setGroupId( artifact.getGroupId() );
744 pomReference.setArtifactId( artifact.getArtifactId() );
745 pomReference.setVersion( artifact.getVersion() );
746 pomReference.setType( "pom" );
748 // Get the artifact POM from proxied repositories if needed
749 connectors.fetchFromProxies( managedRepository, pomReference );
751 // Open and read the POM from the managed repo
752 File pom = managedRepository.toFile( pomReference );
761 // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
762 FileReader reader = new FileReader( pom );
766 model = mavenXpp3Reader.read(reader);
770 if ( reader != null )
776 DistributionManagement dist = model.getDistributionManagement();
779 Relocation relocation = dist.getRelocation();
780 if ( relocation != null )
782 // artifact is relocated : update the repositoryPath
783 if ( relocation.getGroupId() != null )
785 artifact.setGroupId( relocation.getGroupId() );
787 if ( relocation.getArtifactId() != null )
789 artifact.setArtifactId( relocation.getArtifactId() );
791 if ( relocation.getVersion() != null )
793 artifact.setVersion( relocation.getVersion() );
798 catch ( FileNotFoundException e )
800 // Artifact has no POM in repo : ignore
802 catch ( IOException e )
804 // Unable to read POM : ignore.
806 catch ( XmlPullParserException e )
808 // Invalid POM : ignore
814 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
817 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
818 event.setRemoteIP( remoteIP );
820 for ( AuditListener listener : auditListeners )
822 listener.auditEvent( event );
826 public void addAuditListener( AuditListener listener )
828 this.auditListeners.add( listener );
831 public void clearAuditListeners()
833 this.auditListeners.clear();
836 public void removeAuditListener( AuditListener listener )
838 this.auditListeners.remove( listener );
841 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
843 // [MRM-503] - Metadata file need Pragma:no-cache response
845 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
847 response.addHeader( "Pragma", "no-cache" );
848 response.addHeader( "Cache-Control", "no-cache" );
851 // We need to specify this so connecting wagons can work correctly
852 response.addDateHeader( "last-modified", resource.getModificationTime() );
854 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
857 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
860 if ( !( locator instanceof ArchivaDavResourceLocator ) )
862 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
863 "Locator does not implement RepositoryLocator" );
867 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
869 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
872 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
874 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
875 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
877 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
879 return archivaLocator;
882 private static class LogicalResource
886 public LogicalResource( String path )
891 public String getPath()
896 public void setPath( String path )
902 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
907 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
908 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
910 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
912 WebdavMethodUtil.getMethodPermission(
913 request.getMethod() ) );
915 catch ( AuthenticationException e )
917 // safety check for MRM-911
918 String guest = UserManager.GUEST_USERNAME;
921 if ( servletAuth.isAuthorized( guest,
922 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
923 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
928 catch ( UnauthorizedException ae )
930 throw new UnauthorizedDavException( repositoryId,
931 "You are not authenticated and authorized to access any repository." );
934 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
936 catch ( MustChangePasswordException e )
938 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
940 catch ( AccountLockedException e )
942 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
944 catch ( AuthorizationException e )
946 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
947 "Fatal Authorization Subsystem Error." );
949 catch ( UnauthorizedException e )
951 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
955 private DavResource getResource( DavServletRequest request, List<String> repositories,
956 ArchivaDavResourceLocator locator, String groupId )
959 List<File> mergedRepositoryContents = new ArrayList<File>();
960 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
961 if ( path.startsWith( "/" ) )
963 path = path.substring( 1 );
965 LogicalResource logicalResource = new LogicalResource( path );
968 // if the current user logged in has permission to any of the repositories, allow user to
969 // browse the repo group but displaying only the repositories which the user has permission to access.
970 // otherwise, prompt for authentication.
972 String activePrincipal = getActivePrincipal( request );
974 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
980 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
981 if ( StringUtils.endsWith( pathInfo, "/.indexer" ) )
983 File mergedRepoDir = buildMergedIndexDirectory( repositories, activePrincipal, request, groupId );
984 mergedRepositoryContents.add( mergedRepoDir );
988 for ( String repository : repositories )
990 ManagedRepositoryContent managedRepository = null;
994 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
996 catch ( RepositoryNotFoundException e )
998 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
999 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1001 catch ( RepositoryException e )
1003 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1004 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1007 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1008 if ( resourceFile.exists() )
1010 // in case of group displaying index directory doesn't have sense !!
1011 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1012 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1014 if ( !new File( repoIndexDirectory ).isAbsolute() )
1016 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1017 StringUtils.isEmpty( repoIndexDirectory )
1019 : repoIndexDirectory ).getAbsolutePath();
1022 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1024 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1025 ".indexer" ).getAbsolutePath();
1028 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1029 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1031 // for prompted authentication
1032 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1036 if ( isAuthorized( request, repository ) )
1038 mergedRepositoryContents.add( resourceFile );
1039 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1042 catch ( DavException e )
1044 // TODO: review exception handling
1045 if ( log.isDebugEnabled() )
1047 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1048 + activePrincipal + "': " + e.getMessage() );
1055 // for the current user logged in
1058 if ( servletAuth.isAuthorized( activePrincipal, repository,
1059 WebdavMethodUtil.getMethodPermission(
1060 request.getMethod() ) ) )
1062 mergedRepositoryContents.add( resourceFile );
1063 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1066 catch ( UnauthorizedException e )
1068 // TODO: review exception handling
1069 if ( log.isDebugEnabled() )
1071 log.debug( "Skipping repository '" + managedRepository + "' for user '"
1072 + activePrincipal + "': " + e.getMessage() );
1083 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1086 ArchivaVirtualDavResource resource =
1087 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1090 // compatibility with MRM-440 to ensure browsing the repository group works ok
1091 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1093 throw new BrowserRedirectException( resource.getHref() );
1099 protected String getActivePrincipal( DavServletRequest request )
1101 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1102 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1106 * Check if the current user is authorized to access any of the repos
1109 * @param repositories
1110 * @param activePrincipal
1113 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1115 boolean allow = false;
1117 // if securitySession != null, it means that the user was prompted for authentication
1118 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1120 for ( String repository : repositories )
1124 if ( isAuthorized( request, repository ) )
1130 catch ( DavException e )
1138 for ( String repository : repositories )
1142 if ( servletAuth.isAuthorized( activePrincipal, repository,
1143 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1149 catch ( UnauthorizedException e )
1159 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1160 throws RepositoryMetadataException, DigesterException, IOException
1162 File outputFile = new File( outputFilename );
1163 if ( outputFile.exists() )
1165 FileUtils.deleteQuietly( outputFile );
1168 outputFile.getParentFile().mkdirs();
1169 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1171 createChecksumFile( outputFilename, digestSha1 );
1172 createChecksumFile( outputFilename, digestMd5 );
1177 private void createChecksumFile( String path, Digester digester )
1178 throws DigesterException, IOException
1180 File checksumFile = new File( path + digester.getFilenameExtension() );
1181 if ( !checksumFile.exists() )
1183 FileUtils.deleteQuietly( checksumFile );
1184 checksum.createChecksum( new File( path ), digester );
1186 else if ( !checksumFile.isFile() )
1188 log.error( "Checksum file is not a file." );
1192 private boolean isProjectReference( String requestedResource )
1196 metadataTools.toVersionedReference( requestedResource );
1199 catch ( RepositoryMetadataException re )
1205 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1206 DavServletRequest request, String groupId )
1212 HttpSession session = request.getSession();
1214 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1215 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1216 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1217 if ( temporaryGroupIndexMap == null )
1219 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1222 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( groupId );
1224 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1226 if ( System.currentTimeMillis() - tmp.getCreationTime() > ( indexMerger.getDefaultGroupIndexTtl() * 60
1229 log.debug( "tmp group index is too old so delete it" );
1230 indexMerger.cleanTemporaryGroupIndex( tmp );
1234 return tmp.getDirectory();
1238 Set<String> authzRepos = new HashSet<String>();
1239 for ( String repository : repositories )
1243 if ( servletAuth.isAuthorized( activePrincipal, repository,
1244 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1246 authzRepos.add( repository );
1247 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1250 catch ( UnauthorizedException e )
1252 // TODO: review exception handling
1253 if ( log.isDebugEnabled() )
1255 log.debug( "Skipping repository '" + repository + "' for user '" + activePrincipal + "': "
1260 IndexingContext indexingContext = indexMerger.buildMergedIndex( authzRepos, true );
1261 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1262 TemporaryGroupIndex temporaryGroupIndex =
1263 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId() ).setCreationTime(
1264 new Date().getTime() );
1265 temporaryGroupIndexMap.put( groupId, temporaryGroupIndex );
1266 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1267 temporaryGroupIndexMap );
1268 return mergedRepoDir;
1270 catch ( RepositoryAdminException e )
1272 throw new DavException( 500, e );
1274 catch ( IndexMergerException e )
1276 throw new DavException( 500, e );
1281 public void setServletAuth( ServletAuthenticator servletAuth )
1283 this.servletAuth = servletAuth;
1286 public void setHttpAuth( HttpAuthenticator httpAuth )
1288 this.httpAuth = httpAuth;
1291 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1293 this.scheduler = scheduler;
1296 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1298 this.archivaConfiguration = archivaConfiguration;
1301 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1303 this.repositoryFactory = repositoryFactory;
1306 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1308 this.repositoryRequest = repositoryRequest;
1311 public void setConnectors( RepositoryProxyConnectors connectors )
1313 this.connectors = connectors;