1 package org.apache.maven.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
23 import java.io.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
31 import javax.servlet.http.HttpServletResponse;
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.jackrabbit.webdav.DavException;
35 import org.apache.jackrabbit.webdav.DavResource;
36 import org.apache.jackrabbit.webdav.DavResourceFactory;
37 import org.apache.jackrabbit.webdav.DavResourceLocator;
38 import org.apache.jackrabbit.webdav.DavServletRequest;
39 import org.apache.jackrabbit.webdav.DavServletResponse;
40 import org.apache.jackrabbit.webdav.DavSession;
41 import org.apache.jackrabbit.webdav.lock.LockManager;
42 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
43 import org.apache.maven.archiva.common.utils.PathUtil;
44 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
45 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
46 import org.apache.maven.archiva.model.ArtifactReference;
47 import org.apache.maven.archiva.model.ProjectReference;
48 import org.apache.maven.archiva.model.VersionedReference;
49 import org.apache.maven.archiva.policies.ProxyDownloadException;
50 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
51 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
52 import org.apache.maven.archiva.repository.RepositoryContentFactory;
53 import org.apache.maven.archiva.repository.RepositoryException;
54 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
55 import org.apache.maven.archiva.repository.audit.AuditEvent;
56 import org.apache.maven.archiva.repository.audit.AuditListener;
57 import org.apache.maven.archiva.repository.audit.Auditable;
58 import org.apache.maven.archiva.repository.content.RepositoryRequest;
59 import org.apache.maven.archiva.repository.layout.LayoutException;
60 import org.apache.maven.archiva.repository.metadata.MetadataTools;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
62 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
63 import org.apache.maven.archiva.security.ArchivaXworkUser;
64 import org.apache.maven.archiva.security.ServletAuthenticator;
65 import org.apache.maven.archiva.webdav.util.MimeTypes;
66 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
67 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.Relocation;
71 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
72 import org.codehaus.plexus.redback.authentication.AuthenticationException;
73 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
74 import org.codehaus.plexus.redback.authorization.AuthorizationException;
75 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
76 import org.codehaus.plexus.redback.policy.AccountLockedException;
77 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
78 import org.codehaus.plexus.redback.system.SecuritySession;
79 import org.codehaus.plexus.redback.system.SecuritySystemConstants;
80 import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
81 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
85 import com.opensymphony.xwork.ActionContext;
88 * @author <a href="mailto:james@atlassian.com">James William Dumay</a>
89 * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
91 public class ArchivaDavResourceFactory
92 implements DavResourceFactory, Auditable
94 private static final String PROXIED_SUFFIX = " (proxied)";
96 private static final String HTTP_PUT_METHOD = "PUT";
98 private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
101 * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
103 private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
106 * @plexus.requirement
108 private RepositoryContentFactory repositoryFactory;
111 * @plexus.requirement
113 private RepositoryRequest repositoryRequest;
116 * @plexus.requirement role-hint="default"
118 private RepositoryProxyConnectors connectors;
121 * @plexus.requirement
123 private MetadataTools metadataTools;
126 * @plexus.requirement
128 private MimeTypes mimeTypes;
131 * @plexus.requirement
133 private ArchivaConfiguration archivaConfiguration;
136 * @plexus.requirement
138 private ServletAuthenticator servletAuth;
141 * @plexus.requirement role-hint="basic"
143 private HttpAuthenticator httpAuth;
147 * Lock Manager - use simple implementation from JackRabbit
149 private final LockManager lockManager = new SimpleLockManager();
151 /** @plexus.requirement */
152 private RepositoryContentConsumers consumers;
154 public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
155 final DavServletResponse response )
158 checkLocatorIsInstanceOfRepositoryLocator( locator );
159 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
161 RepositoryGroupConfiguration repoGroupConfig =
162 archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
163 List<String> repositories = new ArrayList<String>();
165 boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
166 boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
168 if ( repoGroupConfig != null )
170 if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
172 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
173 "Write method not allowed for repository groups." );
175 repositories.addAll( repoGroupConfig.getRepositories() );
177 // handle browse requests for virtual repos
178 if ( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ).endsWith( "/" ) )
180 return getResource( request, repositories, archivaLocator );
185 repositories.add( archivaLocator.getRepositoryId() );
188 //MRM-419 - Windows Webdav support. Should not 404 if there is no content.
189 if (StringUtils.isEmpty(archivaLocator.getRepositoryId()))
191 throw new DavException(HttpServletResponse.SC_NO_CONTENT);
194 List<DavResource> availableResources = new ArrayList<DavResource>();
195 DavException e = null;
197 for ( String repositoryId : repositories )
199 ManagedRepositoryContent managedRepository = null;
203 managedRepository = getManagedRepository( repositoryId );
205 catch ( DavException de )
207 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
208 repositoryId + ">" );
211 DavResource resource = null;
212 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
214 if ( managedRepository != null )
218 if( isAuthorized( request, repositoryId ) )
220 LogicalResource logicalResource =
221 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
225 resource = doGet( managedRepository, request, archivaLocator, logicalResource );
230 resource = doPut( managedRepository, request, archivaLocator, logicalResource );
234 catch ( DavException de )
240 if( resource == null )
242 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
246 availableResources.add( resource );
251 e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Repository does not exist" );
256 if (availableResources.isEmpty())
261 if ( request.getRequestURI().endsWith( "metadata.xml" ) )
263 // TODO MRM-872 : must merge all available metadatas
266 DavResource resource = availableResources.get( 0 );
267 setHeaders(response, locator, resource );
269 // compatibility with MRM-440 to ensure browsing the repository works ok
270 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
272 throw new BrowserRedirectException( resource.getHref() );
274 resource.addLockManager(lockManager);
278 public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
281 checkLocatorIsInstanceOfRepositoryLocator( locator );
282 ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
284 DavResource resource = null;
285 if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
287 ManagedRepositoryContent managedRepository = getManagedRepository( archivaLocator.getRepositoryId() );
288 String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
289 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
291 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource,
292 managedRepository.getRepository(), davSession, archivaLocator, this, mimeTypes,
293 auditListeners, consumers );
295 resource.addLockManager(lockManager);
299 private DavResource doGet( ManagedRepositoryContent managedRepository, DavServletRequest request,
300 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
303 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
304 ArchivaDavResource resource =
305 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
306 managedRepository.getRepository(), request.getRemoteAddr(),
307 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
309 if ( !resource.isCollection() )
311 boolean previouslyExisted = resourceFile.exists();
313 // At this point the incoming request can either be in default or
314 // legacy layout format.
315 boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
319 // Perform an adjustment of the resource to the managed
320 // repository expected path.
321 String localResourcePath =
322 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
323 resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
325 catch ( LayoutException e )
327 if ( previouslyExisted )
331 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
334 // Attempt to fetch the resource from any defined proxy.
337 String repositoryId = locator.getRepositoryId();
338 String event = ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE ) + PROXIED_SUFFIX;
339 triggerAuditEvent( request.getRemoteAddr(), repositoryId, logicalResource.getPath(), event );
342 if ( !resourceFile.exists() )
349 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
350 managedRepository.getRepository(), request.getRemoteAddr(),
351 request.getDavSession(), locator, this, mimeTypes, auditListeners,
358 private DavResource doPut( ManagedRepositoryContent managedRepository, DavServletRequest request,
359 ArchivaDavResourceLocator locator, LogicalResource logicalResource )
363 * Create parent directories that don't exist when writing a file This actually makes this implementation not
364 * compliant to the WebDAV RFC - but we have enough knowledge about how the collection is being used to do this
365 * reasonably and some versions of Maven's WebDAV don't correctly create the collections themselves.
368 File rootDirectory = new File( managedRepository.getRepoRoot() );
369 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
370 if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
373 String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
374 triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
377 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
379 return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
380 managedRepository.getRepository(), request.getRemoteAddr(),
381 request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers );
384 private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
385 LogicalResource resource )
388 if ( repositoryRequest.isSupportFile( resource.getPath() ) )
390 // Checksums are fetched with artifact / metadata.
392 // Need to adjust the path for the checksum resource.
396 // Is it a Metadata resource?
397 if ( repositoryRequest.isDefault( resource.getPath() ) && repositoryRequest.isMetadata( resource.getPath() ) )
399 return fetchMetadataFromProxies( managedRepository, request, resource );
402 // Not any of the above? Then it's gotta be an artifact reference.
405 // Get the artifact reference in a layout neutral way.
406 ArtifactReference artifact = repositoryRequest.toArtifactReference( resource.getPath() );
408 if ( artifact != null )
410 applyServerSideRelocation( managedRepository, artifact );
412 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
414 resource.setPath( managedRepository.toPath( artifact ) );
416 return ( proxiedFile != null );
419 catch ( LayoutException e )
423 catch ( ProxyDownloadException e )
425 log.error( e.getMessage(), e );
426 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
431 private boolean fetchMetadataFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
432 LogicalResource resource )
435 ProjectReference project;
436 VersionedReference versioned;
441 versioned = metadataTools.toVersionedReference( resource.getPath() );
442 if ( versioned != null )
444 connectors.fetchFromProxies( managedRepository, versioned );
448 catch ( RepositoryMetadataException e )
455 project = metadataTools.toProjectReference( resource.getPath() );
456 if ( project != null )
458 connectors.fetchFromProxies( managedRepository, project );
462 catch ( RepositoryMetadataException e )
471 * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
472 * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
475 * For such clients, archiva does server-side relocation by reading itself the <relocation> element in
476 * metadatas and serving the expected artifact.
478 protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
479 throws ProxyDownloadException
481 if ( "pom".equals( artifact.getType() ) )
486 // Build the artifact POM reference
487 ArtifactReference pomReference = new ArtifactReference();
488 pomReference.setGroupId( artifact.getGroupId() );
489 pomReference.setArtifactId( artifact.getArtifactId() );
490 pomReference.setVersion( artifact.getVersion() );
491 pomReference.setType( "pom" );
493 // Get the artifact POM from proxied repositories if needed
494 connectors.fetchFromProxies( managedRepository, pomReference );
496 // Open and read the POM from the managed repo
497 File pom = managedRepository.toFile( pomReference );
506 Model model = new MavenXpp3Reader().read( new FileReader( pom ) );
507 DistributionManagement dist = model.getDistributionManagement();
510 Relocation relocation = dist.getRelocation();
511 if ( relocation != null )
513 // artifact is relocated : update the repositoryPath
514 if ( relocation.getGroupId() != null )
516 artifact.setGroupId( relocation.getGroupId() );
518 if ( relocation.getArtifactId() != null )
520 artifact.setArtifactId( relocation.getArtifactId() );
522 if ( relocation.getVersion() != null )
524 artifact.setVersion( relocation.getVersion() );
529 catch ( FileNotFoundException e )
531 // Artifact has no POM in repo : ignore
533 catch ( IOException e )
535 // Unable to read POM : ignore.
537 catch ( XmlPullParserException e )
539 // Invalid POM : ignore
544 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
546 String activePrincipal = ArchivaXworkUser.getActivePrincipal( ActionContext.getContext().getSession() );
547 AuditEvent event = new AuditEvent( repositoryId, activePrincipal, resource, action );
548 event.setRemoteIP( remoteIP );
550 for ( AuditListener listener : auditListeners )
552 listener.auditEvent( event );
556 public void addAuditListener( AuditListener listener )
558 this.auditListeners.add( listener );
561 public void clearAuditListeners()
563 this.auditListeners.clear();
566 public void removeAuditListener( AuditListener listener )
568 this.auditListeners.remove( listener );
571 private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
573 // [MRM-503] - Metadata file need Pragma:no-cache response
575 if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
577 response.addHeader( "Pragma", "no-cache" );
578 response.addHeader( "Cache-Control", "no-cache" );
581 //We need to specify this so connecting wagons can work correctly
582 response.addDateHeader("last-modified", resource.getModificationTime());
584 // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
587 private ManagedRepositoryContent getManagedRepository( String respositoryId )
590 if ( respositoryId != null )
594 return repositoryFactory.getManagedRepositoryContent( respositoryId );
596 catch ( RepositoryNotFoundException e )
598 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
600 catch ( RepositoryException e )
602 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
608 private void checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
611 if ( !( locator instanceof RepositoryLocator ) )
613 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
614 "Locator does not implement RepositoryLocator" );
618 class LogicalResource
622 public LogicalResource( String path )
627 public String getPath()
632 public void setPath( String path )
638 protected boolean isAuthorized( DavServletRequest request, String repositoryId )
643 AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
644 SecuritySession securitySession = httpAuth.getSecuritySession();
646 return servletAuth.isAuthenticated( request, result ) &&
647 servletAuth.isAuthorized( request, securitySession, repositoryId,
648 WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
650 catch ( AuthenticationException e )
652 throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
654 catch ( MustChangePasswordException e )
656 throw new UnauthorizedDavException( repositoryId, "You must change your password." );
658 catch ( AccountLockedException e )
660 throw new UnauthorizedDavException( repositoryId, "User account is locked." );
662 catch ( AuthorizationException e )
664 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
665 "Fatal Authorization Subsystem Error." );
667 catch ( UnauthorizedException e )
669 throw new UnauthorizedDavException( repositoryId, e.getMessage() );
673 private DavResource getResource( DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator )
676 List<File> mergedRepositoryContents = new ArrayList<File>();
677 LogicalResource logicalResource =
678 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
681 // if the current user logged in has permission to any of the repositories, allow user to
682 // browse the repo group but displaying only the repositories which the user has permission to access.
683 // otherwise, prompt for authentication.
685 // put the current session in the session map which will be passed to ArchivaXworkUser
686 Map<String, Object> sessionMap = new HashMap<String, Object>();
687 if( request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) != null )
689 sessionMap.put( SecuritySystemConstants.SECURITY_SESSION_KEY,
690 request.getSession().getAttribute( SecuritySystemConstants.SECURITY_SESSION_KEY ) );
693 String activePrincipal = ArchivaXworkUser.getActivePrincipal( sessionMap );
694 boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
698 for( String repository : repositories )
700 // for prompted authentication
701 if( httpAuth.getSecuritySession() != null )
705 if( isAuthorized( request, repository ) )
707 getResource( locator, mergedRepositoryContents, logicalResource, repository );
710 catch ( DavException e )
717 // for the current user logged in
720 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
722 getResource( locator, mergedRepositoryContents, logicalResource, repository );
725 catch ( UnauthorizedException e )
734 throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
737 ArchivaVirtualDavResource resource =
738 new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this );
740 // compatibility with MRM-440 to ensure browsing the repository group works ok
741 if ( resource.isCollection() && !request.getRequestURI().endsWith("/" ) )
743 throw new BrowserRedirectException( resource.getHref() );
749 private void getResource( ArchivaDavResourceLocator locator, List<File> mergedRepositoryContents,
750 LogicalResource logicalResource, String repository )
753 ManagedRepositoryContent managedRepository = null;
757 managedRepository = getManagedRepository( repository );
759 catch ( DavException de )
761 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid managed repository <" +
765 if ( !locator.getResourcePath().startsWith( ArchivaVirtualDavResource.HIDDEN_PATH_PREFIX ) )
767 if( managedRepository != null )
769 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
770 if( resourceFile.exists() )
772 mergedRepositoryContents.add( resourceFile );
779 * Check if the current user is authorized to access any of the repos
782 * @param repositories
783 * @param activePrincipal
786 private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
788 boolean allow = false;
791 // if securitySession != null, it means that the user was prompted for authentication
792 if( httpAuth.getSecuritySession() != null )
794 for( String repository : repositories )
798 if( isAuthorized( request, repository ) )
804 catch( DavException e )
812 for( String repository : repositories )
816 if( servletAuth.isAuthorizedToAccessVirtualRepository( activePrincipal, repository ) )
822 catch ( UnauthorizedException e )