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.TemporaryGroupIndex;
43 import org.apache.archiva.indexer.search.RepositorySearch;
44 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
45 import org.apache.archiva.metadata.repository.storage.RelocationException;
46 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
47 import org.apache.archiva.model.ArchivaRepositoryMetadata;
48 import org.apache.archiva.model.ArtifactReference;
49 import org.apache.archiva.policies.ProxyDownloadException;
50 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
51 import org.apache.archiva.redback.authentication.AuthenticationException;
52 import org.apache.archiva.redback.authentication.AuthenticationResult;
53 import org.apache.archiva.redback.authorization.AuthorizationException;
54 import org.apache.archiva.redback.authorization.UnauthorizedException;
55 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
56 import org.apache.archiva.redback.policy.AccountLockedException;
57 import org.apache.archiva.redback.policy.MustChangePasswordException;
58 import org.apache.archiva.redback.system.SecuritySession;
59 import org.apache.archiva.redback.users.User;
60 import org.apache.archiva.redback.users.UserManager;
61 import org.apache.archiva.repository.ManagedRepositoryContent;
62 import org.apache.archiva.repository.RepositoryContentFactory;
63 import org.apache.archiva.repository.RepositoryException;
64 import org.apache.archiva.repository.RepositoryNotFoundException;
65 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
66 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
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.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<AuditListener>();
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( new LegacyPathParser( archivaConfiguration ) );
206 public void initialize()
211 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
212 final DavServletResponse response )
215 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
217 RepositoryGroupConfiguration repoGroupConfig =
218 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
220 String activePrincipal = getActivePrincipal( request );
222 List<String> resourcesInAbsolutePath = new ArrayList<String>();
224 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
225 DavResource resource;
226 if ( repoGroupConfig != null )
230 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
231 "Write method not allowed for repository groups." );
234 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
236 // handle browse requests for virtual repos
237 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
241 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
244 catch ( RepositoryAdminException e )
246 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
251 // make a copy to avoid potential concurrent modifications (eg. by configuration)
252 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
254 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
255 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
256 resourcesInAbsolutePath, repoGroupConfig );
264 RemoteRepository remoteRepository =
265 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
267 if ( remoteRepository != null )
269 String logicalResource = getLogicalResource( archivaLocator, null, false );
270 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
271 File resourceFile = StringUtils.equals( logicalResource, "/" )
272 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
273 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
274 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
275 request.getRemoteAddr(), activePrincipal,
276 request.getDavSession(), archivaLocator, this, mimeTypes,
277 auditListeners, scheduler, fileLockManager );
278 setHeaders( response, locator, resource );
282 catch ( RepositoryAdminException e )
284 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
285 archivaLocator.getRepositoryId(), e.getMessage() );
288 ManagedRepositoryContent managedRepositoryContent = null;
292 managedRepositoryContent =
293 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
295 catch ( RepositoryNotFoundException e )
297 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
298 "Invalid repository: " + archivaLocator.getRepositoryId() );
300 catch ( RepositoryException e )
302 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
305 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
309 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
310 managedRepositoryAdmin.getManagedRepository(
311 archivaLocator.getRepositoryId() ) );
313 String logicalResource = getLogicalResource( archivaLocator, null, false );
314 resourcesInAbsolutePath.add(
315 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
318 catch ( RepositoryAdminException e )
320 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
324 String requestedResource = request.getRequestURI();
326 // MRM-872 : merge all available metadata
327 // merge metadata only when requested via the repo group
328 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
329 requestedResource ) ) && repoGroupConfig != null )
331 // this should only be at the project level not version level!
332 if ( isProjectReference( requestedResource ) )
335 ArchivaDavResource res = (ArchivaDavResource) resource;
337 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
339 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
341 // for MRM-872 handle checksums of the merged metadata files
342 if ( repositoryRequest.isSupportFile( requestedResource ) )
344 File metadataChecksum =
345 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
346 if ( metadataChecksum.exists() )
348 LogicalResource logicalResource =
349 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
352 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
353 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
354 archivaLocator, this, mimeTypes, auditListeners, scheduler,
360 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
362 // merge the metadata of all repos under group
363 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
364 for ( String resourceAbsPath : resourcesInAbsolutePath )
368 File metadataFile = new File( resourceAbsPath );
369 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
370 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
372 catch ( XMLException e )
374 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
375 "Error occurred while reading metadata file." );
377 catch ( RepositoryMetadataException r )
379 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
380 "Error occurred while merging metadata file." );
386 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
388 LogicalResource logicalResource =
389 new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
392 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
393 request.getRemoteAddr(), activePrincipal,
394 request.getDavSession(), archivaLocator, this, mimeTypes,
395 auditListeners, scheduler, fileLockManager );
397 catch ( RepositoryMetadataException r )
399 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
400 "Error occurred while writing metadata file." );
402 catch ( IOException ie )
404 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
405 "Error occurred while generating checksum files." );
407 catch ( DigesterException de )
409 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
410 "Error occurred while generating checksum files."
418 setHeaders( response, locator, resource );
420 // compatibility with MRM-440 to ensure browsing the repository works ok
421 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
423 throw new BrowserRedirectException( resource.getHref() );
425 resource.addLockManager( lockManager );
429 private DavResource processRepositoryGroup( final DavServletRequest request,
430 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
431 String activePrincipal, List<String> resourcesInAbsolutePath,
432 RepositoryGroupConfiguration repoGroupConfig )
435 DavResource resource = null;
436 List<DavException> storedExceptions = new ArrayList<DavException>();
438 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
440 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
442 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
444 // we are in the case of index file request
445 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
446 File temporaryIndexDirectory =
447 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
449 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
450 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
451 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
452 archivaLocator, this, mimeTypes, auditListeners, scheduler,
458 for ( String repositoryId : repositories )
460 ManagedRepositoryContent managedRepositoryContent;
463 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
465 catch ( RepositoryNotFoundException e )
467 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
469 catch ( RepositoryException e )
471 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
476 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
477 DavResource updatedResource =
478 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
480 if ( resource == null )
482 resource = updatedResource;
485 String logicalResource = getLogicalResource( archivaLocator, null, false );
486 if ( logicalResource.endsWith( "/" ) )
488 logicalResource = logicalResource.substring( 1 );
490 resourcesInAbsolutePath.add(
491 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
493 catch ( DavException e )
495 storedExceptions.add( e );
497 catch ( RepositoryAdminException e )
499 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
503 if ( resource == null )
505 if ( !storedExceptions.isEmpty() )
508 for ( DavException e : storedExceptions )
510 if ( 401 == e.getErrorCode() )
516 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
520 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
526 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
527 boolean useOrigResourcePath )
529 // FIXME remove this hack
530 // but currently managedRepository can be null in case of group
531 String layout = managedRepository == null ? new ManagedRepository().getLayout() : managedRepository.getLayout();
532 RepositoryStorage repositoryStorage =
533 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
534 String path = repositoryStorage.getFilePath(
535 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(),
537 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
538 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(),
543 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator,
544 ManagedRepositoryContent managedRepositoryContent, String contextPath )
547 String layout = managedRepositoryContent.getRepository() == null
548 ? new ManagedRepository().getLayout()
549 : managedRepositoryContent.getRepository().getLayout();
550 RepositoryStorage repositoryStorage =
551 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
554 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(),
555 managedRepositoryContent );
557 catch ( RelocationException e )
559 String path = e.getPath();
560 log.debug( "Relocation to {}", path );
562 throw new BrowserRedirectException( contextPath + ( StringUtils.startsWith( path, "/" ) ? "" : "/" ) + path,
563 e.getRelocationType() );
565 catch ( XMLException e )
567 log.error( e.getMessage(), e );
568 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
572 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
573 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
574 ManagedRepository managedRepository )
577 DavResource resource = null;
578 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
580 // Maven Centric part ask evaluation if -SNAPSHOT
581 String path = evaluatePathWithVersion( archivaLocator, managedRepositoryContent, request.getContextPath() );
582 if ( path.startsWith( "/" ) )
584 path = path.substring( 1 );
586 LogicalResource logicalResource = new LogicalResource( path );
587 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
589 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
590 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
591 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
593 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
595 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
597 // force a resource not found
598 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
602 if ( !resource.isCollection() )
604 boolean previouslyExisted = resourceFile.exists();
606 // Attempt to fetch the resource from any defined proxy.
608 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
610 // At this point the incoming request can either be in default or
611 // legacy layout format.
614 // Perform an adjustment of the resource to the managed
615 // repository expected path.
616 String localResourcePath =
617 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
618 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
620 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
621 managedRepositoryContent.getRepository(),
622 request.getRemoteAddr(), activePrincipal,
623 request.getDavSession(), archivaLocator, this, mimeTypes,
624 auditListeners, scheduler, fileLockManager );
626 catch ( LayoutException e )
628 if ( !resourceFile.exists() )
630 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
636 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
639 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
640 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
642 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
643 logicalResource.getPath(), event, activePrincipal );
646 if ( !resourceFile.exists() )
648 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
654 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
656 String resourcePath = logicalResource.getPath();
658 // check if target repo is enabled for releases
659 // we suppose that release-artifacts can be deployed only to repos enabled for releases
660 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
661 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
663 ArtifactReference artifact = null;
666 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
668 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
670 // check if artifact already exists and if artifact re-deployment to the repository is allowed
671 if ( managedRepositoryContent.hasContent( artifact )
672 && managedRepositoryContent.getRepository().isBlockRedeployments() )
674 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
675 managedRepositoryContent.getId() );
676 throw new DavException( HttpServletResponse.SC_CONFLICT,
677 "Overwriting released artifacts is not allowed." );
681 catch ( LayoutException e )
683 log.warn( "Artifact path '{}' is invalid.", resourcePath );
688 * Create parent directories that don't exist when writing a file This actually makes this
689 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
690 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
691 * create the collections themselves.
694 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
695 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
697 if ( !destDir.exists() )
700 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
702 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
705 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
706 AuditEvent.CREATE_DIR, activePrincipal );
713 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
716 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
718 ManagedRepositoryContent managedRepositoryContent;
721 managedRepositoryContent =
722 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
724 catch ( RepositoryNotFoundException e )
726 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
727 "Invalid repository: " + archivaLocator.getRepositoryId() );
729 catch ( RepositoryException e )
731 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
734 DavResource resource = null;
737 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
738 archivaLocator.getRepositoryId() ), false );
739 if ( logicalResource.startsWith( "/" ) )
741 logicalResource = logicalResource.substring( 1 );
743 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
744 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
745 managedRepositoryContent.getRepository(), davSession, archivaLocator,
746 this, mimeTypes, auditListeners, scheduler, fileLockManager );
748 resource.addLockManager( lockManager );
750 catch ( RepositoryAdminException e )
752 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
757 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
758 LogicalResource resource )
761 String path = resource.getPath();
762 if ( repositoryRequest.isSupportFile( path ) )
764 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
766 return ( proxiedFile != null );
769 // Is it a Metadata resource?
770 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
772 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
775 // Is it an Archetype Catalog?
776 if ( repositoryRequest.isArchetypeCatalog( path ) )
778 // FIXME we must implement a merge of remote archetype catalog from remote servers.
779 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
781 return ( proxiedFile != null );
784 // Not any of the above? Then it's gotta be an artifact reference.
787 // Get the artifact reference in a layout neutral way.
788 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
790 if ( artifact != null )
792 String repositoryLayout = managedRepository.getRepository().getLayout();
794 RepositoryStorage repositoryStorage =
795 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
796 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
798 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
800 resource.setPath( managedRepository.toPath( artifact ) );
802 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
803 artifact.getVersion() );
805 return ( proxiedFile != null );
808 catch ( LayoutException e )
812 catch ( ProxyDownloadException e )
814 log.error( e.getMessage(), e );
815 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
816 "Unable to fetch artifact resource." );
823 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
826 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
827 event.setRemoteIP( remoteIP );
829 for ( AuditListener listener : auditListeners )
831 listener.auditEvent( event );
835 public void addAuditListener( AuditListener listener )
837 this.auditListeners.add( listener );
840 public void clearAuditListeners()
842 this.auditListeners.clear();
845 public void removeAuditListener( AuditListener listener )
847 this.auditListeners.remove( listener );
850 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
852 // [MRM-503] - Metadata file need Pragma:no-cache response
854 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
855 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
857 response.setHeader( "Pragma", "no-cache" );
858 response.setHeader( "Cache-Control", "no-cache" );
859 response.setDateHeader( "Last-Modified", new Date().getTime() );
861 // if the resource is a directory don't cache it as new groupId deployed will be available
862 // without need of refreshing browser
865 // We need to specify this so connecting wagons can work correctly
866 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
868 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
871 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
874 if ( !( locator instanceof ArchivaDavResourceLocator ) )
876 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
877 "Locator does not implement RepositoryLocator" );
881 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
883 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
886 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
888 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
889 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
891 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
893 return archivaLocator;
896 private static class LogicalResource
900 public LogicalResource( String path )
905 public String getPath()
910 public void setPath( String path )
916 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
921 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
922 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
924 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
926 WebdavMethodUtil.getMethodPermission(
927 request.getMethod() ) );
929 catch ( AuthenticationException e )
931 // safety check for MRM-911
932 String guest = UserManager.GUEST_USERNAME;
935 if ( servletAuth.isAuthorized( guest,
936 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
937 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
942 catch ( UnauthorizedException ae )
944 throw new UnauthorizedDavException( repositoryId,
945 "You are not authenticated and authorized to access any repository." );
948 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
950 catch ( MustChangePasswordException e )
952 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
954 catch ( AccountLockedException e )
956 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
958 catch ( AuthorizationException e )
960 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
961 "Fatal Authorization Subsystem Error." );
963 catch ( UnauthorizedException e )
965 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
969 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
970 ArchivaDavResourceLocator locator,
971 RepositoryGroupConfiguration repositoryGroupConfiguration )
972 throws DavException, RepositoryAdminException
974 List<File> mergedRepositoryContents = new ArrayList<File>();
975 // multiple repo types so we guess they are all the same type
976 // so use the first one
977 // FIXME add a method with group in the repository storage
978 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 1 );
980 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
981 if ( path.startsWith( "/" ) )
983 path = path.substring( 1 );
985 LogicalResource logicalResource = new LogicalResource( path );
988 // if the current user logged in has permission to any of the repositories, allow user to
989 // browse the repo group but displaying only the repositories which the user has permission to access.
990 // otherwise, prompt for authentication.
992 String activePrincipal = getActivePrincipal( request );
994 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
997 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
1002 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
1004 File mergedRepoDir =
1005 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
1006 mergedRepositoryContents.add( mergedRepoDir );
1010 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1012 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1013 repositoryGroupConfiguration.getId() + "/"
1014 + repositoryGroupConfiguration.getMergedIndexPath() );
1015 if ( !tmpDirectory.exists() )
1017 synchronized ( tmpDirectory.getAbsolutePath() )
1019 if ( !tmpDirectory.exists() )
1021 tmpDirectory.mkdirs();
1025 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1027 for ( String repository : repositories )
1029 ManagedRepositoryContent managedRepository = null;
1033 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1035 catch ( RepositoryNotFoundException e )
1037 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1038 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1040 catch ( RepositoryException e )
1042 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1043 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1046 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1047 if ( resourceFile.exists() )
1049 // in case of group displaying index directory doesn't have sense !!
1050 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1051 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1053 if ( !new File( repoIndexDirectory ).isAbsolute() )
1055 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1056 StringUtils.isEmpty( repoIndexDirectory )
1058 : repoIndexDirectory ).getAbsolutePath();
1061 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1063 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1064 ".indexer" ).getAbsolutePath();
1067 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1068 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1070 // for prompted authentication
1071 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1075 if ( isAuthorized( request, repository ) )
1077 mergedRepositoryContents.add( resourceFile );
1078 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1081 catch ( DavException e )
1083 // TODO: review exception handling
1085 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1086 activePrincipal, e.getMessage() );
1093 // for the current user logged in
1096 if ( servletAuth.isAuthorized( activePrincipal, repository,
1097 WebdavMethodUtil.getMethodPermission(
1098 request.getMethod() ) ) )
1100 mergedRepositoryContents.add( resourceFile );
1101 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1104 catch ( UnauthorizedException e )
1106 // TODO: review exception handling
1108 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1109 activePrincipal, e.getMessage() );
1120 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1123 ArchivaVirtualDavResource resource =
1124 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1127 // compatibility with MRM-440 to ensure browsing the repository group works ok
1128 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1130 throw new BrowserRedirectException( resource.getHref() );
1136 protected String getActivePrincipal( DavServletRequest request )
1138 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1139 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1143 * Check if the current user is authorized to access any of the repos
1146 * @param repositories
1147 * @param activePrincipal
1150 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1152 // when no repositories configured it's impossible to browse nothing !
1153 // at least make possible to see nothing :-)
1154 if ( repositories == null || repositories.isEmpty() )
1159 boolean allow = false;
1161 // if securitySession != null, it means that the user was prompted for authentication
1162 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1164 for ( String repository : repositories )
1168 if ( isAuthorized( request, repository ) )
1174 catch ( DavException e )
1182 for ( String repository : repositories )
1186 if ( servletAuth.isAuthorized( activePrincipal, repository,
1187 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1193 catch ( UnauthorizedException e )
1203 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1204 throws RepositoryMetadataException, DigesterException, IOException
1206 File outputFile = new File( outputFilename );
1207 if ( outputFile.exists() )
1209 FileUtils.deleteQuietly( outputFile );
1212 outputFile.getParentFile().mkdirs();
1213 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1215 createChecksumFile( outputFilename, digestSha1 );
1216 createChecksumFile( outputFilename, digestMd5 );
1221 private void createChecksumFile( String path, Digester digester )
1222 throws DigesterException, IOException
1224 File checksumFile = new File( path + digester.getFilenameExtension() );
1225 if ( !checksumFile.exists() )
1227 FileUtils.deleteQuietly( checksumFile );
1228 checksum.createChecksum( new File( path ), digester );
1230 else if ( !checksumFile.isFile() )
1232 log.error( "Checksum file is not a file." );
1236 private boolean isProjectReference( String requestedResource )
1240 metadataTools.toVersionedReference( requestedResource );
1243 catch ( RepositoryMetadataException re )
1249 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1250 DavServletRequest request,
1251 RepositoryGroupConfiguration repositoryGroupConfiguration )
1257 HttpSession session = request.getSession();
1259 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1260 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1261 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1262 if ( temporaryGroupIndexMap == null )
1264 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1267 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1269 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1271 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1272 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1274 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1275 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1276 indexMerger.cleanTemporaryGroupIndex( tmp );
1280 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1281 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1282 return tmp.getDirectory();
1286 Set<String> authzRepos = new HashSet<String>();
1288 String permission = WebdavMethodUtil.getMethodPermission( request.getMethod() );
1290 for ( String repository : repositories )
1294 if ( servletAuth.isAuthorized( activePrincipal, repository, permission ) )
1296 authzRepos.add( repository );
1297 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1300 catch ( UnauthorizedException e )
1302 // TODO: review exception handling
1304 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1308 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1309 repositoryGroupConfiguration.getId(), authzRepos );
1311 File tempRepoFile = Files.createTempDir();
1312 tempRepoFile.deleteOnExit();
1314 IndexMergerRequest indexMergerRequest = new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1315 repositoryGroupConfiguration.getMergedIndexPath(),
1316 repositoryGroupConfiguration.getMergedIndexTtl() ).mergedIndexDirectory( tempRepoFile );
1318 MergedRemoteIndexesTask.MergedRemoteIndexesTaskRequest taskRequest =
1319 new MergedRemoteIndexesTask.MergedRemoteIndexesTaskRequest(indexMergerRequest, indexMerger);
1321 MergedRemoteIndexesTask job = new MergedRemoteIndexesTask( taskRequest );
1323 IndexingContext indexingContext = job.execute().getIndexingContext();
1325 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1326 TemporaryGroupIndex temporaryGroupIndex =
1327 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1328 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1329 new Date().getTime() );
1330 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1331 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1332 temporaryGroupIndexMap );
1333 return mergedRepoDir;
1335 catch ( RepositoryAdminException e )
1337 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1339 catch ( IndexMergerException e )
1341 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1346 public void setServletAuth( ServletAuthenticator servletAuth )
1348 this.servletAuth = servletAuth;
1351 public void setHttpAuth( HttpAuthenticator httpAuth )
1353 this.httpAuth = httpAuth;
1356 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1358 this.scheduler = scheduler;
1361 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1363 this.archivaConfiguration = archivaConfiguration;
1366 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1368 this.repositoryFactory = repositoryFactory;
1371 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1373 this.repositoryRequest = repositoryRequest;
1376 public void setConnectors( RepositoryProxyConnectors connectors )
1378 this.connectors = connectors;
1381 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1383 return remoteRepositoryAdmin;
1386 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1388 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1391 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1393 return managedRepositoryAdmin;
1396 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1398 this.managedRepositoryAdmin = managedRepositoryAdmin;