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.filelock.FileLockManager;
31 import org.apache.archiva.common.plexusbridge.PlexusSisuBridge;
32 import org.apache.archiva.common.plexusbridge.PlexusSisuBridgeException;
33 import org.apache.archiva.common.utils.PathUtil;
34 import org.apache.archiva.common.utils.VersionUtil;
35 import org.apache.archiva.configuration.ArchivaConfiguration;
36 import org.apache.archiva.configuration.RepositoryGroupConfiguration;
37 import org.apache.archiva.indexer.merger.IndexMerger;
38 import org.apache.archiva.indexer.merger.IndexMergerException;
39 import org.apache.archiva.indexer.merger.IndexMergerRequest;
40 import org.apache.archiva.indexer.merger.TemporaryGroupIndex;
41 import org.apache.archiva.indexer.search.RepositorySearch;
42 import org.apache.archiva.maven2.metadata.MavenMetadataReader;
43 import org.apache.archiva.metadata.repository.storage.RelocationException;
44 import org.apache.archiva.metadata.repository.storage.RepositoryStorage;
45 import org.apache.archiva.model.ArchivaRepositoryMetadata;
46 import org.apache.archiva.model.ArtifactReference;
47 import org.apache.archiva.policies.ProxyDownloadException;
48 import org.apache.archiva.proxy.model.RepositoryProxyConnectors;
49 import org.apache.archiva.redback.authentication.AuthenticationException;
50 import org.apache.archiva.redback.authentication.AuthenticationResult;
51 import org.apache.archiva.redback.authorization.AuthorizationException;
52 import org.apache.archiva.redback.authorization.UnauthorizedException;
53 import org.apache.archiva.redback.integration.filter.authentication.HttpAuthenticator;
54 import org.apache.archiva.redback.policy.AccountLockedException;
55 import org.apache.archiva.redback.policy.MustChangePasswordException;
56 import org.apache.archiva.redback.system.SecuritySession;
57 import org.apache.archiva.redback.users.User;
58 import org.apache.archiva.redback.users.UserManager;
59 import org.apache.archiva.repository.ManagedRepositoryContent;
60 import org.apache.archiva.repository.RepositoryContentFactory;
61 import org.apache.archiva.repository.RepositoryException;
62 import org.apache.archiva.repository.RepositoryNotFoundException;
63 import org.apache.archiva.repository.content.legacy.LegacyPathParser;
64 import org.apache.archiva.repository.content.maven2.RepositoryRequest;
65 import org.apache.archiva.repository.layout.LayoutException;
66 import org.apache.archiva.repository.metadata.MetadataTools;
67 import org.apache.archiva.repository.metadata.RepositoryMetadataException;
68 import org.apache.archiva.repository.metadata.RepositoryMetadataMerge;
69 import org.apache.archiva.repository.metadata.RepositoryMetadataWriter;
70 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
71 import org.apache.archiva.security.ServletAuthenticator;
72 import org.apache.archiva.webdav.util.MimeTypes;
73 import org.apache.archiva.webdav.util.RepositoryPathUtil;
74 import org.apache.archiva.webdav.util.TemporaryGroupIndexSessionCleaner;
75 import org.apache.archiva.webdav.util.WebdavMethodUtil;
76 import org.apache.archiva.xml.XMLException;
77 import org.apache.commons.io.FileUtils;
78 import org.apache.commons.io.FilenameUtils;
79 import org.apache.commons.lang.StringUtils;
80 import org.apache.commons.lang.SystemUtils;
81 import org.apache.jackrabbit.webdav.DavException;
82 import org.apache.jackrabbit.webdav.DavResource;
83 import org.apache.jackrabbit.webdav.DavResourceFactory;
84 import org.apache.jackrabbit.webdav.DavResourceLocator;
85 import org.apache.jackrabbit.webdav.DavServletRequest;
86 import org.apache.jackrabbit.webdav.DavServletResponse;
87 import org.apache.jackrabbit.webdav.DavSession;
88 import org.apache.jackrabbit.webdav.lock.LockManager;
89 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
90 import org.apache.maven.index.context.IndexingContext;
91 import org.codehaus.plexus.digest.ChecksumFile;
92 import org.codehaus.plexus.digest.Digester;
93 import org.codehaus.plexus.digest.DigesterException;
94 import org.slf4j.Logger;
95 import org.slf4j.LoggerFactory;
96 import org.slf4j.MarkerFactory;
97 import org.springframework.context.ApplicationContext;
98 import org.springframework.stereotype.Service;
100 import javax.annotation.PostConstruct;
101 import javax.inject.Inject;
102 import javax.inject.Named;
103 import javax.servlet.http.HttpServletResponse;
104 import javax.servlet.http.HttpSession;
106 import java.io.IOException;
107 import java.util.ArrayList;
108 import java.util.Date;
109 import java.util.HashMap;
110 import java.util.HashSet;
111 import java.util.List;
112 import java.util.Map;
113 import java.util.Set;
118 @Service( "davResourceFactory#archiva" )
119 public class ArchivaDavResourceFactory
120 implements DavResourceFactory, Auditable
122 private static final String PROXIED_SUFFIX = " (proxied)";
124 private static final String HTTP_PUT_METHOD = "PUT";
126 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
129 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
132 private RepositoryContentFactory repositoryFactory;
134 private RepositoryRequest repositoryRequest;
137 @Named( value = "repositoryProxyConnectors#default" )
138 private RepositoryProxyConnectors connectors;
141 private MetadataTools metadataTools;
144 private MimeTypes mimeTypes;
146 private ArchivaConfiguration archivaConfiguration;
149 private ServletAuthenticator servletAuth;
152 @Named( value = "httpAuthenticator#basic" )
153 private HttpAuthenticator httpAuth;
156 private RemoteRepositoryAdmin remoteRepositoryAdmin;
159 private ManagedRepositoryAdmin managedRepositoryAdmin;
162 private IndexMerger indexMerger;
165 private RepositorySearch repositorySearch;
168 * Lock Manager - use simple implementation from JackRabbit
170 private final LockManager lockManager = new SimpleLockManager();
172 private ChecksumFile checksum;
174 private Digester digestSha1;
176 private Digester digestMd5;
179 @Named( value = "archivaTaskScheduler#repository" )
180 private RepositoryArchivaTaskScheduler scheduler;
183 @Named(value= "fileLockManager#default")
184 private FileLockManager fileLockManager;
186 private ApplicationContext applicationContext;
189 public ArchivaDavResourceFactory( ApplicationContext applicationContext, PlexusSisuBridge plexusSisuBridge,
190 ArchivaConfiguration archivaConfiguration )
191 throws PlexusSisuBridgeException
193 this.archivaConfiguration = archivaConfiguration;
194 this.applicationContext = applicationContext;
195 this.checksum = plexusSisuBridge.lookup( ChecksumFile.class );
197 this.digestMd5 = plexusSisuBridge.lookup( Digester.class, "md5" );
198 this.digestSha1 = plexusSisuBridge.lookup( Digester.class, "sha1" );
200 // TODO remove this hard dependency on maven !!
201 repositoryRequest = new RepositoryRequest( new LegacyPathParser( archivaConfiguration ) );
205 public void initialize()
210 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
211 final DavServletResponse response )
214 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
216 RepositoryGroupConfiguration repoGroupConfig =
217 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
219 String activePrincipal = getActivePrincipal( request );
221 List<String> resourcesInAbsolutePath = new ArrayList<String>();
223 boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
224 DavResource resource;
225 if ( repoGroupConfig != null )
229 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
230 "Write method not allowed for repository groups." );
233 log.debug( "Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal );
235 // handle browse requests for virtual repos
236 if ( getLogicalResource( archivaLocator, null, true ).endsWith( "/" ) )
240 return getResourceFromGroup( request, repoGroupConfig.getRepositories(), archivaLocator,
243 catch ( RepositoryAdminException e )
245 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
250 // make a copy to avoid potential concurrent modifications (eg. by configuration)
251 // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
253 List<String> repositories = new ArrayList<String>( repoGroupConfig.getRepositories() );
254 resource = processRepositoryGroup( request, archivaLocator, repositories, activePrincipal,
255 resourcesInAbsolutePath, repoGroupConfig );
263 RemoteRepository remoteRepository =
264 remoteRepositoryAdmin.getRemoteRepository( archivaLocator.getRepositoryId() );
266 if ( remoteRepository != null )
268 String logicalResource = getLogicalResource( archivaLocator, null, false );
269 IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext( remoteRepository );
270 File resourceFile = StringUtils.equals( logicalResource, "/" )
271 ? new File( indexingContext.getIndexDirectoryFile().getParent() )
272 : new File( indexingContext.getIndexDirectoryFile().getParent(), logicalResource );
273 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), locator.getResourcePath(), null,
274 request.getRemoteAddr(), activePrincipal,
275 request.getDavSession(), archivaLocator, this, mimeTypes,
276 auditListeners, scheduler, fileLockManager );
277 setHeaders( response, locator, resource );
281 catch ( RepositoryAdminException e )
283 log.debug( "RepositoryException remote repository with d'{}' not found, msg: {}",
284 archivaLocator.getRepositoryId(), e.getMessage() );
287 ManagedRepositoryContent managedRepositoryContent = null;
291 managedRepositoryContent =
292 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
294 catch ( RepositoryNotFoundException e )
296 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
297 "Invalid repository: " + archivaLocator.getRepositoryId() );
299 catch ( RepositoryException e )
301 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
304 log.debug( "Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(), activePrincipal );
308 resource = processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
309 managedRepositoryAdmin.getManagedRepository(
310 archivaLocator.getRepositoryId() ) );
312 String logicalResource = getLogicalResource( archivaLocator, null, false );
313 resourcesInAbsolutePath.add(
314 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
317 catch ( RepositoryAdminException e )
319 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
323 String requestedResource = request.getRequestURI();
325 // MRM-872 : merge all available metadata
326 // merge metadata only when requested via the repo group
327 if ( ( repositoryRequest.isMetadata( requestedResource ) || repositoryRequest.isMetadataSupportFile(
328 requestedResource ) ) && repoGroupConfig != null )
330 // this should only be at the project level not version level!
331 if ( isProjectReference( requestedResource ) )
334 ArchivaDavResource res = (ArchivaDavResource) resource;
336 StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ),
338 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
340 // for MRM-872 handle checksums of the merged metadata files
341 if ( repositoryRequest.isSupportFile( requestedResource ) )
343 File metadataChecksum =
344 new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
345 if ( metadataChecksum.exists() )
347 LogicalResource logicalResource =
348 new LogicalResource (getLogicalResource( archivaLocator, null, false ) );
351 new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(), null,
352 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
353 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
358 if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
360 // merge the metadata of all repos under group
361 ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
362 for ( String resourceAbsPath : resourcesInAbsolutePath )
366 File metadataFile = new File( resourceAbsPath );
367 ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read( metadataFile );
368 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
370 catch ( XMLException e )
372 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
373 "Error occurred while reading metadata file." );
375 catch ( RepositoryMetadataException r )
377 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
378 "Error occurred while merging metadata file." );
384 File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
386 LogicalResource logicalResource = new LogicalResource( getLogicalResource( archivaLocator, null, false ) );
389 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(), null,
390 request.getRemoteAddr(), activePrincipal,
391 request.getDavSession(), archivaLocator, this, mimeTypes,
392 auditListeners, scheduler, fileLockManager );
394 catch ( RepositoryMetadataException r )
396 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
397 "Error occurred while writing metadata file." );
399 catch ( IOException ie )
401 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
402 "Error occurred while generating checksum files." );
404 catch ( DigesterException de )
406 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
407 "Error occurred while generating checksum files." + de.getMessage() );
414 setHeaders( response, locator, resource );
416 // compatibility with MRM-440 to ensure browsing the repository works ok
417 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
419 throw new BrowserRedirectException( resource.getHref() );
421 resource.addLockManager( lockManager );
425 private DavResource processRepositoryGroup( final DavServletRequest request,
426 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
427 String activePrincipal, List<String> resourcesInAbsolutePath,
428 RepositoryGroupConfiguration repoGroupConfig )
431 DavResource resource = null;
432 List<DavException> storedExceptions = new ArrayList<DavException>();
434 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
436 String rootPath = StringUtils.substringBeforeLast( pathInfo, "/" );
438 if ( StringUtils.endsWith( rootPath, repoGroupConfig.getMergedIndexPath() ) )
440 // we are in the case of index file request
441 String requestedFileName = StringUtils.substringAfterLast( pathInfo, "/" );
442 File temporaryIndexDirectory =
443 buildMergedIndexDirectory( repositories, activePrincipal, request, repoGroupConfig );
445 File resourceFile = new File( temporaryIndexDirectory, requestedFileName );
446 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), requestedFileName, null,
447 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
448 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
453 for ( String repositoryId : repositories )
455 ManagedRepositoryContent managedRepositoryContent;
458 managedRepositoryContent = repositoryFactory.getManagedRepositoryContent( repositoryId );
460 catch ( RepositoryNotFoundException e )
462 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
464 catch ( RepositoryException e )
466 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
471 ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository( repositoryId );
472 DavResource updatedResource =
473 processRepository( request, archivaLocator, activePrincipal, managedRepositoryContent,
475 if ( resource == null )
477 resource = updatedResource;
480 String logicalResource = getLogicalResource( archivaLocator, null, false );
481 if ( logicalResource.endsWith( "/" ) )
483 logicalResource = logicalResource.substring( 1 );
485 resourcesInAbsolutePath.add(
486 new File( managedRepositoryContent.getRepoRoot(), logicalResource ).getAbsolutePath() );
488 catch ( DavException e )
490 storedExceptions.add( e );
492 catch ( RepositoryAdminException e )
494 storedExceptions.add( new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e ) );
498 if ( resource == null )
500 if ( !storedExceptions.isEmpty() )
503 for ( DavException e : storedExceptions )
505 if ( 401 == e.getErrorCode() )
511 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
515 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
521 private String getLogicalResource( ArchivaDavResourceLocator archivaLocator, ManagedRepository managedRepository,
522 boolean useOrigResourcePath )
524 // FIXME remove this hack
525 // but currently managedRepository can be null in case of group
526 String layout = managedRepository == null ? new ManagedRepository( ).getLayout() : managedRepository.getLayout();
527 RepositoryStorage repositoryStorage =
528 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
529 String path = repositoryStorage.getFilePath(
530 useOrigResourcePath ? archivaLocator.getOrigResourcePath() : archivaLocator.getResourcePath(), managedRepository );
531 log.debug( "found path {} for resourcePath: '{}' with managedRepo '{}' and layout '{}'", path,
532 archivaLocator.getResourcePath(), managedRepository == null ? "null" : managedRepository.getId(), layout );
536 private String evaluatePathWithVersion( ArchivaDavResourceLocator archivaLocator, ManagedRepositoryContent managedRepositoryContent, String contextPath )
539 String layout = managedRepositoryContent.getRepository() == null ? new ManagedRepository( ).getLayout() : managedRepositoryContent.getRepository().getLayout();
540 RepositoryStorage repositoryStorage =
541 this.applicationContext.getBean( "repositoryStorage#" + layout, RepositoryStorage.class );
544 return repositoryStorage.getFilePathWithVersion( archivaLocator.getResourcePath(), managedRepositoryContent );
546 catch ( RelocationException e )
548 String path = e.getPath();
549 log.debug( "Relocation to {}", path );
551 throw new BrowserRedirectException(contextPath + ( StringUtils.startsWith( path, "/" ) ? "": "/" ) + path, e.getRelocationType() );
553 catch ( XMLException e )
555 log.error( e.getMessage(), e );
556 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
560 private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
561 String activePrincipal, ManagedRepositoryContent managedRepositoryContent,
562 ManagedRepository managedRepository )
565 DavResource resource = null;
566 if ( isAuthorized( request, managedRepositoryContent.getId() ) )
568 // Maven Centric part ask evaluation if -SNAPSHOT
569 String path = evaluatePathWithVersion(archivaLocator, managedRepositoryContent, request.getContextPath());
570 if ( path.startsWith( "/" ) )
572 path = path.substring( 1 );
574 LogicalResource logicalResource = new LogicalResource( path );
575 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), path );
577 new ArchivaDavResource( resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(),
578 request.getRemoteAddr(), activePrincipal, request.getDavSession(),
579 archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager );
581 if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
583 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
585 // force a resource not found
586 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
590 if ( !resource.isCollection() )
592 boolean previouslyExisted = resourceFile.exists();
594 // Attempt to fetch the resource from any defined proxy.
596 fetchContentFromProxies( managedRepositoryContent, request, logicalResource );
598 // At this point the incoming request can either be in default or
599 // legacy layout format.
602 // Perform an adjustment of the resource to the managed
603 // repository expected path.
604 String localResourcePath =
605 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepositoryContent );
606 resourceFile = new File( managedRepositoryContent.getRepoRoot(), localResourcePath );
608 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
609 managedRepositoryContent.getRepository(),
610 request.getRemoteAddr(), activePrincipal,
611 request.getDavSession(), archivaLocator, this, mimeTypes,
612 auditListeners, scheduler, fileLockManager );
614 catch ( LayoutException e )
616 if ( !resourceFile.exists() )
618 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
624 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
627 log.debug( "Proxied artifact '{}' in repository '{}' (current user '{}')",
628 resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal );
630 triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
631 logicalResource.getPath(), event, activePrincipal );
634 if ( !resourceFile.exists() )
636 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
642 if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
644 String resourcePath = logicalResource.getPath();
646 // check if target repo is enabled for releases
647 // we suppose that release-artifacts can be deployed only to repos enabled for releases
648 if ( managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(
649 resourcePath ) && !repositoryRequest.isSupportFile( resourcePath ) )
651 ArtifactReference artifact = null;
654 artifact = managedRepositoryContent.toArtifactReference( resourcePath );
656 if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
658 // check if artifact already exists and if artifact re-deployment to the repository is allowed
659 if ( managedRepositoryContent.hasContent( artifact )
660 && managedRepositoryContent.getRepository().isBlockRedeployments() )
662 log.warn( "Overwriting released artifacts in repository '{}' is not allowed.",
663 managedRepositoryContent.getId() );
664 throw new DavException( HttpServletResponse.SC_CONFLICT,
665 "Overwriting released artifacts is not allowed." );
669 catch ( LayoutException e )
671 log.warn( "Artifact path '{}' is invalid.", resourcePath );
676 * Create parent directories that don't exist when writing a file This actually makes this
677 * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
678 * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
679 * create the collections themselves.
682 File rootDirectory = new File( managedRepositoryContent.getRepoRoot() );
683 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
685 if ( !destDir.exists() )
688 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
690 log.debug( "Creating destination directory '{}' (current user '{}')", destDir.getName(),
693 triggerAuditEvent( request.getRemoteAddr(), managedRepositoryContent.getId(), relPath,
694 AuditEvent.CREATE_DIR, activePrincipal );
701 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
704 ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
706 ManagedRepositoryContent managedRepositoryContent;
709 managedRepositoryContent =
710 repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
712 catch ( RepositoryNotFoundException e )
714 throw new DavException( HttpServletResponse.SC_NOT_FOUND,
715 "Invalid repository: " + archivaLocator.getRepositoryId() );
717 catch ( RepositoryException e )
719 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
722 DavResource resource = null;
725 String logicalResource = getLogicalResource( archivaLocator, managedRepositoryAdmin.getManagedRepository(
726 archivaLocator.getRepositoryId() ), false );
727 if ( logicalResource.startsWith( "/" ) )
729 logicalResource = logicalResource.substring( 1 );
731 File resourceFile = new File( managedRepositoryContent.getRepoRoot(), logicalResource );
732 resource = new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
733 managedRepositoryContent.getRepository(), davSession, archivaLocator,
734 this, mimeTypes, auditListeners, scheduler, fileLockManager );
736 resource.addLockManager( lockManager );
738 catch ( RepositoryAdminException e )
740 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
745 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
746 LogicalResource resource )
749 String path = resource.getPath();
750 if ( repositoryRequest.isSupportFile( path ) )
752 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
754 return ( proxiedFile != null );
757 // Is it a Metadata resource?
758 if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
760 return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
763 // Is it an Archetype Catalog?
764 if ( repositoryRequest.isArchetypeCatalog( path ) )
766 // FIXME we must implement a merge of remote archetype catalog from remote servers.
767 File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
769 return ( proxiedFile != null );
772 // Not any of the above? Then it's gotta be an artifact reference.
775 // Get the artifact reference in a layout neutral way.
776 ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
778 if ( artifact != null )
780 String repositoryLayout = managedRepository.getRepository().getLayout();
782 RepositoryStorage repositoryStorage =
783 this.applicationContext.getBean( "repositoryStorage#" + repositoryLayout, RepositoryStorage.class );
784 repositoryStorage.applyServerSideRelocation( managedRepository, artifact );
786 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
788 resource.setPath( managedRepository.toPath( artifact ) );
790 log.debug( "Proxied artifact '{}:{}:{}'", artifact.getGroupId(), artifact.getArtifactId(),
791 artifact.getVersion() );
793 return ( proxiedFile != null );
796 catch ( LayoutException e )
800 catch ( ProxyDownloadException e )
802 log.error( e.getMessage(), e );
803 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
804 "Unable to fetch artifact resource." );
811 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
814 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
815 event.setRemoteIP( remoteIP );
817 for ( AuditListener listener : auditListeners )
819 listener.auditEvent( event );
823 public void addAuditListener( AuditListener listener )
825 this.auditListeners.add( listener );
828 public void clearAuditListeners()
830 this.auditListeners.clear();
833 public void removeAuditListener( AuditListener listener )
835 this.auditListeners.remove( listener );
838 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
840 // [MRM-503] - Metadata file need Pragma:no-cache response
842 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" )
843 || ( (ArchivaDavResource) resource ).getLocalResource().isDirectory() )
845 response.setHeader( "Pragma", "no-cache" );
846 response.setHeader( "Cache-Control", "no-cache" );
847 response.setDateHeader( "Last-Modified", new Date().getTime() );
849 // if the resource is a directory don't cache it as new groupId deployed will be available
850 // without need of refreshing browser
853 // We need to specify this so connecting wagons can work correctly
854 response.setDateHeader( "Last-Modified", resource.getModificationTime() );
856 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
859 private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
862 if ( !( locator instanceof ArchivaDavResourceLocator ) )
864 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
865 "Locator does not implement RepositoryLocator" );
869 if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
871 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
874 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
876 // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
877 if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
879 throw new DavException( HttpServletResponse.SC_NO_CONTENT );
881 return archivaLocator;
884 private static class LogicalResource
888 public LogicalResource( String path )
893 public String getPath()
898 public void setPath( String path )
904 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
909 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
910 SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
912 return servletAuth.isAuthenticated( request, result ) && servletAuth.isAuthorized( request, securitySession,
914 WebdavMethodUtil.getMethodPermission(
915 request.getMethod() ) );
917 catch ( AuthenticationException e )
919 // safety check for MRM-911
920 String guest = UserManager.GUEST_USERNAME;
923 if ( servletAuth.isAuthorized( guest,
924 ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
925 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
930 catch ( UnauthorizedException ae )
932 throw new UnauthorizedDavException( repositoryId,
933 "You are not authenticated and authorized to access any repository." );
936 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
938 catch ( MustChangePasswordException e )
940 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
942 catch ( AccountLockedException e )
944 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
946 catch ( AuthorizationException e )
948 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
949 "Fatal Authorization Subsystem Error." );
951 catch ( UnauthorizedException e )
953 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
957 private DavResource getResourceFromGroup( DavServletRequest request, List<String> repositories,
958 ArchivaDavResourceLocator locator,
959 RepositoryGroupConfiguration repositoryGroupConfiguration )
960 throws DavException, RepositoryAdminException
962 List<File> mergedRepositoryContents = new ArrayList<File>();
963 // multiple repo types so we guess they are all the same type
964 // so use the first one
965 // FIXME add a method with group in the repository storage
966 String firstRepoId = repositoryGroupConfiguration.getRepositories().get( 1 );
968 String path = getLogicalResource( locator, managedRepositoryAdmin.getManagedRepository( firstRepoId ), false );
969 if ( path.startsWith( "/" ) )
971 path = path.substring( 1 );
973 LogicalResource logicalResource = new LogicalResource( path );
976 // if the current user logged in has permission to any of the repositories, allow user to
977 // browse the repo group but displaying only the repositories which the user has permission to access.
978 // otherwise, prompt for authentication.
980 String activePrincipal = getActivePrincipal( request );
982 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
985 String pathInfo = StringUtils.removeEnd( request.getPathInfo(), "/" );
990 if ( StringUtils.endsWith( pathInfo, repositoryGroupConfiguration.getMergedIndexPath() ) )
993 buildMergedIndexDirectory( repositories, activePrincipal, request, repositoryGroupConfiguration );
994 mergedRepositoryContents.add( mergedRepoDir );
998 if ( StringUtils.equalsIgnoreCase( pathInfo, "/" + repositoryGroupConfiguration.getId() ) )
1000 File tmpDirectory = new File( SystemUtils.getJavaIoTmpDir(),
1001 repositoryGroupConfiguration.getId() + "/"
1002 + repositoryGroupConfiguration.getMergedIndexPath() );
1003 if ( !tmpDirectory.exists() )
1005 synchronized ( tmpDirectory.getAbsolutePath() )
1007 if ( !tmpDirectory.exists() )
1009 tmpDirectory.mkdirs();
1013 mergedRepositoryContents.add( tmpDirectory.getParentFile() );
1015 for ( String repository : repositories )
1017 ManagedRepositoryContent managedRepository = null;
1021 managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
1023 catch ( RepositoryNotFoundException e )
1025 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1026 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1028 catch ( RepositoryException e )
1030 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
1031 "Invalid managed repository <" + repository + ">: " + e.getMessage() );
1034 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
1035 if ( resourceFile.exists() )
1037 // in case of group displaying index directory doesn't have sense !!
1038 String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
1039 if ( StringUtils.isNotEmpty( repoIndexDirectory ) )
1041 if ( !new File( repoIndexDirectory ).isAbsolute() )
1043 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1044 StringUtils.isEmpty( repoIndexDirectory )
1046 : repoIndexDirectory ).getAbsolutePath();
1049 if ( StringUtils.isEmpty( repoIndexDirectory ) )
1051 repoIndexDirectory = new File( managedRepository.getRepository().getLocation(),
1052 ".indexer" ).getAbsolutePath();
1055 if ( !StringUtils.equals( FilenameUtils.normalize( repoIndexDirectory ),
1056 FilenameUtils.normalize( resourceFile.getAbsolutePath() ) ) )
1058 // for prompted authentication
1059 if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
1063 if ( isAuthorized( request, repository ) )
1065 mergedRepositoryContents.add( resourceFile );
1066 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1069 catch ( DavException e )
1071 // TODO: review exception handling
1073 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1074 activePrincipal, e.getMessage() );
1081 // for the current user logged in
1084 if ( servletAuth.isAuthorized( activePrincipal, repository,
1085 WebdavMethodUtil.getMethodPermission(
1086 request.getMethod() ) ) )
1088 mergedRepositoryContents.add( resourceFile );
1089 log.debug( "Repository '{}' accessed by '{}'", repository, activePrincipal );
1092 catch ( UnauthorizedException e )
1094 // TODO: review exception handling
1096 log.debug( "Skipping repository '{}' for user '{}': {}", managedRepository,
1097 activePrincipal, e.getMessage() );
1108 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
1111 ArchivaVirtualDavResource resource =
1112 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
1115 // compatibility with MRM-440 to ensure browsing the repository group works ok
1116 if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
1118 throw new BrowserRedirectException( resource.getHref() );
1124 protected String getActivePrincipal( DavServletRequest request )
1126 User sessionUser = httpAuth.getSessionUser( request.getSession() );
1127 return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
1131 * Check if the current user is authorized to access any of the repos
1134 * @param repositories
1135 * @param activePrincipal
1138 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
1140 // when no repositories configured it's impossible to browse nothing !
1141 // at least make possible to see nothing :-)
1142 if ( repositories == null || repositories.isEmpty() )
1147 boolean allow = false;
1149 // if securitySession != null, it means that the user was prompted for authentication
1150 if ( httpAuth.getSecuritySession( request.getSession() ) != null )
1152 for ( String repository : repositories )
1156 if ( isAuthorized( request, repository ) )
1162 catch ( DavException e )
1170 for ( String repository : repositories )
1174 if ( servletAuth.isAuthorized( activePrincipal, repository,
1175 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1181 catch ( UnauthorizedException e )
1191 private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
1192 throws RepositoryMetadataException, DigesterException, IOException
1194 File outputFile = new File( outputFilename );
1195 if ( outputFile.exists() )
1197 FileUtils.deleteQuietly( outputFile );
1200 outputFile.getParentFile().mkdirs();
1201 RepositoryMetadataWriter.write( mergedMetadata, outputFile );
1203 createChecksumFile( outputFilename, digestSha1 );
1204 createChecksumFile( outputFilename, digestMd5 );
1209 private void createChecksumFile( String path, Digester digester )
1210 throws DigesterException, IOException
1212 File checksumFile = new File( path + digester.getFilenameExtension() );
1213 if ( !checksumFile.exists() )
1215 FileUtils.deleteQuietly( checksumFile );
1216 checksum.createChecksum( new File( path ), digester );
1218 else if ( !checksumFile.isFile() )
1220 log.error( "Checksum file is not a file." );
1224 private boolean isProjectReference( String requestedResource )
1228 metadataTools.toVersionedReference( requestedResource );
1231 catch ( RepositoryMetadataException re )
1237 protected File buildMergedIndexDirectory( List<String> repositories, String activePrincipal,
1238 DavServletRequest request,
1239 RepositoryGroupConfiguration repositoryGroupConfiguration )
1245 HttpSession session = request.getSession();
1247 Map<String, TemporaryGroupIndex> temporaryGroupIndexMap =
1248 (Map<String, TemporaryGroupIndex>) session.getAttribute(
1249 TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY );
1250 if ( temporaryGroupIndexMap == null )
1252 temporaryGroupIndexMap = new HashMap<String, TemporaryGroupIndex>();
1255 TemporaryGroupIndex tmp = temporaryGroupIndexMap.get( repositoryGroupConfiguration.getId() );
1257 if ( tmp != null && tmp.getDirectory() != null && tmp.getDirectory().exists() )
1259 if ( System.currentTimeMillis() - tmp.getCreationTime() > (
1260 repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000 ) )
1262 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1263 "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId() );
1264 indexMerger.cleanTemporaryGroupIndex( tmp );
1268 log.debug( MarkerFactory.getMarker( "group.merged.index" ),
1269 "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId() );
1270 return tmp.getDirectory();
1274 Set<String> authzRepos = new HashSet<String>();
1275 for ( String repository : repositories )
1279 if ( servletAuth.isAuthorized( activePrincipal, repository,
1280 WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
1282 authzRepos.add( repository );
1283 authzRepos.addAll( this.repositorySearch.getRemoteIndexingContextIds( repository ) );
1286 catch ( UnauthorizedException e )
1288 // TODO: review exception handling
1290 log.debug( "Skipping repository '{}' for user '{}': {}", repository, activePrincipal,
1294 log.info( "generate temporary merged index for repository group '{}' for repositories '{}'",
1295 repositoryGroupConfiguration.getId(), authzRepos );
1296 IndexingContext indexingContext = indexMerger.buildMergedIndex(
1297 new IndexMergerRequest( authzRepos, true, repositoryGroupConfiguration.getId(),
1298 repositoryGroupConfiguration.getMergedIndexPath(),
1299 repositoryGroupConfiguration.getMergedIndexTtl() ) );
1300 File mergedRepoDir = indexingContext.getIndexDirectoryFile();
1301 TemporaryGroupIndex temporaryGroupIndex =
1302 new TemporaryGroupIndex( mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(),
1303 repositoryGroupConfiguration.getMergedIndexTtl() ).setCreationTime(
1304 new Date().getTime() );
1305 temporaryGroupIndexMap.put( repositoryGroupConfiguration.getId(), temporaryGroupIndex );
1306 session.setAttribute( TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY,
1307 temporaryGroupIndexMap );
1308 return mergedRepoDir;
1310 catch ( RepositoryAdminException e )
1312 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1314 catch ( IndexMergerException e )
1316 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
1321 public void setServletAuth( ServletAuthenticator servletAuth )
1323 this.servletAuth = servletAuth;
1326 public void setHttpAuth( HttpAuthenticator httpAuth )
1328 this.httpAuth = httpAuth;
1331 public void setScheduler( RepositoryArchivaTaskScheduler scheduler )
1333 this.scheduler = scheduler;
1336 public void setArchivaConfiguration( ArchivaConfiguration archivaConfiguration )
1338 this.archivaConfiguration = archivaConfiguration;
1341 public void setRepositoryFactory( RepositoryContentFactory repositoryFactory )
1343 this.repositoryFactory = repositoryFactory;
1346 public void setRepositoryRequest( RepositoryRequest repositoryRequest )
1348 this.repositoryRequest = repositoryRequest;
1351 public void setConnectors( RepositoryProxyConnectors connectors )
1353 this.connectors = connectors;
1356 public RemoteRepositoryAdmin getRemoteRepositoryAdmin()
1358 return remoteRepositoryAdmin;
1361 public void setRemoteRepositoryAdmin( RemoteRepositoryAdmin remoteRepositoryAdmin )
1363 this.remoteRepositoryAdmin = remoteRepositoryAdmin;
1366 public ManagedRepositoryAdmin getManagedRepositoryAdmin()
1368 return managedRepositoryAdmin;
1371 public void setManagedRepositoryAdmin( ManagedRepositoryAdmin managedRepositoryAdmin )
1373 this.managedRepositoryAdmin = managedRepositoryAdmin;