1 package org.apache.archiva.webdav;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.admin.model.RepositoryAdminException;
23 import org.apache.archiva.admin.model.beans.ManagedRepository;
24 import org.apache.archiva.admin.model.beans.RemoteRepository;
25 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
26 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
27 import org.apache.archiva.audit.Auditable;
28 import org.apache.archiva.common.filelock.FileLockManager;
29 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
31 import org.apache.archiva.common.utils.PathUtil;
32 import org.apache.archiva.common.utils.VersionUtil;
33 import org.apache.archiva.configuration.ArchivaConfiguration;
34 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
35 import org.apache.archiva.indexer.merger.IndexMerger;
36 import org.apache.archiva.indexer.merger.IndexMergerException;
37 import org.apache.archiva.indexer.merger.IndexMergerRequest;
38 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
39 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
40 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
41 import org.apache.archiva.indexer.search.RepositorySearch;
42 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
43 import org.apache.archiva.metadata.model.facets.AuditEvent;
44 import org.apache.archiva.metadata.repository.storage.RelocationException;
45 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
46 import org.apache.archiva.model.ArchivaRepositoryMetadata;
47 import org.apache.archiva.model.ArtifactReference;
48 import org.apache.archiva.policies.ProxyDownloadException;
49 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
50 import org.apache.archiva.redback.authentication.AuthenticationException;
51 import org.apache.archiva.redback.authentication.AuthenticationResult;
52 import org.apache.archiva.redback.authorization.AuthorizationException;
53 import org.apache.archiva.redback.authorization.UnauthorizedException;
54 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
55 import org.apache.archiva.redback.policy.AccountLockedException;
56 import org.apache.archiva.redback.policy.MustChangePasswordException;
57 import org.apache.archiva.redback.system.SecuritySession;
58 import org.apache.archiva.redback.users.User;
59 import org.apache.archiva.redback.users.UserManager;
60 import org.apache.archiva.repository.ManagedRepositoryContent;
61 import org.apache.archiva.repository.RepositoryContentFactory;
62 import org.apache.archiva.repository.RepositoryException;
63 import org.apache.archiva.repository.RepositoryNotFoundException;
64 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
65 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
66 import org.apache.archiva.repository.events.AuditListener;
67 import org.apache.archiva.repository.layout.LayoutException;
68 import org.apache.archiva.repository.metadata.MetadataTools;
69 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
71 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
72 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
73 import org.apache.archiva.security.ServletAuthenticator;
74 import org.apache.archiva.webdav.util.MimeTypes;
75 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
76 import org.apache.archiva.webdav.util.WebdavMethodUtil;
77 import org.apache.archiva.xml.XMLException;
78 import org.apache.commons.io.FileUtils;
79 import org.apache.commons.io.FilenameUtils;
80 import org.apache.commons.lang.StringUtils;
81 import org.apache.commons.lang.SystemUtils;
82 import org.apache.jackrabbit.webdav.DavException;
83 import org.apache.jackrabbit.webdav.DavResource;
84 import org.apache.jackrabbit.webdav.DavResourceFactory;
85 import org.apache.jackrabbit.webdav.DavResourceLocator;
86 import org.apache.jackrabbit.webdav.DavServletRequest;
87 import org.apache.jackrabbit.webdav.DavServletResponse;
88 import org.apache.jackrabbit.webdav.DavSession;
89 import org.apache.jackrabbit.webdav.lock.LockManager;
90 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
91 import org.apache.maven.index.context.IndexingContext;
92 import org.codehaus.plexus.digest.ChecksumFile;
93 import org.codehaus.plexus.digest.Digester;
94 import org.codehaus.plexus.digest.DigesterException;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97 import org.slf4j.MarkerFactory;
98 import org.springframework.context.ApplicationContext;
99 import org.springframework.stereotype.Service;
101 import javax.annotation.PostConstruct;
102 import javax.inject.Inject;
103 import javax.inject.Named;
104 import javax.servlet.http.HttpServletResponse;
105 import javax.servlet.http.HttpSession;
107 import java.io.IOException;
108 import java.nio.file.Files;
109 import java.util.ArrayList;
110 import java.util.Date;
111 import java.util.HashMap;
112 import java.util.HashSet;
113 import java.util.List;
114 import java.util.Map;
115 import java.util.Set;
120 @Service( "davResourceFactory#archiva" )
121 public class ArchivaDavResourceFactory
122 implements DavResourceFactory, Auditable
124 private static final String PROXIED_SUFFIX = " (proxied)";
126 private static final String HTTP_PUT_METHOD = "PUT";
128 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
131 private List<AuditListener> auditListeners = new ArrayList<>();
134 private RepositoryContentFactory repositoryFactory;
136 private RepositoryRequest repositoryRequest;
139 @Named( value = "repositoryProxyConnectors#default" )
140 private RepositoryProxyConnectors connectors;
143 private MetadataTools metadataTools;
146 private MimeTypes mimeTypes;
148 private ArchivaConfiguration archivaConfiguration;
151 private ServletAuthenticator servletAuth;
154 @Named( value = "httpAuthenticator#basic" )
155 private HttpAuthenticator httpAuth;
158 private RemoteRepositoryAdmin remoteRepositoryAdmin;
161 private ManagedRepositoryAdmin managedRepositoryAdmin;
164 private IndexMerger indexMerger;
167 private RepositorySearch repositorySearch;
170 * Lock Manager - use simple implementation from JackRabbit
172 private final LockManager lockManager = new SimpleLockManager();
174 private ChecksumFile checksum;
176 private Digester digestSha1;
178 private Digester digestMd5;
181 @Named( value = "archivaTaskScheduler#repository" )
182 private RepositoryArchivaTaskScheduler scheduler;
185 @Named( value = "fileLockManager#default" )
186 private FileLockManager fileLockManager;
188 private ApplicationContext applicationContext;
191 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
192 ArchivaConfiguration archivaConfiguration )
193 throws PlexusSisuBridgeException
195 this.archivaConfiguration = archivaConfiguration;
196 this.applicationContext = applicationContext;
197 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
199 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
200 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
202 // TODO remove this hard dependency on maven !!
203 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
207 public void initialize()
213 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
214 final DavServletResponse response )
217 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
219 RepositoryGroupConfiguration repoGroupConfig =
220 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
222 String activePrincipal = getActivePrincipal( request );
224 List<String> resourcesInAbsolutePath = new ArrayList<>();
226 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
227 DavResource resource;
228 if ( repoGroupConfig != null )
232 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
233 "Write method not allowed for repository groups." );
236 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
238 // handle browse requests for virtual repos
239 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
243 DavResource davResource =
244 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
247 setHeaders( response, locator, davResource, true );
252 catch ( RepositoryAdminException e )
254 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
259 // make a copy to avoid potential concurrent modifications (eg. by configuration)
260 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
262 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
263 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
264 resourcesInAbsolutePath, repoGroupConfig );
272 RemoteRepository remoteRepository =
273 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
275 if ( remoteRepository != null )
277 String logicalResource = getLogicalResource( archivaLocator, null, false );
278 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
279 File resourceFile = StringUtils.equals( logicalResource, "/" )
280 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
281 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
282 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), //
283 locator.getResourcePath(), //
285 request.getRemoteAddr(), //
287 request.getDavSession(), //
294 setHeaders( response, locator, resource, false );
298 catch ( RepositoryAdminException e )
300 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
301 archivaLocator.getRepositoryId(), e.getMessage() );
304 ManagedRepositoryContent managedRepositoryContent = null;
308 managedRepositoryContent =
309 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
311 catch ( RepositoryNotFoundException e )
313 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
314 "Invalid repository: " + archivaLocator.getRepositoryId() );
316 catch ( RepositoryException e )
318 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
321 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
325 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
326 managedRepositoryAdmin.getManagedRepository(
327 archivaLocator.getRepositoryId() ) );
329 String logicalResource = getLogicalResource( archivaLocator, null, false );
330 resourcesInAbsolutePath.add(
331 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
334 catch ( RepositoryAdminException e )
336 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
340 String requestedResource = request.getRequestURI();
342 // MRM-872 : merge all available metadata
343 // merge metadata only when requested via the repo group
344 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
345 requestedResource ) ) && repoGroupConfig != null )
347 // this should only be at the project level not version level!
348 if ( isProjectReference( requestedResource ) )
351 ArchivaDavResource res = (ArchivaDavResource) resource;
353 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
355 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
357 // for MRM-872 handle checksums of the merged metadata files
358 if ( repositoryRequest.isSupportFile( requestedResource ) )
360 File metadataChecksum =
361 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
363 if ( metadataChecksum.exists() )
365 LogicalResource logicalResource =
366 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
369 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
370 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
371 archivaLocator, this, mimeTypes, auditListeners, scheduler,
377 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
379 // merge the metadata of all repos under group
380 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
381 for ( String resourceAbsPath : resourcesInAbsolutePath )
385 File metadataFile = new File( resourceAbsPath );
386 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
387 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
389 catch ( XMLException e )
391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
392 "Error occurred while reading metadata file." );
394 catch ( RepositoryMetadataException r )
396 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
397 "Error occurred while merging metadata file." );
403 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
405 LogicalResource logicalResource =
406 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
409 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
410 request.getRemoteAddr(), activePrincipal,
411 request.getDavSession(), archivaLocator, this, mimeTypes,
412 auditListeners, scheduler, fileLockManager );
414 catch ( RepositoryMetadataException r )
416 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
417 "Error occurred while writing metadata file." );
419 catch ( IOException ie )
421 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
422 "Error occurred while generating checksum files." );
424 catch ( DigesterException de )
426 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
427 "Error occurred while generating checksum files."
435 setHeaders( response, locator, resource, false );
437 // compatibility with MRM-440 to ensure browsing the repository works ok
438 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
440 throw new BrowserRedirectException( resource.getHref() );
442 resource.addLockManager( lockManager );
446 private DavResource processRepositoryGroup( final DavServletRequest request,
447 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
448 String activePrincipal, List<String> resourcesInAbsolutePath,
449 RepositoryGroupConfiguration repoGroupConfig )
452 DavResource resource = null;
453 List<DavException> storedExceptions = new ArrayList<>();
455 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
457 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
459 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
461 // we are in the case of index file request
462 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
463 File temporaryIndexDirectory =
464 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
466 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
467 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
468 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
469 archivaLocator, this, mimeTypes, auditListeners, scheduler,
475 for ( String repositoryId : repositories )
477 ManagedRepositoryContent managedRepositoryContent;
480 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
482 catch ( RepositoryNotFoundException e )
484 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
486 catch ( RepositoryException e )
488 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
493 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
494 DavResource updatedResource =
495 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
497 if ( resource == null )
499 resource = updatedResource;
502 String logicalResource = getLogicalResource( archivaLocator, null, false );
503 if ( logicalResource.endsWith( "/" ) )
505 logicalResource = logicalResource.substring( 1 );
507 resourcesInAbsolutePath.add(
508 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
510 catch ( DavException e )
512 storedExceptions.add( e );
514 catch ( RepositoryAdminException e )
516 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
520 if ( resource == null )
522 if ( !storedExceptions.isEmpty() )
525 for ( DavException e : storedExceptions )
527 if ( 401 == e.getErrorCode() )
533 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
537 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
543 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
544 boolean useOrigResourcePath )
546 // FIXME remove this hack
547 // but currently managedRepository can be null in case of group
548 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
549 RepositoryStorage repositoryStorage =
550 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
551 String path = repositoryStorage.getFilePath(
552 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
554 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
555 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
560 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, //
561 ManagedRepositoryContent managedRepositoryContent, //
565 String layout = managedRepositoryContent.getRepository() == null
566 ? new ManagedRepository().getLayout()
567 : managedRepositoryContent.getRepository().getLayout();
568 RepositoryStorage repositoryStorage =
569 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
572 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), //
573 managedRepositoryContent );
575 catch ( RelocationException e )
577 String path = e.getPath();
578 log.debug( "Relocation to {}", path );
580 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
581 e.getRelocationType() );
583 catch ( XMLException e )
585 log.error( e.getMessage(), e );
586 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
590 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
591 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
592 ManagedRepository managedRepository )
595 DavResource resource = null;
596 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
598 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
599 // Maven Centric part ask evaluation if -SNAPSHOT
600 // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
602 String path = readMethod
603 ? evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
604 : getLogicalResource( archivaLocator, managedRepository, false );
605 if ( path.startsWith( "/" ) )
607 path = path.substring( 1 );
609 LogicalResource logicalResource = new LogicalResource( path );
610 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
612 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
613 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
614 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
616 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
618 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
620 // force a resource not found
621 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
625 if ( !resource.isCollection() )
627 boolean previouslyExisted = resourceFile.exists();
629 // Attempt to fetch the resource from any defined proxy.
631 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
633 // At this point the incoming request can either be in default or
634 // legacy layout format.
637 // Perform an adjustment of the resource to the managed
638 // repository expected path.
639 String localResourcePath =
640 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
641 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
643 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
644 managedRepositoryContent.getRepository(),
645 request.getRemoteAddr(), activePrincipal,
646 request.getDavSession(), archivaLocator, this, mimeTypes,
647 auditListeners, scheduler, fileLockManager );
649 catch ( LayoutException e )
651 if ( !resourceFile.exists() )
653 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
659 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
662 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
663 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
665 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
666 logicalResource.getPath(), event, activePrincipal );
669 if ( !resourceFile.exists() )
671 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
677 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
679 String resourcePath = logicalResource.getPath();
681 // check if target repo is enabled for releases
682 // we suppose that release-artifacts can be deployed only to repos enabled for releases
683 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
684 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
686 ArtifactReference artifact = null;
689 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
691 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
693 // check if artifact already exists and if artifact re-deployment to the repository is allowed
694 if ( managedRepositoryContent.hasContent( artifact )
695 && managedRepositoryContent.getRepository().isBlockRedeployments() )
697 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
698 managedRepositoryContent.getId() );
699 throw new DavException( HttpServletResponse.SC_CONFLICT,
700 "Overwriting released artifacts is not allowed." );
704 catch ( LayoutException e )
706 log.warn( "Artifact path '{}' is invalid.", resourcePath );
711 * Create parent directories that don't exist when writing a file This actually makes this
712 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
713 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
714 * create the collections themselves.
717 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
718 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
720 if ( !destDir.exists() )
723 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
725 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
728 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
729 AuditEvent.CREATE_DIR, activePrincipal );
737 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
740 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
742 ManagedRepositoryContent managedRepositoryContent;
745 managedRepositoryContent =
746 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
748 catch ( RepositoryNotFoundException e )
750 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
751 "Invalid repository: " + archivaLocator.getRepositoryId() );
753 catch ( RepositoryException e )
755 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
758 DavResource resource = null;
761 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
762 archivaLocator.getRepositoryId() ), false );
763 if ( logicalResource.startsWith( "/" ) )
765 logicalResource = logicalResource.substring( 1 );
767 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
768 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
769 managedRepositoryContent.getRepository(), davSession, archivaLocator,
770 this, mimeTypes, auditListeners, scheduler, fileLockManager );
772 resource.addLockManager( lockManager );
774 catch ( RepositoryAdminException e )
776 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
781 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
782 LogicalResource resource )
785 String path = resource.getPath();
786 if ( repositoryRequest.isSupportFile( path ) )
788 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
790 return ( proxiedFile != null );
793 // Is it a Metadata resource?
794 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
796 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
799 // Is it an Archetype Catalog?
800 if ( repositoryRequest.isArchetypeCatalog( path ) )
802 // FIXME we must implement a merge of remote archetype catalog from remote servers.
803 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
805 return ( proxiedFile != null );
808 // Not any of the above? Then it's gotta be an artifact reference.
811 // Get the artifact reference in a layout neutral way.
812 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
814 if ( artifact != null )
816 String repositoryLayout = managedRepository.getRepository().getLayout();
818 RepositoryStorage repositoryStorage =
819 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
820 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
822 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
824 resource.setPath( managedRepository.toPath( artifact ) );
826 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
827 artifact.getVersion() );
829 return ( proxiedFile != null );
832 catch ( LayoutException e )
836 catch ( ProxyDownloadException e )
838 log.error( e.getMessage(), e );
839 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
840 "Unable to fetch artifact resource." );
847 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
850 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
851 event.setRemoteIP( remoteIP );
853 for ( AuditListener listener : auditListeners )
855 listener.auditEvent( event );
860 public void addAuditListener( AuditListener listener )
862 this.auditListeners.add( listener );
866 public void clearAuditListeners()
868 this.auditListeners.clear();
872 public void removeAuditListener( AuditListener listener )
874 this.auditListeners.remove( listener );
877 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource,
880 // [MRM-503] - Metadata file need Pragma:no-cache response
882 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
883 && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
885 response.setHeader( "Pragma", "no-cache" );
886 response.setHeader( "Cache-Control", "no-cache" );
887 response.setDateHeader( "Last-Modified", new Date().getTime() );
889 // if the resource is a directory don't cache it as new groupId deployed will be available
890 // without need of refreshing browser
891 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
892 resource instanceof ArchivaVirtualDavResource && ( new File(
893 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
895 response.setHeader( "Pragma", "no-cache" );
896 response.setHeader( "Cache-Control", "no-cache" );
897 response.setDateHeader( "Last-Modified", new Date().getTime() );
901 if ( resource instanceof ArchivaVirtualDavResource )
903 //MRM-1854 here we have a directory so force "Last-Modified"
904 response.setDateHeader( "Last-Modified", new Date().getTime() );
909 // We need to specify this so connecting wagons can work correctly
910 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
912 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
915 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
918 if ( !( locator instanceof ArchivaDavResourceLocator ) )
920 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
921 "Locator does not implement RepositoryLocator" );
925 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
927 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
930 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
932 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
933 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
935 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
937 return archivaLocator;
940 private static class LogicalResource
944 public LogicalResource( String path )
949 public String getPath()
954 public void setPath( String path )
960 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
965 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
966 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
968 return servletAuth.isAuthenticated( request, result ) //
969 && servletAuth.isAuthorized( request, securitySession, repositoryId, //
970 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
972 catch ( AuthenticationException e )
974 // safety check for MRM-911
975 String guest = UserManager.GUEST_USERNAME;
978 if ( servletAuth.isAuthorized( guest,
979 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
980 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
985 catch ( UnauthorizedException ae )
987 throw new UnauthorizedDavException( repositoryId,
988 "You are not authenticated and authorized to access any repository." );
991 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
993 catch ( MustChangePasswordException e )
995 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
997 catch ( AccountLockedException e )
999 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
1001 catch ( AuthorizationException e )
1003 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1004 "Fatal Authorization Subsystem Error." );
1006 catch ( UnauthorizedException e )
1008 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
1012 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
1013 ArchivaDavResourceLocator locator,
1014 RepositoryGroupConfiguration repositoryGroupConfiguration )
1015 throws DavException, RepositoryAdminException
1017 if ( repositoryGroupConfiguration.getRepositories() == null
1018 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1021 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1023 return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1024 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1027 List<File> mergedRepositoryContents = new ArrayList<>();
1028 // multiple repo types so we guess they are all the same type
1029 // so use the first one
1030 // FIXME add a method with group in the repository storage
1031 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1033 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1034 if ( path.startsWith( "/" ) )
1036 path = path.substring( 1 );
1038 LogicalResource logicalResource = new LogicalResource( path );
1041 // if the current user logged in has permission to any of the repositories, allow user to
1042 // browse the repo group but displaying only the repositories which the user has permission to access.
1043 // otherwise, prompt for authentication.
1045 String activePrincipal = getActivePrincipal( request );
1047 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1050 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1055 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1057 File mergedRepoDir =
1058 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1059 mergedRepositoryContents.add( mergedRepoDir );
1063 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1065 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1066 repositoryGroupConfiguration.getId() + "/"
1067 + repositoryGroupConfiguration.getMergedIndexPath() );
1068 if ( !tmpDirectory.exists() )
1070 synchronized ( tmpDirectory.getAbsolutePath() )
1072 if ( !tmpDirectory.exists() )
1074 tmpDirectory.mkdirs();
1078 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1080 for ( String repository : repositories )
1082 ManagedRepositoryContent managedRepository = null;
1086 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1088 catch ( RepositoryNotFoundException e )
1090 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1091 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1093 catch ( RepositoryException e )
1095 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1096 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1099 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1100 if ( resourceFile.exists() )
1102 // in case of group displaying index directory doesn't have sense !!
1103 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1104 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1106 if ( !new File( repoIndexDirectory ).isAbsolute() )
1108 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1109 StringUtils.isEmpty( repoIndexDirectory )
1111 : repoIndexDirectory ).getAbsolutePath();
1114 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1116 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1117 ".indexer" ).getAbsolutePath();
1120 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1121 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1123 // for prompted authentication
1124 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1128 if ( isAuthorized( request, repository ) )
1130 mergedRepositoryContents.add( resourceFile );
1131 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1134 catch ( DavException e )
1136 // TODO: review exception handling
1138 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1139 activePrincipal, e.getMessage() );
1146 // for the current user logged in
1149 if ( servletAuth.isAuthorized( activePrincipal, repository,
1150 WebdavMethodUtil.getMethodPermission(
1151 request.getMethod() ) ) )
1153 mergedRepositoryContents.add( resourceFile );
1154 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1157 catch ( UnauthorizedException e )
1159 // TODO: review exception handling
1161 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1162 activePrincipal, e.getMessage() );
1173 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1176 ArchivaVirtualDavResource resource =
1177 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1180 // compatibility with MRM-440 to ensure browsing the repository group works ok
1181 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1183 throw new BrowserRedirectException( resource.getHref() );
1189 protected String getActivePrincipal( DavServletRequest request )
1191 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1192 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1196 * Check if the current user is authorized to access any of the repos
1199 * @param repositories
1200 * @param activePrincipal
1203 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1205 // when no repositories configured it's impossible to browse nothing !
1206 // at least make possible to see nothing :-)
1207 if ( repositories == null || repositories.isEmpty() )
1212 boolean allow = false;
1214 // if securitySession != null, it means that the user was prompted for authentication
1215 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1217 for ( String repository : repositories )
1221 if ( isAuthorized( request, repository ) )
1227 catch ( DavException e )
1235 for ( String repository : repositories )
1239 if ( servletAuth.isAuthorized( activePrincipal, repository,
1240 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1246 catch ( UnauthorizedException e )
1256 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1257 throws RepositoryMetadataException, DigesterException, IOException
1259 File outputFile = new File( outputFilename );
1260 if ( outputFile.exists() )
1262 FileUtils.deleteQuietly( outputFile );
1265 outputFile.getParentFile().mkdirs();
1266 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1268 createChecksumFile( outputFilename, digestSha1 );
1269 createChecksumFile( outputFilename, digestMd5 );
1274 private void createChecksumFile( String path, Digester digester )
1275 throws DigesterException, IOException
1277 File checksumFile = new File( path + digester.getFilenameExtension() );
1278 if ( !checksumFile.exists() )
1280 FileUtils.deleteQuietly( checksumFile );
1281 checksum.createChecksum( new File( path ), digester );
1283 else if ( !checksumFile.isFile() )
1285 log.error( "Checksum file is not a file." );
1289 private boolean isProjectReference( String requestedResource )
1293 metadataTools.toVersionedReference( requestedResource );
1296 catch ( RepositoryMetadataException re )
1302 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1303 DavServletRequest request,
1304 RepositoryGroupConfiguration repositoryGroupConfiguration )
1310 HttpSession session = request.getSession();
1312 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1313 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1314 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1315 if ( temporaryGroupIndexMap == null )
1317 temporaryGroupIndexMap = new HashMap<>();
1320 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1322 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1324 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1325 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1327 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1328 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1329 indexMerger.cleanTemporaryGroupIndex( tmp );
1333 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1334 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1335 return tmp.getDirectory();
1339 Set<String> authzRepos = new HashSet<String>();
1341 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1343 for ( String repository : repositories )
1347 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1349 authzRepos.add( repository );
1350 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1353 catch ( UnauthorizedException e )
1355 // TODO: review exception handling
1357 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1361 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1362 repositoryGroupConfiguration.getId(), authzRepos );
1364 File tempRepoFile = Files.createTempDirectory( "temp" ).toFile();
1365 tempRepoFile.deleteOnExit();
1367 IndexMergerRequest indexMergerRequest =
1368 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1369 repositoryGroupConfiguration.getMergedIndexPath(),
1370 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1371 tempRepoFile ).temporary( true );
1373 MergedRemoteIndexesTaskRequest taskRequest =
1374 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1376 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1378 IndexingContext indexingContext = job.execute().getIndexingContext();
1380 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1381 TemporaryGroupIndex temporaryGroupIndex =
1382 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1383 repositoryGroupConfiguration.getMergedIndexTtl() ) //
1384 .setCreationTime( new Date().getTime() );
1385 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1386 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1387 temporaryGroupIndexMap );
1388 return mergedRepoDir;
1390 catch ( RepositoryAdminException e )
1392 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1394 catch ( IndexMergerException e )
1396 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1398 catch ( IOException e )
1400 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1405 public void setServletAuth( ServletAuthenticator servletAuth )
1407 this.servletAuth = servletAuth;
1410 public void setHttpAuth( HttpAuthenticator httpAuth )
1412 this.httpAuth = httpAuth;
1415 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1417 this.scheduler = scheduler;
1420 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1422 this.archivaConfiguration = archivaConfiguration;
1425 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1427 this.repositoryFactory = repositoryFactory;
1430 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1432 this.repositoryRequest = repositoryRequest;
1435 public void setConnectors( RepositoryProxyConnectors connectors )
1437 this.connectors = connectors;
1440 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1442 return remoteRepositoryAdmin;
1445 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1447 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1450 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1452 return managedRepositoryAdmin;
1455 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1457 this.managedRepositoryAdmin = managedRepositoryAdmin;