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.common.filelock.FileLockException;
23 import org.apache.archiva.common.filelock.FileLockManager;
24 import org.apache.archiva.common.filelock.FileLockTimeoutException;
25 import org.apache.archiva.common.filelock.Lock;
26 import org.apache.archiva.metadata.model.facets.AuditEvent;
27 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
28 import org.apache.archiva.repository.events.AuditListener;
29 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
30 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
31 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
32 import org.apache.archiva.webdav.util.IndexWriter;
33 import org.apache.archiva.webdav.util.MimeTypes;
34 import org.apache.commons.io.FileUtils;
35 import org.apache.commons.io.IOUtils;
36 import org.apache.jackrabbit.util.Text;
37 import org.apache.jackrabbit.webdav.DavException;
38 import org.apache.jackrabbit.webdav.DavResource;
39 import org.apache.jackrabbit.webdav.DavResourceFactory;
40 import org.apache.jackrabbit.webdav.DavResourceIterator;
41 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
42 import org.apache.jackrabbit.webdav.DavResourceLocator;
43 import org.apache.jackrabbit.webdav.DavServletResponse;
44 import org.apache.jackrabbit.webdav.DavSession;
45 import org.apache.jackrabbit.webdav.MultiStatusResponse;
46 import org.apache.jackrabbit.webdav.io.InputContext;
47 import org.apache.jackrabbit.webdav.io.OutputContext;
48 import org.apache.jackrabbit.webdav.lock.ActiveLock;
49 import org.apache.jackrabbit.webdav.lock.LockInfo;
50 import org.apache.jackrabbit.webdav.lock.LockManager;
51 import org.apache.jackrabbit.webdav.lock.Scope;
52 import org.apache.jackrabbit.webdav.lock.Type;
53 import org.apache.jackrabbit.webdav.property.DavProperty;
54 import org.apache.jackrabbit.webdav.property.DavPropertyName;
55 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
56 import org.apache.jackrabbit.webdav.property.DavPropertySet;
57 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
58 import org.apache.jackrabbit.webdav.property.ResourceType;
59 import org.joda.time.DateTime;
60 import org.joda.time.format.DateTimeFormatter;
61 import org.joda.time.format.ISODateTimeFormat;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 import javax.servlet.http.HttpServletResponse;
66 import java.io.IOException;
67 import java.io.InputStream;
68 import java.io.OutputStream;
69 import java.nio.file.Files;
70 import java.nio.file.Path;
71 import java.nio.file.Paths;
72 import java.util.ArrayList;
73 import java.util.List;
74 import java.util.stream.Stream;
78 public class ArchivaDavResource
79 implements DavResource
81 public static final String HIDDEN_PATH_PREFIX = ".";
83 private final ArchivaDavResourceLocator locator;
85 private final DavResourceFactory factory;
87 private final Path localResource;
89 private final String logicalResource;
91 private DavPropertySet properties = null;
93 private LockManager lockManager;
95 private final DavSession session;
97 private String remoteAddr;
99 private final org.apache.archiva.repository.ManagedRepository repository;
101 private final MimeTypes mimeTypes;
103 private List<AuditListener> auditListeners;
105 private String principal;
107 public static final String COMPLIANCE_CLASS = "1, 2";
109 private final ArchivaTaskScheduler scheduler;
111 private final FileLockManager fileLockManager;
113 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
115 public ArchivaDavResource( String localResource, String logicalResource, org.apache.archiva.repository.ManagedRepository repository,
116 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
117 MimeTypes mimeTypes, List<AuditListener> auditListeners,
118 RepositoryArchivaTaskScheduler scheduler, FileLockManager fileLockManager )
120 this.localResource = Paths.get( localResource );
121 this.logicalResource = logicalResource;
122 this.locator = locator;
123 this.factory = factory;
124 this.session = session;
126 // TODO: push into locator as well as moving any references out of the resource factory
127 this.repository = repository;
129 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
130 this.mimeTypes = mimeTypes;
131 this.auditListeners = auditListeners;
132 this.scheduler = scheduler;
133 this.fileLockManager = fileLockManager;
136 public ArchivaDavResource( String localResource, String logicalResource, org.apache.archiva.repository.ManagedRepository repository,
137 String remoteAddr, String principal, DavSession session,
138 ArchivaDavResourceLocator locator, DavResourceFactory factory, MimeTypes mimeTypes,
139 List<AuditListener> auditListeners, RepositoryArchivaTaskScheduler scheduler,
140 FileLockManager fileLockManager )
142 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
143 scheduler, fileLockManager );
145 this.remoteAddr = remoteAddr;
146 this.principal = principal;
150 public String getComplianceClass()
152 return COMPLIANCE_CLASS;
156 public String getSupportedMethods()
162 public boolean exists()
164 return Files.exists(localResource);
168 public boolean isCollection()
170 return Files.isDirectory(localResource);
174 public String getDisplayName()
176 String resPath = getResourcePath();
177 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
181 public DavResourceLocator getLocator()
186 public Path getLocalResource()
188 return localResource;
192 public String getResourcePath()
194 return locator.getResourcePath();
198 public String getHref()
200 return locator.getHref( isCollection() );
204 public long getModificationTime()
208 return Files.getLastModifiedTime(localResource).toMillis();
210 catch ( IOException e )
212 log.error("Could not get modification time of {}: {}", localResource, e.getMessage(), e);
218 public void spool( OutputContext outputContext )
221 if ( !isCollection() )
223 outputContext.setContentLength( Files.size( localResource ) );
224 outputContext.setContentType( mimeTypes.getMimeType( localResource.getFileName().toString() ) );
229 if ( !isCollection() && outputContext.hasStream() )
231 Lock lock = fileLockManager.readFileLock( localResource );
232 try (InputStream is = Files.newInputStream( lock.getFile()))
234 IOUtils.copy( is, outputContext.getOutputStream() );
237 else if ( outputContext.hasStream() )
239 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
240 writer.write( outputContext );
243 catch ( FileLockException e )
245 throw new IOException( e.getMessage(), e );
247 catch ( FileLockTimeoutException e )
249 throw new IOException( e.getMessage(), e );
254 public DavPropertyName[] getPropertyNames()
256 return getProperties().getPropertyNames();
260 public DavProperty getProperty( DavPropertyName name )
262 return getProperties().get( name );
266 public DavPropertySet getProperties()
268 return initProperties();
272 public void setProperty( DavProperty property )
278 public void removeProperty( DavPropertyName propertyName )
283 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
289 @SuppressWarnings("unchecked")
291 public MultiStatusResponse alterProperties( List changeList )
298 public DavResource getCollection()
300 DavResource parent = null;
301 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
303 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
304 if ( parentPath.equals( "" ) )
308 DavResourceLocator parentloc =
309 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
312 parent = factory.createResource( parentloc, session );
314 catch ( DavException e )
323 public void addMember( DavResource resource, InputContext inputContext )
326 Path localFile = localResource.resolve( resource.getDisplayName() );
327 boolean exists = Files.exists(localFile);
329 if ( isCollection() && inputContext.hasStream() ) // New File
331 try (OutputStream stream = Files.newOutputStream( localFile ))
333 IOUtils.copy( inputContext.getInputStream(), stream );
335 catch ( IOException e )
337 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
340 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
341 long expectedContentLength = inputContext.getContentLength();
342 long actualContentLength = 0;
345 actualContentLength = Files.size(localFile);
347 catch ( IOException e )
349 log.error( "Could not get length of file {}: {}", localFile, e.getMessage(), e );
351 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
352 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
354 String msg = "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
355 log.debug( "Upload failed: {}", msg );
357 org.apache.archiva.common.utils.FileUtils.deleteQuietly( localFile );
358 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
361 queueRepositoryTask( localFile );
363 log.debug( "File '{}{}(current user '{}')", resource.getDisplayName(),
364 ( exists ? "' modified " : "' created " ), this.principal );
366 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
368 else if ( !inputContext.hasStream() && isCollection() ) // New directory
372 Files.createDirectories( localFile );
374 catch ( IOException e )
376 log.error("Could not create directory {}: {}", localFile, e.getMessage(), e);
379 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
381 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
385 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
386 + " as this is not a DAV collection";
388 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
393 public DavResourceIterator getMembers()
395 List<DavResource> list = new ArrayList<>();
396 if ( exists() && isCollection() )
398 try ( Stream<Path> stream = Files.list(localResource))
400 stream.forEach ( p ->
402 String item = p.toString();
405 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
407 String path = locator.getResourcePath( ) + '/' + item;
408 DavResourceLocator resourceLocator =
409 locator.getFactory( ).createResourceLocator( locator.getPrefix( ), path );
410 DavResource resource = factory.createResource( resourceLocator, session );
412 if ( resource != null )
414 list.add( resource );
416 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
419 catch ( DavException e )
424 } catch (IOException e) {
425 log.error("Error while listing {}", localResource);
428 return new DavResourceIteratorImpl( list );
432 public void removeMember( DavResource member )
435 Path resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
437 if ( Files.exists(resource) )
441 if ( Files.isDirectory(resource) )
443 org.apache.archiva.common.utils.FileUtils.deleteDirectory( resource );
444 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
448 Files.deleteIfExists( resource );
449 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
452 log.debug( "{}{}' removed (current user '{}')", ( Files.isDirectory(resource) ? "Directory '" : "File '" ),
453 member.getDisplayName(), this.principal );
456 catch ( IOException e )
458 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
463 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
467 private void triggerAuditEvent( DavResource member, String action )
470 String path = logicalResource + "/" + member.getDisplayName();
472 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
473 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, action );
474 auditEvent.setRemoteIP( resource.remoteAddr );
476 for ( AuditListener listener : auditListeners )
478 listener.auditEvent( auditEvent );
483 public void move( DavResource destination )
488 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
493 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
494 if ( isCollection() )
496 FileUtils.moveDirectory( getLocalResource().toFile(), resource.getLocalResource().toFile() );
498 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
502 FileUtils.moveFile( getLocalResource().toFile(), resource.getLocalResource().toFile() );
504 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
507 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
508 getLocalResource().getFileName(), destination, this.principal );
511 catch ( IOException e )
513 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
518 public void copy( DavResource destination, boolean shallow )
523 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
526 if ( shallow && isCollection() )
528 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
533 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
534 if ( isCollection() )
536 FileUtils.copyDirectory( getLocalResource().toFile(), resource.getLocalResource().toFile() );
538 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
542 FileUtils.copyFile( getLocalResource().toFile(), resource.getLocalResource().toFile() );
544 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
547 log.debug( "{}{}' copied to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
548 getLocalResource().getFileName(), destination, this.principal );
551 catch ( IOException e )
553 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
558 public boolean isLockable( Type type, Scope scope )
560 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
564 public boolean hasLock( Type type, Scope scope )
566 return getLock( type, scope ) != null;
570 public ActiveLock getLock( Type type, Scope scope )
572 ActiveLock lock = null;
573 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
575 lock = lockManager.getLock( type, scope, this );
581 public ActiveLock[] getLocks()
583 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
584 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
588 public ActiveLock lock( LockInfo lockInfo )
591 ActiveLock lock = null;
592 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
594 lock = lockManager.createLock( lockInfo, this );
598 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
604 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
609 throw new DavException( DavServletResponse.SC_NOT_FOUND );
611 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
614 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
615 "No lock with the given type/scope present on resource " + getResourcePath() );
618 lock = lockManager.refreshLock( lockInfo, lockToken, this );
624 public void unlock( String lockToken )
627 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
630 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
632 else if ( lock.isLockedByToken( lockToken ) )
634 lockManager.releaseLock( lockToken, this );
638 throw new DavException( DavServletResponse.SC_LOCKED );
643 public void addLockManager( LockManager lockManager )
645 this.lockManager = lockManager;
649 public DavResourceFactory getFactory()
655 public DavSession getSession()
661 * Fill the set of properties
663 protected DavPropertySet initProperties()
667 properties = new DavPropertySet();
670 if ( properties != null )
675 DavPropertySet properties = new DavPropertySet();
677 // set (or reset) fundamental properties
678 if ( getDisplayName() != null )
680 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
682 if ( isCollection() )
684 properties.add( new ResourceType( ResourceType.COLLECTION ) );
685 // Windows XP support
686 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
690 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
692 // Windows XP support
693 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
696 // Need to get the ISO8601 date for properties
700 dt = new DateTime( Files.getLastModifiedTime( localResource ).toMillis() );
702 catch ( IOException e )
704 log.error("Could not get modification time of {}: {}", localResource, e.getMessage(), e);
707 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
708 String modifiedDate = fmt.print( dt );
710 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
712 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
716 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, Files.size(localResource) ) );
718 catch ( IOException e )
720 log.error("Could not get file size of {}: {}", localResource, e.getMessage(), e);
721 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, 0 ) );
724 this.properties = properties;
729 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
732 if ( !( resource instanceof ArchivaDavResource ) )
734 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
735 "DavResource is not instance of ArchivaDavResource" );
737 return (ArchivaDavResource) resource;
740 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
742 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
743 event.setRemoteIP( remoteIP );
745 for ( AuditListener listener : auditListeners )
747 listener.auditEvent( event );
751 private void queueRepositoryTask( Path localFile )
753 RepositoryTask task = new RepositoryTask();
754 task.setRepositoryId( repository.getId() );
755 task.setResourceFile( localFile );
756 task.setUpdateRelatedArtifacts( false );
757 task.setScanAll( false );
761 scheduler.queueTask( task );
763 catch ( TaskQueueException e )
765 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
766 + "'].", localFile.getFileName() );