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.AuditEvent;
28 import org.apache.archiva.audit.AuditListener;
29 import org.apache.archiva.audit.Auditable;
30 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
31 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
32 import org.apache.archiva.common.utils.PathUtil;
33 import org.apache.archiva.common.utils.VersionUtil;
34 import org.apache.archiva.configuration.ArchivaConfiguration;
35 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
36 import org.apache.archiva.indexer.merger.IndexMerger;
37 import org.apache.archiva.indexer.merger.IndexMergerException;
38 import org.apache.archiva.indexer.merger.IndexMergerRequest;
39 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
40 import org.apache.archiva.indexer.search.RepositorySearch;
41 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
42 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
43 import org.apache.archiva.model.ArchivaRepositoryMetadata;
44 import org.apache.archiva.model.ArtifactReference;
45 import org.apache.archiva.policies.ProxyDownloadException;
46 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
47 import org.apache.archiva.redback.authentication.AuthenticationException;
48 import org.apache.archiva.redback.authentication.AuthenticationResult;
49 import org.apache.archiva.redback.authorization.AuthorizationException;
50 import org.apache.archiva.redback.authorization.UnauthorizedException;
51 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
52 import org.apache.archiva.redback.policy.AccountLockedException;
53 import org.apache.archiva.redback.policy.MustChangePasswordException;
54 import org.apache.archiva.redback.system.SecuritySession;
55 import org.apache.archiva.redback.users.User;
56 import org.apache.archiva.redback.users.UserManager;
57 import org.apache.archiva.repository.ManagedRepositoryContent;
58 import org.apache.archiva.repository.RepositoryContentFactory;
59 import org.apache.archiva.repository.RepositoryException;
60 import org.apache.archiva.repository.RepositoryNotFoundException;
61 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
62 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
63 import org.apache.archiva.repository.layout.LayoutException;
64 import org.apache.archiva.repository.metadata.MetadataTools;
65 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
66 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
67 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
68 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
69 import org.apache.archiva.security.ServletAuthenticator;
70 import org.apache.archiva.webdav.util.MimeTypes;
71 import org.apache.archiva.webdav.util.RepositoryPathUtil;
72 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
73 import org.apache.archiva.webdav.util.WebdavMethodUtil;
74 import org.apache.archiva.xml.XMLException;
75 import org.apache.commons.io.FileUtils;
76 import org.apache.commons.io.FilenameUtils;
77 import org.apache.commons.lang.StringUtils;
78 import org.apache.commons.lang.SystemUtils;
79 import org.apache.jackrabbit.webdav.DavException;
80 import org.apache.jackrabbit.webdav.DavResource;
81 import org.apache.jackrabbit.webdav.DavResourceFactory;
82 import org.apache.jackrabbit.webdav.DavResourceLocator;
83 import org.apache.jackrabbit.webdav.DavServletRequest;
84 import org.apache.jackrabbit.webdav.DavServletResponse;
85 import org.apache.jackrabbit.webdav.DavSession;
86 import org.apache.jackrabbit.webdav.lock.LockManager;
87 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
88 import org.apache.maven.index.context.IndexingContext;
89 import org.codehaus.plexus.digest.ChecksumFile;
90 import org.codehaus.plexus.digest.Digester;
91 import org.codehaus.plexus.digest.DigesterException;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
94 import org.slf4j.MarkerFactory;
95 import org.springframework.context.ApplicationContext;
96 import org.springframework.stereotype.Service;
98 import javax.annotation.PostConstruct;
99 import javax.inject.Inject;
100 import javax.inject.Named;
101 import javax.servlet.http.HttpServletResponse;
102 import javax.servlet.http.HttpSession;
104 import java.io.IOException;
105 import java.util.ArrayList;
106 import java.util.Date;
107 import java.util.HashMap;
108 import java.util.HashSet;
109 import java.util.List;
110 import java.util.Map;
111 import java.util.Set;
116 @Service( "davResourceFactory#archiva" )
117 public class ArchivaDavResourceFactory
118 implements DavResourceFactory, Auditable
120 private static final String PROXIED_SUFFIX = " (proxied)";
122 private static final String HTTP_PUT_METHOD = "PUT";
124 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
127 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
130 private RepositoryContentFactory repositoryFactory;
132 private RepositoryRequest repositoryRequest;
135 @Named( value = "repositoryProxyConnectors#default" )
136 private RepositoryProxyConnectors connectors;
139 private MetadataTools metadataTools;
142 private MimeTypes mimeTypes;
144 private ArchivaConfiguration archivaConfiguration;
147 private ServletAuthenticator servletAuth;
150 @Named( value = "httpAuthenticator#basic" )
151 private HttpAuthenticator httpAuth;
154 private RemoteRepositoryAdmin remoteRepositoryAdmin;
157 private ManagedRepositoryAdmin managedRepositoryAdmin;
160 private IndexMerger indexMerger;
163 private RepositorySearch repositorySearch;
166 * Lock Manager - use simple implementation from JackRabbit
168 private final LockManager lockManager = new SimpleLockManager();
170 private ChecksumFile checksum;
172 private Digester digestSha1;
174 private Digester digestMd5;
177 @Named( value = "archivaTaskScheduler#repository" )
178 private RepositoryArchivaTaskScheduler scheduler;
180 private ApplicationContext applicationContext;
183 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
184 ArchivaConfiguration archivaConfiguration )
185 throws PlexusSisuBridgeException
187 this.archivaConfiguration = archivaConfiguration;
188 this.applicationContext = applicationContext;
189 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
191 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
192 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
194 // TODO remove this hard dependency on maven !!
195 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
199 public void initialize()
204 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
205 final DavServletResponse response )
208 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
210 RepositoryGroupConfiguration repoGroupConfig =
211 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
213 String activePrincipal = getActivePrincipal( request );
215 List<String> resourcesInAbsolutePath = new ArrayList<String>();
217 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
218 DavResource resource;
219 if ( repoGroupConfig != null )
223 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
224 "Write method not allowed for repository groups." );
227 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
229 // handle browse requests for virtual repos
230 if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
232 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
237 // make a copy to avoid potential concurrent modifications (eg. by configuration)
238 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
240 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
241 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
242 resourcesInAbsolutePath, repoGroupConfig );
250 RemoteRepository remoteRepository =
251 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
253 if ( remoteRepository != null )
255 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
256 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
257 File resourceFile = StringUtils.equals( logicalResource, "/" )
258 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
259 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
260 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
261 request.getRemoteAddr(), activePrincipal,
262 request.getDavSession(), archivaLocator, this, mimeTypes,
263 auditListeners, scheduler );
264 setHeaders( response, locator, resource );
268 catch ( RepositoryAdminException e )
270 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
271 archivaLocator.getRepositoryId(), e.getMessage() );
274 ManagedRepositoryContent managedRepositoryContent = null;
278 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
280 catch ( RepositoryNotFoundException e )
282 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
283 "Invalid repository: " + archivaLocator.getRepositoryId() );
285 catch ( RepositoryException e )
287 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
290 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
294 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
295 managedRepositoryAdmin.getManagedRepository( archivaLocator.getRepositoryId() ) );
297 catch ( RepositoryAdminException e )
299 throw new DavException( 500, e );
302 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
303 resourcesInAbsolutePath.add(
304 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
307 String requestedResource = request.getRequestURI();
309 // MRM-872 : merge all available metadata
310 // merge metadata only when requested via the repo group
311 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
312 requestedResource ) ) && repoGroupConfig != null )
314 // this should only be at the project level not version level!
315 if ( isProjectReference( requestedResource ) )
318 ArchivaDavResource res = (ArchivaDavResource) resource;
320 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
322 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
324 // for MRM-872 handle checksums of the merged metadata files
325 if ( repositoryRequest.isSupportFile( requestedResource ) )
327 File metadataChecksum =
328 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
329 if ( metadataChecksum.exists() )
331 LogicalResource logicalResource =
332 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
335 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
336 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
337 archivaLocator, this, mimeTypes, auditListeners, scheduler );
342 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
344 // merge the metadata of all repos under group
345 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
346 for ( String resourceAbsPath : resourcesInAbsolutePath )
350 File metadataFile = new File( resourceAbsPath );
351 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
352 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
354 catch ( XMLException e )
356 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
357 "Error occurred while reading metadata file." );
359 catch ( RepositoryMetadataException r )
361 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
362 "Error occurred while merging metadata file." );
368 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
370 LogicalResource logicalResource = new LogicalResource(
371 RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
374 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
375 request.getRemoteAddr(), activePrincipal,
376 request.getDavSession(), archivaLocator, this, mimeTypes,
377 auditListeners, scheduler );
379 catch ( RepositoryMetadataException r )
381 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
382 "Error occurred while writing metadata file." );
384 catch ( IOException ie )
386 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
387 "Error occurred while generating checksum files." );
389 catch ( DigesterException de )
391 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
392 "Error occurred while generating checksum files." );
399 setHeaders( response, locator, resource );
401 // compatibility with MRM-440 to ensure browsing the repository works ok
402 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
404 throw new BrowserRedirectException( resource.getHref() );
406 resource.addLockManager( lockManager );
410 private DavResource processRepositoryGroup( final DavServletRequest request,
411 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
412 String activePrincipal, List<String> resourcesInAbsolutePath,
413 RepositoryGroupConfiguration repoGroupConfig )
416 DavResource resource = null;
417 List<DavException> storedExceptions = new ArrayList<DavException>();
419 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
421 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
423 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
425 // we are in the case of index file request
426 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
427 File temporaryIndexDirectory =
428 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
430 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
431 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
432 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
433 archivaLocator, this, mimeTypes, auditListeners, scheduler );
438 for ( String repositoryId : repositories )
440 ManagedRepositoryContent managedRepository;
443 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
445 catch ( RepositoryNotFoundException e )
447 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
449 catch ( RepositoryException e )
451 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
456 DavResource updatedResource =
457 processRepository( request, archivaLocator, activePrincipal, managedRepository,
458 managedRepositoryAdmin.getManagedRepository( repositoryId ) );
459 if ( resource == null )
461 resource = updatedResource;
464 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
465 if ( logicalResource.endsWith( "/" ) )
467 logicalResource = logicalResource.substring( 1 );
469 resourcesInAbsolutePath.add(
470 new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
472 catch ( DavException e )
474 storedExceptions.add( e );
476 catch ( RepositoryAdminException e )
478 storedExceptions.add( new DavException( 500, e ) );
482 if ( resource == null )
484 if ( !storedExceptions.isEmpty() )
487 for ( DavException e : storedExceptions )
489 if ( 401 == e.getErrorCode() )
495 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
499 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
505 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
506 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
507 ManagedRepository managedRepository )
510 DavResource resource = null;
511 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
513 RepositoryStorage repositoryStorage =
514 this.applicationContext.getBean( "repositoryStorage#" + managedRepository.getLayout(),
515 RepositoryStorage.class );
516 String path = repositoryStorage.getFilePath( archivaLocator.getResourcePath(), managedRepository );
517 if ( path.startsWith( "/" ) )
519 path = path.substring( 1 );
521 LogicalResource logicalResource = new LogicalResource( path );
522 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
524 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
525 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
526 archivaLocator, this, mimeTypes, auditListeners, scheduler );
528 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
530 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
532 // force a resource not found
533 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
537 if ( !resource.isCollection() )
539 boolean previouslyExisted = resourceFile.exists();
541 // Attempt to fetch the resource from any defined proxy.
543 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
545 // At this point the incoming request can either be in default or
546 // legacy layout format.
549 // Perform an adjustment of the resource to the managed
550 // repository expected path.
551 String localResourcePath =
552 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
553 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
555 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
556 managedRepositoryContent.getRepository(),
557 request.getRemoteAddr(), activePrincipal,
558 request.getDavSession(), archivaLocator, this, mimeTypes,
559 auditListeners, scheduler );
561 catch ( LayoutException e )
563 if ( !resourceFile.exists() )
565 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
571 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
574 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
575 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
577 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
578 logicalResource.getPath(), event, activePrincipal );
581 if ( !resourceFile.exists() )
583 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
589 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
591 String resourcePath = logicalResource.getPath();
593 // check if target repo is enabled for releases
594 // we suppose that release-artifacts can be deployed only to repos enabled for releases
595 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
596 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
598 ArtifactReference artifact = null;
601 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
603 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
605 // check if artifact already exists and if artifact re-deployment to the repository is allowed
606 if ( managedRepositoryContent.hasContent( artifact )
607 && managedRepositoryContent.getRepository().isBlockRedeployments() )
609 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
610 managedRepositoryContent.getId() );
611 throw new DavException( HttpServletResponse.SC_CONFLICT,
612 "Overwriting released artifacts is not allowed." );
616 catch ( LayoutException e )
618 log.warn( "Artifact path '{}' is invalid.", resourcePath );
623 * Create parent directories that don't exist when writing a file This actually makes this
624 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
625 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
626 * create the collections themselves.
629 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
630 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
632 if ( !destDir.exists() )
635 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
637 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
640 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
641 AuditEvent.CREATE_DIR, activePrincipal );
647 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
650 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
652 ManagedRepositoryContent managedRepository;
655 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
657 catch ( RepositoryNotFoundException e )
659 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
660 "Invalid repository: " + archivaLocator.getRepositoryId() );
662 catch ( RepositoryException e )
664 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
667 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
668 if ( logicalResource.startsWith( "/" ) )
670 logicalResource = logicalResource.substring( 1 );
672 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
673 DavResource resource =
674 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
675 davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
677 resource.addLockManager( lockManager );
681 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
682 LogicalResource resource )
685 String path = resource.getPath();
686 if ( repositoryRequest.isSupportFile( path ) )
688 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
690 return ( proxiedFile != null );
693 // Is it a Metadata resource?
694 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
696 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
699 // Is it an Archetype Catalog?
700 if ( repositoryRequest.isArchetypeCatalog( path ) )
702 // FIXME we must implement a merge of remote archetype catalog from remote servers.
703 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
705 return ( proxiedFile != null );
708 // Not any of the above? Then it's gotta be an artifact reference.
711 // Get the artifact reference in a layout neutral way.
712 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
714 if ( artifact != null )
716 String repositoryLayout = managedRepository.getRepository().getLayout();
718 RepositoryStorage repositoryStorage =
719 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
720 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
722 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
724 resource.setPath( managedRepository.toPath( artifact ) );
726 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
727 artifact.getVersion() );
729 return ( proxiedFile != null );
732 catch ( LayoutException e )
736 catch ( ProxyDownloadException e )
738 log.error( e.getMessage(), e );
739 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
740 "Unable to fetch artifact resource." );
747 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
750 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
751 event.setRemoteIP( remoteIP );
753 for ( AuditListener listener : auditListeners )
755 listener.auditEvent( event );
759 public void addAuditListener( AuditListener listener )
761 this.auditListeners.add( listener );
764 public void clearAuditListeners()
766 this.auditListeners.clear();
769 public void removeAuditListener( AuditListener listener )
771 this.auditListeners.remove( listener );
774 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
776 // [MRM-503] - Metadata file need Pragma:no-cache response
778 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
779 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
781 response.setHeader( "Pragma", "no-cache" );
782 response.setHeader( "Cache-Control", "no-cache" );
783 response.setDateHeader( "Last-Modified", new Date().getTime() );
785 // if the resource is a directory don't cache it as new groupId deployed will be available
786 // without need of refreshing browser
789 // We need to specify this so connecting wagons can work correctly
790 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
792 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
795 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
798 if ( !( locator instanceof ArchivaDavResourceLocator ) )
800 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
801 "Locator does not implement RepositoryLocator" );
805 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
807 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
810 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
812 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
813 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
815 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
817 return archivaLocator;
820 private static class LogicalResource
824 public LogicalResource( String path )
829 public String getPath()
834 public void setPath( String path )
840 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
845 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
846 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
848 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
850 WebdavMethodUtil.getMethodPermission(
851 request.getMethod() ) );
853 catch ( AuthenticationException e )
855 // safety check for MRM-911
856 String guest = UserManager.GUEST_USERNAME;
859 if ( servletAuth.isAuthorized( guest,
860 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
861 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
866 catch ( UnauthorizedException ae )
868 throw new UnauthorizedDavException( repositoryId,
869 "You are not authenticated and authorized to access any repository." );
872 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
874 catch ( MustChangePasswordException e )
876 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
878 catch ( AccountLockedException e )
880 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
882 catch ( AuthorizationException e )
884 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
885 "Fatal Authorization Subsystem Error." );
887 catch ( UnauthorizedException e )
889 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
893 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
894 ArchivaDavResourceLocator locator,
895 RepositoryGroupConfiguration repositoryGroupConfiguration )
898 List<File> mergedRepositoryContents = new ArrayList<File>();
899 String path = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
900 if ( path.startsWith( "/" ) )
902 path = path.substring( 1 );
904 LogicalResource logicalResource = new LogicalResource( path );
907 // if the current user logged in has permission to any of the repositories, allow user to
908 // browse the repo group but displaying only the repositories which the user has permission to access.
909 // otherwise, prompt for authentication.
911 String activePrincipal = getActivePrincipal( request );
913 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
916 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
921 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
924 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
925 mergedRepositoryContents.add( mergedRepoDir );
929 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
931 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
932 repositoryGroupConfiguration.getId() + "/"
933 + repositoryGroupConfiguration.getMergedIndexPath() );
934 if ( !tmpDirectory.exists() )
936 synchronized ( tmpDirectory.getAbsolutePath() )
938 if ( !tmpDirectory.exists() )
940 tmpDirectory.mkdirs();
944 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
946 for ( String repository : repositories )
948 ManagedRepositoryContent managedRepository = null;
952 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
954 catch ( RepositoryNotFoundException e )
956 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
957 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
959 catch ( RepositoryException e )
961 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
962 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
965 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
966 if ( resourceFile.exists() )
968 // in case of group displaying index directory doesn't have sense !!
969 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
970 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
972 if ( !new File( repoIndexDirectory ).isAbsolute() )
974 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
975 StringUtils.isEmpty( repoIndexDirectory )
977 : repoIndexDirectory ).getAbsolutePath();
980 if ( StringUtils.isEmpty( repoIndexDirectory ) )
982 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
983 ".indexer" ).getAbsolutePath();
986 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
987 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
989 // for prompted authentication
990 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
994 if ( isAuthorized( request, repository ) )
996 mergedRepositoryContents.add( resourceFile );
997 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1000 catch ( DavException e )
1002 // TODO: review exception handling
1004 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1005 activePrincipal, e.getMessage() );
1012 // for the current user logged in
1015 if ( servletAuth.isAuthorized( activePrincipal, repository,
1016 WebdavMethodUtil.getMethodPermission(
1017 request.getMethod() ) ) )
1019 mergedRepositoryContents.add( resourceFile );
1020 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1023 catch ( UnauthorizedException e )
1025 // TODO: review exception handling
1027 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1028 activePrincipal, e.getMessage() );
1039 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1042 ArchivaVirtualDavResource resource =
1043 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1046 // compatibility with MRM-440 to ensure browsing the repository group works ok
1047 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1049 throw new BrowserRedirectException( resource.getHref() );
1055 protected String getActivePrincipal( DavServletRequest request )
1057 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1058 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1062 * Check if the current user is authorized to access any of the repos
1065 * @param repositories
1066 * @param activePrincipal
1069 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1071 // when no repositories configured it's impossible to browse nothing !
1072 // at least make possible to see nothing :-)
1073 if ( repositories == null || repositories.isEmpty() )
1078 boolean allow = false;
1080 // if securitySession != null, it means that the user was prompted for authentication
1081 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1083 for ( String repository : repositories )
1087 if ( isAuthorized( request, repository ) )
1093 catch ( DavException e )
1101 for ( String repository : repositories )
1105 if ( servletAuth.isAuthorized( activePrincipal, repository,
1106 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1112 catch ( UnauthorizedException e )
1122 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1123 throws RepositoryMetadataException, DigesterException, IOException
1125 File outputFile = new File( outputFilename );
1126 if ( outputFile.exists() )
1128 FileUtils.deleteQuietly( outputFile );
1131 outputFile.getParentFile().mkdirs();
1132 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1134 createChecksumFile( outputFilename, digestSha1 );
1135 createChecksumFile( outputFilename, digestMd5 );
1140 private void createChecksumFile( String path, Digester digester )
1141 throws DigesterException, IOException
1143 File checksumFile = new File( path + digester.getFilenameExtension() );
1144 if ( !checksumFile.exists() )
1146 FileUtils.deleteQuietly( checksumFile );
1147 checksum.createChecksum( new File( path ), digester );
1149 else if ( !checksumFile.isFile() )
1151 log.error( "Checksum file is not a file." );
1155 private boolean isProjectReference( String requestedResource )
1159 metadataTools.toVersionedReference( requestedResource );
1162 catch ( RepositoryMetadataException re )
1168 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1169 DavServletRequest request,
1170 RepositoryGroupConfiguration repositoryGroupConfiguration )
1176 HttpSession session = request.getSession();
1178 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1179 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1180 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1181 if ( temporaryGroupIndexMap == null )
1183 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1186 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1188 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1190 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1191 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1193 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1194 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1195 indexMerger.cleanTemporaryGroupIndex( tmp );
1199 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1200 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1201 return tmp.getDirectory();
1205 Set<String> authzRepos = new HashSet<String>();
1206 for ( String repository : repositories )
1210 if ( servletAuth.isAuthorized( activePrincipal, repository,
1211 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1213 authzRepos.add( repository );
1214 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1217 catch ( UnauthorizedException e )
1219 // TODO: review exception handling
1221 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1225 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1226 repositoryGroupConfiguration.getId(), authzRepos );
1227 IndexingContext indexingContext = indexMerger.buildMergedIndex(
1228 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1229 repositoryGroupConfiguration.getMergedIndexPath(),
1230 repositoryGroupConfiguration.getMergedIndexTtl() ) );
1231 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1232 TemporaryGroupIndex temporaryGroupIndex =
1233 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1234 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1235 new Date().getTime() );
1236 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1237 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1238 temporaryGroupIndexMap );
1239 return mergedRepoDir;
1241 catch ( RepositoryAdminException e )
1243 throw new DavException( 500, e );
1245 catch ( IndexMergerException e )
1247 throw new DavException( 500, e );
1252 public void setServletAuth( ServletAuthenticator servletAuth )
1254 this.servletAuth = servletAuth;
1257 public void setHttpAuth( HttpAuthenticator httpAuth )
1259 this.httpAuth = httpAuth;
1262 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1264 this.scheduler = scheduler;
1267 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1269 this.archivaConfiguration = archivaConfiguration;
1272 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1274 this.repositoryFactory = repositoryFactory;
1277 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1279 this.repositoryRequest = repositoryRequest;
1282 public void setConnectors( RepositoryProxyConnectors connectors )
1284 this.connectors = connectors;
1287 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1289 return remoteRepositoryAdmin;
1292 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1294 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1297 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1299 return managedRepositoryAdmin;
1302 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1304 this.managedRepositoryAdmin = managedRepositoryAdmin;