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 com.google.common.io.Files;
23 import org.apache.archiva.admin.model.RepositoryAdminException;
24 import org.apache.archiva.admin.model.beans.ManagedRepository;
25 import org.apache.archiva.admin.model.beans.RemoteRepository;
26 import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin;
27 import org.apache.archiva.admin.model.remote.RemoteRepositoryAdmin;
28 import org.apache.archiva.audit.AuditEvent;
29 import org.apache.archiva.audit.AuditListener;
30 import org.apache.archiva.audit.Auditable;
31 import org.apache.archiva.common.filelock.FileLockManager;
32 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
33 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
34 import org.apache.archiva.common.utils.PathUtil;
35 import org.apache.archiva.common.utils.VersionUtil;
36 import org.apache.archiva.configuration.ArchivaConfiguration;
37 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
38 import org.apache.archiva.indexer.merger.IndexMerger;
39 import org.apache.archiva.indexer.merger.IndexMergerException;
40 import org.apache.archiva.indexer.merger.IndexMergerRequest;
41 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTask;
42 import org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest;
43 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
44 import org.apache.archiva.indexer.search.RepositorySearch;
45 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
46 import org.apache.archiva.metadata.repository.storage.RelocationException;
47 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
48 import org.apache.archiva.model.ArchivaRepositoryMetadata;
49 import org.apache.archiva.model.ArtifactReference;
50 import org.apache.archiva.policies.ProxyDownloadException;
51 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
52 import org.apache.archiva.redback.authentication.AuthenticationException;
53 import org.apache.archiva.redback.authentication.AuthenticationResult;
54 import org.apache.archiva.redback.authorization.AuthorizationException;
55 import org.apache.archiva.redback.authorization.UnauthorizedException;
56 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
57 import org.apache.archiva.redback.policy.AccountLockedException;
58 import org.apache.archiva.redback.policy.MustChangePasswordException;
59 import org.apache.archiva.redback.system.SecuritySession;
60 import org.apache.archiva.redback.users.User;
61 import org.apache.archiva.redback.users.UserManager;
62 import org.apache.archiva.repository.ManagedRepositoryContent;
63 import org.apache.archiva.repository.RepositoryContentFactory;
64 import org.apache.archiva.repository.RepositoryException;
65 import org.apache.archiva.repository.RepositoryNotFoundException;
66 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
67 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
68 import org.apache.archiva.repository.layout.LayoutException;
69 import org.apache.archiva.repository.metadata.MetadataTools;
70 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
71 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
72 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
73 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
74 import org.apache.archiva.security.ServletAuthenticator;
75 import org.apache.archiva.webdav.util.MimeTypes;
76 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
77 import org.apache.archiva.webdav.util.WebdavMethodUtil;
78 import org.apache.archiva.xml.XMLException;
79 import org.apache.commons.io.FileUtils;
80 import org.apache.commons.io.FilenameUtils;
81 import org.apache.commons.lang.StringUtils;
82 import org.apache.commons.lang.SystemUtils;
83 import org.apache.jackrabbit.webdav.DavException;
84 import org.apache.jackrabbit.webdav.DavResource;
85 import org.apache.jackrabbit.webdav.DavResourceFactory;
86 import org.apache.jackrabbit.webdav.DavResourceLocator;
87 import org.apache.jackrabbit.webdav.DavServletRequest;
88 import org.apache.jackrabbit.webdav.DavServletResponse;
89 import org.apache.jackrabbit.webdav.DavSession;
90 import org.apache.jackrabbit.webdav.lock.LockManager;
91 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
92 import org.apache.maven.index.context.IndexingContext;
93 import org.codehaus.plexus.digest.ChecksumFile;
94 import org.codehaus.plexus.digest.Digester;
95 import org.codehaus.plexus.digest.DigesterException;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98 import org.slf4j.MarkerFactory;
99 import org.springframework.context.ApplicationContext;
100 import org.springframework.stereotype.Service;
102 import javax.annotation.PostConstruct;
103 import javax.inject.Inject;
104 import javax.inject.Named;
105 import javax.servlet.http.HttpServletResponse;
106 import javax.servlet.http.HttpSession;
108 import java.io.IOException;
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<AuditListener>();
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()
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<String>();
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 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
245 catch ( RepositoryAdminException e )
247 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
252 // make a copy to avoid potential concurrent modifications (eg. by configuration)
253 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
255 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
256 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
257 resourcesInAbsolutePath, repoGroupConfig );
265 RemoteRepository remoteRepository =
266 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
268 if ( remoteRepository != null )
270 String logicalResource = getLogicalResource( archivaLocator, null, false );
271 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
272 File resourceFile = StringUtils.equals( logicalResource, "/" )
273 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
274 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
275 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
276 request.getRemoteAddr(), activePrincipal,
277 request.getDavSession(), archivaLocator, this, mimeTypes,
278 auditListeners, scheduler, fileLockManager );
279 setHeaders( response, locator, resource );
283 catch ( RepositoryAdminException e )
285 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
286 archivaLocator.getRepositoryId(), e.getMessage() );
289 ManagedRepositoryContent managedRepositoryContent = null;
293 managedRepositoryContent =
294 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
296 catch ( RepositoryNotFoundException e )
298 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
299 "Invalid repository: " + archivaLocator.getRepositoryId() );
301 catch ( RepositoryException e )
303 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
306 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
310 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
311 managedRepositoryAdmin.getManagedRepository(
312 archivaLocator.getRepositoryId() ) );
314 String logicalResource = getLogicalResource( archivaLocator, null, false );
315 resourcesInAbsolutePath.add(
316 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
319 catch ( RepositoryAdminException e )
321 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
325 String requestedResource = request.getRequestURI();
327 // MRM-872 : merge all available metadata
328 // merge metadata only when requested via the repo group
329 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
330 requestedResource ) ) && repoGroupConfig != null )
332 // this should only be at the project level not version level!
333 if ( isProjectReference( requestedResource ) )
336 ArchivaDavResource res = (ArchivaDavResource) resource;
338 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
340 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
342 // for MRM-872 handle checksums of the merged metadata files
343 if ( repositoryRequest.isSupportFile( requestedResource ) )
345 File metadataChecksum =
346 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
347 if ( metadataChecksum.exists() )
349 LogicalResource logicalResource =
350 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
353 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
354 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
355 archivaLocator, this, mimeTypes, auditListeners, scheduler,
361 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
363 // merge the metadata of all repos under group
364 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
365 for ( String resourceAbsPath : resourcesInAbsolutePath )
369 File metadataFile = new File( resourceAbsPath );
370 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
371 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
373 catch ( XMLException e )
375 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
376 "Error occurred while reading metadata file." );
378 catch ( RepositoryMetadataException r )
380 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
381 "Error occurred while merging metadata file." );
387 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
389 LogicalResource logicalResource =
390 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
393 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
394 request.getRemoteAddr(), activePrincipal,
395 request.getDavSession(), archivaLocator, this, mimeTypes,
396 auditListeners, scheduler, fileLockManager );
398 catch ( RepositoryMetadataException r )
400 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
401 "Error occurred while writing metadata file." );
403 catch ( IOException ie )
405 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
406 "Error occurred while generating checksum files." );
408 catch ( DigesterException de )
410 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
411 "Error occurred while generating checksum files."
419 setHeaders( response, locator, resource );
421 // compatibility with MRM-440 to ensure browsing the repository works ok
422 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
424 throw new BrowserRedirectException( resource.getHref() );
426 resource.addLockManager( lockManager );
430 private DavResource processRepositoryGroup( final DavServletRequest request,
431 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
432 String activePrincipal, List<String> resourcesInAbsolutePath,
433 RepositoryGroupConfiguration repoGroupConfig )
436 DavResource resource = null;
437 List<DavException> storedExceptions = new ArrayList<DavException>();
439 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
441 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
443 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
445 // we are in the case of index file request
446 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
447 File temporaryIndexDirectory =
448 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
450 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
451 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
452 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
453 archivaLocator, this, mimeTypes, auditListeners, scheduler,
459 for ( String repositoryId : repositories )
461 ManagedRepositoryContent managedRepositoryContent;
464 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
466 catch ( RepositoryNotFoundException e )
468 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
470 catch ( RepositoryException e )
472 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
477 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
478 DavResource updatedResource =
479 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
481 if ( resource == null )
483 resource = updatedResource;
486 String logicalResource = getLogicalResource( archivaLocator, null, false );
487 if ( logicalResource.endsWith( "/" ) )
489 logicalResource = logicalResource.substring( 1 );
491 resourcesInAbsolutePath.add(
492 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
494 catch ( DavException e )
496 storedExceptions.add( e );
498 catch ( RepositoryAdminException e )
500 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
504 if ( resource == null )
506 if ( !storedExceptions.isEmpty() )
509 for ( DavException e : storedExceptions )
511 if ( 401 == e.getErrorCode() )
517 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
521 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
527 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
528 boolean useOrigResourcePath )
530 // FIXME remove this hack
531 // but currently managedRepository can be null in case of group
532 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
533 RepositoryStorage repositoryStorage =
534 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
535 String path = repositoryStorage.getFilePath(
536 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
538 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
539 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
544 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator,
545 ManagedRepositoryContent managedRepositoryContent, String contextPath )
548 String layout = managedRepositoryContent.getRepository() == null
549 ? new ManagedRepository().getLayout()
550 : managedRepositoryContent.getRepository().getLayout();
551 RepositoryStorage repositoryStorage =
552 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
555 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(),
556 managedRepositoryContent );
558 catch ( RelocationException e )
560 String path = e.getPath();
561 log.debug( "Relocation to {}", path );
563 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
564 e.getRelocationType() );
566 catch ( XMLException e )
568 log.error( e.getMessage(), e );
569 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
573 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
574 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
575 ManagedRepository managedRepository )
578 DavResource resource = null;
579 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
581 // Maven Centric part ask evaluation if -SNAPSHOT
582 String path = evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() );
583 if ( path.startsWith( "/" ) )
585 path = path.substring( 1 );
587 LogicalResource logicalResource = new LogicalResource( path );
588 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
590 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
591 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
592 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
594 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
596 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
598 // force a resource not found
599 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
603 if ( !resource.isCollection() )
605 boolean previouslyExisted = resourceFile.exists();
607 // Attempt to fetch the resource from any defined proxy.
609 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
611 // At this point the incoming request can either be in default or
612 // legacy layout format.
615 // Perform an adjustment of the resource to the managed
616 // repository expected path.
617 String localResourcePath =
618 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
619 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
621 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
622 managedRepositoryContent.getRepository(),
623 request.getRemoteAddr(), activePrincipal,
624 request.getDavSession(), archivaLocator, this, mimeTypes,
625 auditListeners, scheduler, fileLockManager );
627 catch ( LayoutException e )
629 if ( !resourceFile.exists() )
631 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
637 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
640 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
641 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
643 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
644 logicalResource.getPath(), event, activePrincipal );
647 if ( !resourceFile.exists() )
649 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
655 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
657 String resourcePath = logicalResource.getPath();
659 // check if target repo is enabled for releases
660 // we suppose that release-artifacts can be deployed only to repos enabled for releases
661 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
662 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
664 ArtifactReference artifact = null;
667 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
669 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
671 // check if artifact already exists and if artifact re-deployment to the repository is allowed
672 if ( managedRepositoryContent.hasContent( artifact )
673 && managedRepositoryContent.getRepository().isBlockRedeployments() )
675 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
676 managedRepositoryContent.getId() );
677 throw new DavException( HttpServletResponse.SC_CONFLICT,
678 "Overwriting released artifacts is not allowed." );
682 catch ( LayoutException e )
684 log.warn( "Artifact path '{}' is invalid.", resourcePath );
689 * Create parent directories that don't exist when writing a file This actually makes this
690 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
691 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
692 * create the collections themselves.
695 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
696 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
698 if ( !destDir.exists() )
701 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
703 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
706 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
707 AuditEvent.CREATE_DIR, activePrincipal );
714 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
717 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
719 ManagedRepositoryContent managedRepositoryContent;
722 managedRepositoryContent =
723 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
725 catch ( RepositoryNotFoundException e )
727 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
728 "Invalid repository: " + archivaLocator.getRepositoryId() );
730 catch ( RepositoryException e )
732 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
735 DavResource resource = null;
738 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
739 archivaLocator.getRepositoryId() ), false );
740 if ( logicalResource.startsWith( "/" ) )
742 logicalResource = logicalResource.substring( 1 );
744 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
745 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
746 managedRepositoryContent.getRepository(), davSession, archivaLocator,
747 this, mimeTypes, auditListeners, scheduler, fileLockManager );
749 resource.addLockManager( lockManager );
751 catch ( RepositoryAdminException e )
753 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
758 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
759 LogicalResource resource )
762 String path = resource.getPath();
763 if ( repositoryRequest.isSupportFile( path ) )
765 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
767 return ( proxiedFile != null );
770 // Is it a Metadata resource?
771 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
773 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
776 // Is it an Archetype Catalog?
777 if ( repositoryRequest.isArchetypeCatalog( path ) )
779 // FIXME we must implement a merge of remote archetype catalog from remote servers.
780 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
782 return ( proxiedFile != null );
785 // Not any of the above? Then it's gotta be an artifact reference.
788 // Get the artifact reference in a layout neutral way.
789 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
791 if ( artifact != null )
793 String repositoryLayout = managedRepository.getRepository().getLayout();
795 RepositoryStorage repositoryStorage =
796 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
797 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
799 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
801 resource.setPath( managedRepository.toPath( artifact ) );
803 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
804 artifact.getVersion() );
806 return ( proxiedFile != null );
809 catch ( LayoutException e )
813 catch ( ProxyDownloadException e )
815 log.error( e.getMessage(), e );
816 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
817 "Unable to fetch artifact resource." );
824 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
827 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
828 event.setRemoteIP( remoteIP );
830 for ( AuditListener listener : auditListeners )
832 listener.auditEvent( event );
836 public void addAuditListener( AuditListener listener )
838 this.auditListeners.add( listener );
841 public void clearAuditListeners()
843 this.auditListeners.clear();
846 public void removeAuditListener( AuditListener listener )
848 this.auditListeners.remove( listener );
851 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
853 // [MRM-503] - Metadata file need Pragma:no-cache response
855 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
856 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
858 response.setHeader( "Pragma", "no-cache" );
859 response.setHeader( "Cache-Control", "no-cache" );
860 response.setDateHeader( "Last-Modified", new Date().getTime() );
862 // if the resource is a directory don't cache it as new groupId deployed will be available
863 // without need of refreshing browser
866 // We need to specify this so connecting wagons can work correctly
867 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
869 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
872 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
875 if ( !( locator instanceof ArchivaDavResourceLocator ) )
877 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
878 "Locator does not implement RepositoryLocator" );
882 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
884 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
887 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
889 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
890 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
892 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
894 return archivaLocator;
897 private static class LogicalResource
901 public LogicalResource( String path )
906 public String getPath()
911 public void setPath( String path )
917 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
922 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
923 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
925 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
927 WebdavMethodUtil.getMethodPermission(
928 request.getMethod() ) );
930 catch ( AuthenticationException e )
932 // safety check for MRM-911
933 String guest = UserManager.GUEST_USERNAME;
936 if ( servletAuth.isAuthorized( guest,
937 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
938 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
943 catch ( UnauthorizedException ae )
945 throw new UnauthorizedDavException( repositoryId,
946 "You are not authenticated and authorized to access any repository." );
949 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
951 catch ( MustChangePasswordException e )
953 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
955 catch ( AccountLockedException e )
957 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
959 catch ( AuthorizationException e )
961 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
962 "Fatal Authorization Subsystem Error." );
964 catch ( UnauthorizedException e )
966 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
970 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
971 ArchivaDavResourceLocator locator,
972 RepositoryGroupConfiguration repositoryGroupConfiguration )
973 throws DavException, RepositoryAdminException
975 List<File> mergedRepositoryContents = new ArrayList<File>();
976 // multiple repo types so we guess they are all the same type
977 // so use the first one
978 // FIXME add a method with group in the repository storage
979 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 1 );
981 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
982 if ( path.startsWith( "/" ) )
984 path = path.substring( 1 );
986 LogicalResource logicalResource = new LogicalResource( path );
989 // if the current user logged in has permission to any of the repositories, allow user to
990 // browse the repo group but displaying only the repositories which the user has permission to access.
991 // otherwise, prompt for authentication.
993 String activePrincipal = getActivePrincipal( request );
995 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
998 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1003 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1005 File mergedRepoDir =
1006 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1007 mergedRepositoryContents.add( mergedRepoDir );
1011 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1013 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1014 repositoryGroupConfiguration.getId() + "/"
1015 + repositoryGroupConfiguration.getMergedIndexPath() );
1016 if ( !tmpDirectory.exists() )
1018 synchronized ( tmpDirectory.getAbsolutePath() )
1020 if ( !tmpDirectory.exists() )
1022 tmpDirectory.mkdirs();
1026 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1028 for ( String repository : repositories )
1030 ManagedRepositoryContent managedRepository = null;
1034 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1036 catch ( RepositoryNotFoundException e )
1038 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1039 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1041 catch ( RepositoryException e )
1043 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1044 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1047 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1048 if ( resourceFile.exists() )
1050 // in case of group displaying index directory doesn't have sense !!
1051 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1052 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1054 if ( !new File( repoIndexDirectory ).isAbsolute() )
1056 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1057 StringUtils.isEmpty( repoIndexDirectory )
1059 : repoIndexDirectory ).getAbsolutePath();
1062 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1064 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1065 ".indexer" ).getAbsolutePath();
1068 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1069 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1071 // for prompted authentication
1072 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1076 if ( isAuthorized( request, repository ) )
1078 mergedRepositoryContents.add( resourceFile );
1079 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1082 catch ( DavException e )
1084 // TODO: review exception handling
1086 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1087 activePrincipal, e.getMessage() );
1094 // for the current user logged in
1097 if ( servletAuth.isAuthorized( activePrincipal, repository,
1098 WebdavMethodUtil.getMethodPermission(
1099 request.getMethod() ) ) )
1101 mergedRepositoryContents.add( resourceFile );
1102 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1105 catch ( UnauthorizedException e )
1107 // TODO: review exception handling
1109 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1110 activePrincipal, e.getMessage() );
1121 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1124 ArchivaVirtualDavResource resource =
1125 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1128 // compatibility with MRM-440 to ensure browsing the repository group works ok
1129 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1131 throw new BrowserRedirectException( resource.getHref() );
1137 protected String getActivePrincipal( DavServletRequest request )
1139 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1140 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1144 * Check if the current user is authorized to access any of the repos
1147 * @param repositories
1148 * @param activePrincipal
1151 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1153 // when no repositories configured it's impossible to browse nothing !
1154 // at least make possible to see nothing :-)
1155 if ( repositories == null || repositories.isEmpty() )
1160 boolean allow = false;
1162 // if securitySession != null, it means that the user was prompted for authentication
1163 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1165 for ( String repository : repositories )
1169 if ( isAuthorized( request, repository ) )
1175 catch ( DavException e )
1183 for ( String repository : repositories )
1187 if ( servletAuth.isAuthorized( activePrincipal, repository,
1188 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1194 catch ( UnauthorizedException e )
1204 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1205 throws RepositoryMetadataException, DigesterException, IOException
1207 File outputFile = new File( outputFilename );
1208 if ( outputFile.exists() )
1210 FileUtils.deleteQuietly( outputFile );
1213 outputFile.getParentFile().mkdirs();
1214 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1216 createChecksumFile( outputFilename, digestSha1 );
1217 createChecksumFile( outputFilename, digestMd5 );
1222 private void createChecksumFile( String path, Digester digester )
1223 throws DigesterException, IOException
1225 File checksumFile = new File( path + digester.getFilenameExtension() );
1226 if ( !checksumFile.exists() )
1228 FileUtils.deleteQuietly( checksumFile );
1229 checksum.createChecksum( new File( path ), digester );
1231 else if ( !checksumFile.isFile() )
1233 log.error( "Checksum file is not a file." );
1237 private boolean isProjectReference( String requestedResource )
1241 metadataTools.toVersionedReference( requestedResource );
1244 catch ( RepositoryMetadataException re )
1250 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1251 DavServletRequest request,
1252 RepositoryGroupConfiguration repositoryGroupConfiguration )
1258 HttpSession session = request.getSession();
1260 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1261 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1262 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1263 if ( temporaryGroupIndexMap == null )
1265 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1268 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1270 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1272 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1273 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1275 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1276 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1277 indexMerger.cleanTemporaryGroupIndex( tmp );
1281 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1282 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1283 return tmp.getDirectory();
1287 Set<String> authzRepos = new HashSet<String>();
1289 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1291 for ( String repository : repositories )
1295 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1297 authzRepos.add( repository );
1298 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1301 catch ( UnauthorizedException e )
1303 // TODO: review exception handling
1305 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1309 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1310 repositoryGroupConfiguration.getId(), authzRepos );
1312 File tempRepoFile = Files.createTempDir();
1313 tempRepoFile.deleteOnExit();
1315 IndexMergerRequest indexMergerRequest = new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1316 repositoryGroupConfiguration.getMergedIndexPath(),
1317 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory( tempRepoFile );
1319 MergedRemoteIndexesTaskRequest taskRequest =
1320 new MergedRemoteIndexesTaskRequest(indexMergerRequest, indexMerger);
1322 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1324 IndexingContext indexingContext = job.execute().getIndexingContext();
1326 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1327 TemporaryGroupIndex temporaryGroupIndex =
1328 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1329 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1330 new Date().getTime() );
1331 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1332 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1333 temporaryGroupIndexMap );
1334 return mergedRepoDir;
1336 catch ( RepositoryAdminException e )
1338 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1340 catch ( IndexMergerException e )
1342 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1347 public void setServletAuth( ServletAuthenticator servletAuth )
1349 this.servletAuth = servletAuth;
1352 public void setHttpAuth( HttpAuthenticator httpAuth )
1354 this.httpAuth = httpAuth;
1357 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1359 this.scheduler = scheduler;
1362 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1364 this.archivaConfiguration = archivaConfiguration;
1367 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1369 this.repositoryFactory = repositoryFactory;
1372 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1374 this.repositoryRequest = repositoryRequest;
1377 public void setConnectors( RepositoryProxyConnectors connectors )
1379 this.connectors = connectors;
1382 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1384 return remoteRepositoryAdmin;
1387 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1389 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1392 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1394 return managedRepositoryAdmin;
1397 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1399 this.managedRepositoryAdmin = managedRepositoryAdmin;