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.maven2.RepositoryRequest;
65 import org.apache.archiva.repository.events.AuditListener;
66 import org.apache.archiva.repository.layout.LayoutException;
67 import org.apache.archiva.repository.metadata.MetadataTools;
68 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
69 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
71 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
72 import org.apache.archiva.security.ServletAuthenticator;
73 import org.apache.archiva.webdav.util.MimeTypes;
74 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
75 import org.apache.archiva.webdav.util.WebdavMethodUtil;
76 import org.apache.archiva.xml.XMLException;
77 import org.apache.commons.io.FileUtils;
78 import org.apache.commons.io.FilenameUtils;
79 import org.apache.commons.lang.StringUtils;
80 import org.apache.commons.lang.SystemUtils;
81 import org.apache.jackrabbit.webdav.DavException;
82 import org.apache.jackrabbit.webdav.DavResource;
83 import org.apache.jackrabbit.webdav.DavResourceFactory;
84 import org.apache.jackrabbit.webdav.DavResourceLocator;
85 import org.apache.jackrabbit.webdav.DavServletRequest;
86 import org.apache.jackrabbit.webdav.DavServletResponse;
87 import org.apache.jackrabbit.webdav.DavSession;
88 import org.apache.jackrabbit.webdav.lock.LockManager;
89 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
90 import org.apache.maven.index.context.IndexingContext;
91 import org.codehaus.plexus.digest.ChecksumFile;
92 import org.codehaus.plexus.digest.Digester;
93 import org.codehaus.plexus.digest.DigesterException;
94 import org.slf4j.Logger;
95 import org.slf4j.LoggerFactory;
96 import org.slf4j.MarkerFactory;
97 import org.springframework.context.ApplicationContext;
98 import org.springframework.stereotype.Service;
100 import javax.annotation.PostConstruct;
101 import javax.inject.Inject;
102 import javax.inject.Named;
103 import javax.servlet.http.HttpServletResponse;
104 import javax.servlet.http.HttpSession;
106 import java.io.IOException;
107 import java.nio.file.Files;
108 import java.util.ArrayList;
109 import java.util.Date;
110 import java.util.HashMap;
111 import java.util.HashSet;
112 import java.util.List;
113 import java.util.Map;
114 import java.util.Set;
119 @Service( "davResourceFactory#archiva" )
120 public class ArchivaDavResourceFactory
121 implements DavResourceFactory, Auditable
123 private static final String PROXIED_SUFFIX = " (proxied)";
125 private static final String HTTP_PUT_METHOD = "PUT";
127 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
130 private List<AuditListener> auditListeners = new ArrayList<>();
133 private RepositoryContentFactory repositoryFactory;
135 private RepositoryRequest repositoryRequest;
138 @Named( value = "repositoryProxyConnectors#default" )
139 private RepositoryProxyConnectors connectors;
142 private MetadataTools metadataTools;
145 private MimeTypes mimeTypes;
147 private ArchivaConfiguration archivaConfiguration;
150 private ServletAuthenticator servletAuth;
153 @Named( value = "httpAuthenticator#basic" )
154 private HttpAuthenticator httpAuth;
157 private RemoteRepositoryAdmin remoteRepositoryAdmin;
160 private ManagedRepositoryAdmin managedRepositoryAdmin;
163 private IndexMerger indexMerger;
166 private RepositorySearch repositorySearch;
169 * Lock Manager - use simple implementation from JackRabbit
171 private final LockManager lockManager = new SimpleLockManager();
173 private ChecksumFile checksum;
175 private Digester digestSha1;
177 private Digester digestMd5;
180 @Named( value = "archivaTaskScheduler#repository" )
181 private RepositoryArchivaTaskScheduler scheduler;
184 @Named( value = "fileLockManager#default" )
185 private FileLockManager fileLockManager;
187 private ApplicationContext applicationContext;
190 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
191 ArchivaConfiguration archivaConfiguration )
192 throws PlexusSisuBridgeException
194 this.archivaConfiguration = archivaConfiguration;
195 this.applicationContext = applicationContext;
196 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
198 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
199 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
201 // TODO remove this hard dependency on maven !!
202 repositoryRequest = new RepositoryRequest( );
206 public void initialize()
212 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
213 final DavServletResponse response )
216 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
218 RepositoryGroupConfiguration repoGroupConfig =
219 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
221 String activePrincipal = getActivePrincipal( request );
223 List<String> resourcesInAbsolutePath = new ArrayList<>();
225 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
226 DavResource resource;
227 if ( repoGroupConfig != null )
231 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
232 "Write method not allowed for repository groups." );
235 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
237 // handle browse requests for virtual repos
238 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
242 DavResource davResource =
243 getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
246 setHeaders( response, locator, davResource, true );
251 catch ( RepositoryAdminException e )
253 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
258 // make a copy to avoid potential concurrent modifications (eg. by configuration)
259 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
261 List<String> repositories = new ArrayList<>( repoGroupConfig.getRepositories() );
262 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
263 resourcesInAbsolutePath, repoGroupConfig );
271 RemoteRepository remoteRepository =
272 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
274 if ( remoteRepository != null )
276 String logicalResource = getLogicalResource( archivaLocator, null, false );
277 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
278 File resourceFile = StringUtils.equals( logicalResource, "/" )
279 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
280 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
281 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), //
282 locator.getResourcePath(), //
284 request.getRemoteAddr(), //
286 request.getDavSession(), //
293 setHeaders( response, locator, resource, false );
297 catch ( RepositoryAdminException e )
299 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
300 archivaLocator.getRepositoryId(), e.getMessage() );
303 ManagedRepositoryContent managedRepositoryContent = null;
307 managedRepositoryContent =
308 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
310 catch ( RepositoryNotFoundException e )
312 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
313 "Invalid repository: " + archivaLocator.getRepositoryId() );
315 catch ( RepositoryException e )
317 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
320 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
324 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
325 managedRepositoryAdmin.getManagedRepository(
326 archivaLocator.getRepositoryId() ) );
328 String logicalResource = getLogicalResource( archivaLocator, null, false );
329 resourcesInAbsolutePath.add(
330 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
333 catch ( RepositoryAdminException e )
335 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
339 String requestedResource = request.getRequestURI();
341 // MRM-872 : merge all available metadata
342 // merge metadata only when requested via the repo group
343 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
344 requestedResource ) ) && repoGroupConfig != null )
346 // this should only be at the project level not version level!
347 if ( isProjectReference( requestedResource ) )
350 ArchivaDavResource res = (ArchivaDavResource) resource;
352 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
354 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
356 // for MRM-872 handle checksums of the merged metadata files
357 if ( repositoryRequest.isSupportFile( requestedResource ) )
359 File metadataChecksum =
360 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
362 if ( metadataChecksum.exists() )
364 LogicalResource logicalResource =
365 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
368 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
369 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
370 archivaLocator, this, mimeTypes, auditListeners, scheduler,
376 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
378 // merge the metadata of all repos under group
379 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
380 for ( String resourceAbsPath : resourcesInAbsolutePath )
384 File metadataFile = new File( resourceAbsPath );
385 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
386 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
388 catch ( XMLException e )
390 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
391 "Error occurred while reading metadata file." );
393 catch ( RepositoryMetadataException r )
395 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
396 "Error occurred while merging metadata file." );
402 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
404 LogicalResource logicalResource =
405 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
408 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
409 request.getRemoteAddr(), activePrincipal,
410 request.getDavSession(), archivaLocator, this, mimeTypes,
411 auditListeners, scheduler, fileLockManager );
413 catch ( RepositoryMetadataException r )
415 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
416 "Error occurred while writing metadata file." );
418 catch ( IOException ie )
420 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
421 "Error occurred while generating checksum files." );
423 catch ( DigesterException de )
425 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
426 "Error occurred while generating checksum files."
434 setHeaders( response, locator, resource, false );
436 // compatibility with MRM-440 to ensure browsing the repository works ok
437 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
439 throw new BrowserRedirectException( resource.getHref() );
441 resource.addLockManager( lockManager );
445 private DavResource processRepositoryGroup( final DavServletRequest request,
446 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
447 String activePrincipal, List<String> resourcesInAbsolutePath,
448 RepositoryGroupConfiguration repoGroupConfig )
451 DavResource resource = null;
452 List<DavException> storedExceptions = new ArrayList<>();
454 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
456 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
458 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
460 // we are in the case of index file request
461 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
462 File temporaryIndexDirectory =
463 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
465 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
466 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
467 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
468 archivaLocator, this, mimeTypes, auditListeners, scheduler,
474 for ( String repositoryId : repositories )
476 ManagedRepositoryContent managedRepositoryContent;
479 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
481 catch ( RepositoryNotFoundException e )
483 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
485 catch ( RepositoryException e )
487 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
492 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
493 DavResource updatedResource =
494 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
496 if ( resource == null )
498 resource = updatedResource;
501 String logicalResource = getLogicalResource( archivaLocator, null, false );
502 if ( logicalResource.endsWith( "/" ) )
504 logicalResource = logicalResource.substring( 1 );
506 resourcesInAbsolutePath.add(
507 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
509 catch ( DavException e )
511 storedExceptions.add( e );
513 catch ( RepositoryAdminException e )
515 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
519 if ( resource == null )
521 if ( !storedExceptions.isEmpty() )
524 for ( DavException e : storedExceptions )
526 if ( 401 == e.getErrorCode() )
532 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
536 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
542 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
543 boolean useOrigResourcePath )
545 // FIXME remove this hack
546 // but currently managedRepository can be null in case of group
547 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
548 RepositoryStorage repositoryStorage =
549 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
550 String path = repositoryStorage.getFilePath(
551 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
553 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
554 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
559 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, //
560 ManagedRepositoryContent managedRepositoryContent, //
564 String layout = managedRepositoryContent.getRepository() == null
565 ? new ManagedRepository().getLayout()
566 : managedRepositoryContent.getRepository().getLayout();
567 RepositoryStorage repositoryStorage =
568 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
571 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), //
572 managedRepositoryContent );
574 catch ( RelocationException e )
576 String path = e.getPath();
577 log.debug( "Relocation to {}", path );
579 throw new BrowserRedirectException( addHrefPrefix( contextPath, path ), e.getRelocationType() );
581 catch ( XMLException e )
583 log.error( e.getMessage(), e );
584 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
588 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
589 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
590 ManagedRepository managedRepository )
593 DavResource resource = null;
594 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
596 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
597 // Maven Centric part ask evaluation if -SNAPSHOT
598 // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false
600 String path = readMethod
601 ? evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() )
602 : getLogicalResource( archivaLocator, managedRepository, false );
603 if ( path.startsWith( "/" ) )
605 path = path.substring( 1 );
607 LogicalResource logicalResource = new LogicalResource( path );
608 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
610 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
611 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
612 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
614 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
616 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
618 // force a resource not found
619 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
623 if ( !resource.isCollection() )
625 boolean previouslyExisted = resourceFile.exists();
627 boolean fromProxy = fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
629 // At this point the incoming request can either be in default or
630 // legacy layout format.
633 // Perform an adjustment of the resource to the managed
634 // repository expected path.
635 String localResourcePath =
636 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
637 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
639 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
640 managedRepositoryContent.getRepository(),
641 request.getRemoteAddr(), activePrincipal,
642 request.getDavSession(), archivaLocator, this, mimeTypes,
643 auditListeners, scheduler, fileLockManager );
645 catch ( LayoutException e )
647 if ( !resourceFile.exists() )
649 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
655 String action = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
658 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
659 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
661 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
662 logicalResource.getPath(), action, activePrincipal );
665 if ( !resourceFile.exists() )
667 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
673 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
675 String resourcePath = logicalResource.getPath();
677 // check if target repo is enabled for releases
678 // we suppose that release-artifacts can be deployed only to repos enabled for releases
679 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
680 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
682 ArtifactReference artifact = null;
685 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
687 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
689 // check if artifact already exists and if artifact re-deployment to the repository is allowed
690 if ( managedRepositoryContent.hasContent( artifact )
691 && managedRepositoryContent.getRepository().isBlockRedeployments() )
693 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
694 managedRepositoryContent.getId() );
695 throw new DavException( HttpServletResponse.SC_CONFLICT,
696 "Overwriting released artifacts is not allowed." );
700 catch ( LayoutException e )
702 log.warn( "Artifact path '{}' is invalid.", resourcePath );
707 * Create parent directories that don't exist when writing a file This actually makes this
708 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
709 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
710 * create the collections themselves.
713 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
714 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
716 if ( !destDir.exists() )
719 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
721 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
724 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
725 AuditEvent.CREATE_DIR, activePrincipal );
733 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
736 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
738 ManagedRepositoryContent managedRepositoryContent;
741 managedRepositoryContent =
742 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
744 catch ( RepositoryNotFoundException e )
746 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
747 "Invalid repository: " + archivaLocator.getRepositoryId() );
749 catch ( RepositoryException e )
751 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
754 DavResource resource = null;
757 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
758 archivaLocator.getRepositoryId() ), false );
759 if ( logicalResource.startsWith( "/" ) )
761 logicalResource = logicalResource.substring( 1 );
763 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
764 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
765 managedRepositoryContent.getRepository(), davSession, archivaLocator,
766 this, mimeTypes, auditListeners, scheduler, fileLockManager );
768 resource.addLockManager( lockManager );
770 catch ( RepositoryAdminException e )
772 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
777 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
778 LogicalResource resource )
781 String path = resource.getPath();
782 if ( repositoryRequest.isSupportFile( path ) )
784 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
786 return ( proxiedFile != null );
789 // Is it a Metadata resource?
790 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
792 return connectors.fetchMetadataFromProxies( managedRepository, path ).isModified();
795 // Is it an Archetype Catalog?
796 if ( repositoryRequest.isArchetypeCatalog( path ) )
798 // FIXME we must implement a merge of remote archetype catalog from remote servers.
799 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
801 return ( proxiedFile != null );
804 // Not any of the above? Then it's gotta be an artifact reference.
807 // Get the artifact reference in a layout neutral way.
808 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
810 if ( artifact != null )
812 String repositoryLayout = managedRepository.getRepository().getLayout();
814 RepositoryStorage repositoryStorage =
815 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
816 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
818 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
820 resource.setPath( managedRepository.toPath( artifact ) );
822 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
823 artifact.getVersion() );
825 return ( proxiedFile != null );
828 catch ( LayoutException e )
832 catch ( ProxyDownloadException e )
834 log.error( e.getMessage(), e );
835 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
836 "Unable to fetch artifact resource." );
843 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
846 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
847 event.setRemoteIP( remoteIP );
849 for ( AuditListener listener : auditListeners )
851 listener.auditEvent( event );
856 public void addAuditListener( AuditListener listener )
858 this.auditListeners.add( listener );
862 public void clearAuditListeners()
864 this.auditListeners.clear();
868 public void removeAuditListener( AuditListener listener )
870 this.auditListeners.remove( listener );
873 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource,
876 // [MRM-503] - Metadata file need Pragma:no-cache response
878 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || ( resource instanceof ArchivaDavResource
879 && ( ArchivaDavResource.class.cast( resource ).getLocalResource().isDirectory() ) ) )
881 response.setHeader( "Pragma", "no-cache" );
882 response.setHeader( "Cache-Control", "no-cache" );
883 response.setDateHeader( "Last-Modified", new Date().getTime() );
885 // if the resource is a directory don't cache it as new groupId deployed will be available
886 // without need of refreshing browser
887 else if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) || (
888 resource instanceof ArchivaVirtualDavResource && ( new File(
889 ArchivaVirtualDavResource.class.cast( resource ).getLogicalResource() ).isDirectory() ) ) )
891 response.setHeader( "Pragma", "no-cache" );
892 response.setHeader( "Cache-Control", "no-cache" );
893 response.setDateHeader( "Last-Modified", new Date().getTime() );
897 if ( resource instanceof ArchivaVirtualDavResource )
899 //MRM-1854 here we have a directory so force "Last-Modified"
900 response.setDateHeader( "Last-Modified", new Date().getTime() );
905 // We need to specify this so connecting wagons can work correctly
906 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
908 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
911 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
914 if ( !( locator instanceof ArchivaDavResourceLocator ) )
916 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
917 "Locator does not implement RepositoryLocator" );
921 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
923 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
926 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
928 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
929 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
931 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
933 return archivaLocator;
936 private String addHrefPrefix( String contextPath, String path ) {
937 String prefix = archivaConfiguration.getConfiguration().getWebapp().getUi().getApplicationUrl();
938 if (prefix == null || prefix.isEmpty()) {
939 prefix = contextPath;
941 return prefix + ( StringUtils.startsWith( path, "/" ) ? "" :
942 ( StringUtils.endsWith( prefix, "/" ) ? "" : "/" ) )
946 private static class LogicalResource
950 public LogicalResource( String path )
955 public String getPath()
960 public void setPath( String path )
966 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
971 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
972 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
974 return servletAuth.isAuthenticated( request, result ) //
975 && servletAuth.isAuthorized( request, securitySession, repositoryId, //
976 WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
978 catch ( AuthenticationException e )
980 // safety check for MRM-911
981 String guest = UserManager.GUEST_USERNAME;
984 if ( servletAuth.isAuthorized( guest,
985 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
986 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
991 catch ( UnauthorizedException ae )
993 throw new UnauthorizedDavException( repositoryId,
994 "You are not authenticated and authorized to access any repository." );
997 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
999 catch ( MustChangePasswordException e )
1001 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
1003 catch ( AccountLockedException e )
1005 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
1007 catch ( AuthorizationException e )
1009 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1010 "Fatal Authorization Subsystem Error." );
1012 catch ( UnauthorizedException e )
1014 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
1018 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
1019 ArchivaDavResourceLocator locator,
1020 RepositoryGroupConfiguration repositoryGroupConfiguration )
1021 throws DavException, RepositoryAdminException
1023 if ( repositoryGroupConfiguration.getRepositories() == null
1024 || repositoryGroupConfiguration.getRepositories().isEmpty() )
1027 new File( System.getProperty( "appserver.base" ), "groups/" + repositoryGroupConfiguration.getId() );
1029 return new ArchivaDavResource( file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
1030 request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler,
1033 List<File> mergedRepositoryContents = new ArrayList<>();
1034 // multiple repo types so we guess they are all the same type
1035 // so use the first one
1036 // FIXME add a method with group in the repository storage
1037 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 0 );
1039 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
1040 if ( path.startsWith( "/" ) )
1042 path = path.substring( 1 );
1044 LogicalResource logicalResource = new LogicalResource( path );
1047 // if the current user logged in has permission to any of the repositories, allow user to
1048 // browse the repo group but displaying only the repositories which the user has permission to access.
1049 // otherwise, prompt for authentication.
1051 String activePrincipal = getActivePrincipal( request );
1053 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
1056 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1061 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1063 File mergedRepoDir =
1064 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1065 mergedRepositoryContents.add( mergedRepoDir );
1069 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1071 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1072 repositoryGroupConfiguration.getId() + "/"
1073 + repositoryGroupConfiguration.getMergedIndexPath() );
1074 if ( !tmpDirectory.exists() )
1076 synchronized ( tmpDirectory.getAbsolutePath() )
1078 if ( !tmpDirectory.exists() )
1080 tmpDirectory.mkdirs();
1084 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1086 for ( String repository : repositories )
1088 ManagedRepositoryContent managedRepository = null;
1092 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1094 catch ( RepositoryNotFoundException e )
1096 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1097 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1099 catch ( RepositoryException e )
1101 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1102 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1105 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1106 if ( resourceFile.exists() )
1108 // in case of group displaying index directory doesn't have sense !!
1109 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1110 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1112 if ( !new File( repoIndexDirectory ).isAbsolute() )
1114 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1115 StringUtils.isEmpty( repoIndexDirectory )
1117 : repoIndexDirectory ).getAbsolutePath();
1120 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1122 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1123 ".indexer" ).getAbsolutePath();
1126 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1127 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1129 // for prompted authentication
1130 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1134 if ( isAuthorized( request, repository ) )
1136 mergedRepositoryContents.add( resourceFile );
1137 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1140 catch ( DavException e )
1142 // TODO: review exception handling
1144 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1145 activePrincipal, e.getMessage() );
1152 // for the current user logged in
1155 if ( servletAuth.isAuthorized( activePrincipal, repository,
1156 WebdavMethodUtil.getMethodPermission(
1157 request.getMethod() ) ) )
1159 mergedRepositoryContents.add( resourceFile );
1160 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1163 catch ( UnauthorizedException e )
1165 // TODO: review exception handling
1167 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1168 activePrincipal, e.getMessage() );
1179 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1182 ArchivaVirtualDavResource resource =
1183 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1186 // compatibility with MRM-440 to ensure browsing the repository group works ok
1187 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1189 throw new BrowserRedirectException( resource.getHref() );
1195 protected String getActivePrincipal( DavServletRequest request )
1197 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1198 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1202 * Check if the current user is authorized to access any of the repos
1205 * @param repositories
1206 * @param activePrincipal
1209 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1211 // when no repositories configured it's impossible to browse nothing !
1212 // at least make possible to see nothing :-)
1213 if ( repositories == null || repositories.isEmpty() )
1218 boolean allow = false;
1220 // if securitySession != null, it means that the user was prompted for authentication
1221 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1223 for ( String repository : repositories )
1227 if ( isAuthorized( request, repository ) )
1233 catch ( DavException e )
1241 for ( String repository : repositories )
1245 if ( servletAuth.isAuthorized( activePrincipal, repository,
1246 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1252 catch ( UnauthorizedException e )
1262 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1263 throws RepositoryMetadataException, DigesterException, IOException
1265 File outputFile = new File( outputFilename );
1266 if ( outputFile.exists() )
1268 FileUtils.deleteQuietly( outputFile );
1271 outputFile.getParentFile().mkdirs();
1272 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1274 createChecksumFile( outputFilename, digestSha1 );
1275 createChecksumFile( outputFilename, digestMd5 );
1280 private void createChecksumFile( String path, Digester digester )
1281 throws DigesterException, IOException
1283 File checksumFile = new File( path + digester.getFilenameExtension() );
1284 if ( !checksumFile.exists() )
1286 FileUtils.deleteQuietly( checksumFile );
1287 checksum.createChecksum( new File( path ), digester );
1289 else if ( !checksumFile.isFile() )
1291 log.error( "Checksum file is not a file." );
1295 private boolean isProjectReference( String requestedResource )
1299 metadataTools.toVersionedReference( requestedResource );
1302 catch ( RepositoryMetadataException re )
1308 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1309 DavServletRequest request,
1310 RepositoryGroupConfiguration repositoryGroupConfiguration )
1316 HttpSession session = request.getSession();
1318 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1319 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1320 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1321 if ( temporaryGroupIndexMap == null )
1323 temporaryGroupIndexMap = new HashMap<>();
1326 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1328 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1330 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1331 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1333 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1334 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1335 indexMerger.cleanTemporaryGroupIndex( tmp );
1339 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1340 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1341 return tmp.getDirectory();
1345 Set<String> authzRepos = new HashSet<String>();
1347 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1349 for ( String repository : repositories )
1353 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1355 authzRepos.add( repository );
1356 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1359 catch ( UnauthorizedException e )
1361 // TODO: review exception handling
1363 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1367 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1368 repositoryGroupConfiguration.getId(), authzRepos );
1370 File tempRepoFile = Files.createTempDirectory( "temp" ).toFile();
1371 tempRepoFile.deleteOnExit();
1373 IndexMergerRequest indexMergerRequest =
1374 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1375 repositoryGroupConfiguration.getMergedIndexPath(),
1376 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory(
1377 tempRepoFile ).temporary( true );
1379 MergedRemoteIndexesTaskRequest taskRequest =
1380 new MergedRemoteIndexesTaskRequest( indexMergerRequest, indexMerger );
1382 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1384 IndexingContext indexingContext = job.execute().getIndexingContext();
1386 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1387 TemporaryGroupIndex temporaryGroupIndex =
1388 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1389 repositoryGroupConfiguration.getMergedIndexTtl() ) //
1390 .setCreationTime( new Date().getTime() );
1391 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1392 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1393 temporaryGroupIndexMap );
1394 return mergedRepoDir;
1396 catch ( RepositoryAdminException e )
1398 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1400 catch ( IndexMergerException e )
1402 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1404 catch ( IOException e )
1406 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1411 public void setServletAuth( ServletAuthenticator servletAuth )
1413 this.servletAuth = servletAuth;
1416 public void setHttpAuth( HttpAuthenticator httpAuth )
1418 this.httpAuth = httpAuth;
1421 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1423 this.scheduler = scheduler;
1426 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1428 this.archivaConfiguration = archivaConfiguration;
1431 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1433 this.repositoryFactory = repositoryFactory;
1436 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1438 this.repositoryRequest = repositoryRequest;
1441 public void setConnectors( RepositoryProxyConnectors connectors )
1443 this.connectors = connectors;
1446 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1448 return remoteRepositoryAdmin;
1451 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1453 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1456 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1458 return managedRepositoryAdmin;
1461 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1463 this.managedRepositoryAdmin = managedRepositoryAdmin;