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.beans.ManagedRepository;
23 import org.apache.archiva.common.filelock.FileLockException;
24 import org.apache.archiva.common.filelock.FileLockManager;
25 import org.apache.archiva.common.filelock.FileLockTimeoutException;
26 import org.apache.archiva.common.filelock.Lock;
27 import org.apache.archiva.metadata.model.facets.AuditEvent;
28 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
29 import org.apache.archiva.repository.events.AuditListener;
30 import org.apache.archiva.scheduler.ArchivaTaskScheduler;
31 import org.apache.archiva.scheduler.repository.model.RepositoryArchivaTaskScheduler;
32 import org.apache.archiva.scheduler.repository.model.RepositoryTask;
33 import org.apache.archiva.webdav.util.IndexWriter;
34 import org.apache.archiva.webdav.util.MimeTypes;
35 import org.apache.commons.io.FileUtils;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.jackrabbit.util.Text;
38 import org.apache.jackrabbit.webdav.*;
39 import org.apache.jackrabbit.webdav.io.InputContext;
40 import org.apache.jackrabbit.webdav.io.OutputContext;
41 import org.apache.jackrabbit.webdav.lock.*;
42 import org.apache.jackrabbit.webdav.property.*;
43 import org.joda.time.DateTime;
44 import org.joda.time.format.DateTimeFormatter;
45 import org.joda.time.format.ISODateTimeFormat;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import javax.servlet.http.HttpServletResponse;
50 import java.io.IOException;
51 import java.io.InputStream;
52 import java.io.OutputStream;
53 import java.nio.file.Files;
54 import java.nio.file.Path;
55 import java.nio.file.Paths;
56 import java.util.ArrayList;
57 import java.util.List;
58 import java.util.stream.Stream;
62 public class ArchivaDavResource
63 implements DavResource
65 public static final String HIDDEN_PATH_PREFIX = ".";
67 private final ArchivaDavResourceLocator locator;
69 private final DavResourceFactory factory;
71 private final Path localResource;
73 private final String logicalResource;
75 private DavPropertySet properties = null;
77 private LockManager lockManager;
79 private final DavSession session;
81 private String remoteAddr;
83 private final ManagedRepository repository;
85 private final MimeTypes mimeTypes;
87 private List<AuditListener> auditListeners;
89 private String principal;
91 public static final String COMPLIANCE_CLASS = "1, 2";
93 private final ArchivaTaskScheduler scheduler;
95 private final FileLockManager fileLockManager;
97 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
99 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
100 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
101 MimeTypes mimeTypes, List<AuditListener> auditListeners,
102 RepositoryArchivaTaskScheduler scheduler, FileLockManager fileLockManager )
104 this.localResource = Paths.get( localResource );
105 this.logicalResource = logicalResource;
106 this.locator = locator;
107 this.factory = factory;
108 this.session = session;
110 // TODO: push into locator as well as moving any references out of the resource factory
111 this.repository = repository;
113 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
114 this.mimeTypes = mimeTypes;
115 this.auditListeners = auditListeners;
116 this.scheduler = scheduler;
117 this.fileLockManager = fileLockManager;
120 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
121 String remoteAddr, String principal, DavSession session,
122 ArchivaDavResourceLocator locator, DavResourceFactory factory, MimeTypes mimeTypes,
123 List<AuditListener> auditListeners, RepositoryArchivaTaskScheduler scheduler,
124 FileLockManager fileLockManager )
126 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
127 scheduler, fileLockManager );
129 this.remoteAddr = remoteAddr;
130 this.principal = principal;
134 public String getComplianceClass()
136 return COMPLIANCE_CLASS;
140 public String getSupportedMethods()
146 public boolean exists()
148 return Files.exists(localResource);
152 public boolean isCollection()
154 return Files.isDirectory(localResource);
158 public String getDisplayName()
160 String resPath = getResourcePath();
161 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
165 public DavResourceLocator getLocator()
170 public Path getLocalResource()
172 return localResource;
176 public String getResourcePath()
178 return locator.getResourcePath();
182 public String getHref()
184 return locator.getHref( isCollection() );
188 public long getModificationTime()
192 return Files.getLastModifiedTime(localResource).toMillis();
194 catch ( IOException e )
196 log.error("Could not get modification time of {}: {}", localResource, e.getMessage(), e);
202 public void spool( OutputContext outputContext )
205 if ( !isCollection() )
207 outputContext.setContentLength( Files.size( localResource ) );
208 outputContext.setContentType( mimeTypes.getMimeType( localResource.getFileName().toString() ) );
213 if ( !isCollection() && outputContext.hasStream() )
215 Lock lock = fileLockManager.readFileLock( localResource );
216 try (InputStream is = Files.newInputStream( lock.getFile()))
218 IOUtils.copy( is, outputContext.getOutputStream() );
221 else if ( outputContext.hasStream() )
223 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
224 writer.write( outputContext );
227 catch ( FileLockException e )
229 throw new IOException( e.getMessage(), e );
231 catch ( FileLockTimeoutException e )
233 throw new IOException( e.getMessage(), e );
238 public DavPropertyName[] getPropertyNames()
240 return getProperties().getPropertyNames();
244 public DavProperty getProperty( DavPropertyName name )
246 return getProperties().get( name );
250 public DavPropertySet getProperties()
252 return initProperties();
256 public void setProperty( DavProperty property )
262 public void removeProperty( DavPropertyName propertyName )
267 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
273 @SuppressWarnings("unchecked")
275 public MultiStatusResponse alterProperties( List changeList )
282 public DavResource getCollection()
284 DavResource parent = null;
285 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
287 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
288 if ( parentPath.equals( "" ) )
292 DavResourceLocator parentloc =
293 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
296 parent = factory.createResource( parentloc, session );
298 catch ( DavException e )
307 public void addMember( DavResource resource, InputContext inputContext )
310 Path localFile = localResource.resolve( resource.getDisplayName() );
311 boolean exists = Files.exists(localFile);
313 if ( isCollection() && inputContext.hasStream() ) // New File
315 try (OutputStream stream = Files.newOutputStream( localFile ))
317 IOUtils.copy( inputContext.getInputStream(), stream );
319 catch ( IOException e )
321 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
324 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
325 long expectedContentLength = inputContext.getContentLength();
326 long actualContentLength = 0;
329 actualContentLength = Files.size(localFile);
331 catch ( IOException e )
333 log.error( "Could not get length of file {}: {}", localFile, e.getMessage(), e );
335 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
336 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
338 String msg = "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
339 log.debug( "Upload failed: {}", msg );
341 org.apache.archiva.common.utils.FileUtils.deleteQuietly( localFile );
342 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
345 queueRepositoryTask( localFile );
347 log.debug( "File '{}{}(current user '{}')", resource.getDisplayName(),
348 ( exists ? "' modified " : "' created " ), this.principal );
350 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
352 else if ( !inputContext.hasStream() && isCollection() ) // New directory
356 Files.createDirectories( localFile );
358 catch ( IOException e )
360 log.error("Could not create directory {}: {}", localFile, e.getMessage(), e);
363 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
365 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
369 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
370 + " as this is not a DAV collection";
372 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
377 public DavResourceIterator getMembers()
379 List<DavResource> list = new ArrayList<>();
380 if ( exists() && isCollection() )
382 try ( Stream<Path> stream = Files.list(localResource))
384 stream.forEach ( p ->
386 String item = p.toString();
389 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
391 String path = locator.getResourcePath( ) + '/' + item;
392 DavResourceLocator resourceLocator =
393 locator.getFactory( ).createResourceLocator( locator.getPrefix( ), path );
394 DavResource resource = factory.createResource( resourceLocator, session );
396 if ( resource != null )
398 list.add( resource );
400 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
403 catch ( DavException e )
408 } catch (IOException e) {
409 log.error("Error while listing {}", localResource);
412 return new DavResourceIteratorImpl( list );
416 public void removeMember( DavResource member )
419 Path resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
421 if ( Files.exists(resource) )
425 if ( Files.isDirectory(resource) )
427 org.apache.archiva.common.utils.FileUtils.deleteDirectory( resource );
428 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
432 Files.deleteIfExists( resource );
433 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
436 log.debug( "{}{}' removed (current user '{}')", ( Files.isDirectory(resource) ? "Directory '" : "File '" ),
437 member.getDisplayName(), this.principal );
440 catch ( IOException e )
442 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
447 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
451 private void triggerAuditEvent( DavResource member, String action )
454 String path = logicalResource + "/" + member.getDisplayName();
456 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
457 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, action );
458 auditEvent.setRemoteIP( resource.remoteAddr );
460 for ( AuditListener listener : auditListeners )
462 listener.auditEvent( auditEvent );
467 public void move( DavResource destination )
472 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
477 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
478 if ( isCollection() )
480 FileUtils.moveDirectory( getLocalResource().toFile(), resource.getLocalResource().toFile() );
482 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
486 FileUtils.moveFile( getLocalResource().toFile(), resource.getLocalResource().toFile() );
488 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
491 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
492 getLocalResource().getFileName(), destination, this.principal );
495 catch ( IOException e )
497 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
502 public void copy( DavResource destination, boolean shallow )
507 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
510 if ( shallow && isCollection() )
512 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
517 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
518 if ( isCollection() )
520 FileUtils.copyDirectory( getLocalResource().toFile(), resource.getLocalResource().toFile() );
522 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
526 FileUtils.copyFile( getLocalResource().toFile(), resource.getLocalResource().toFile() );
528 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
531 log.debug( "{}{}' copied to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
532 getLocalResource().getFileName(), destination, this.principal );
535 catch ( IOException e )
537 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
542 public boolean isLockable( Type type, Scope scope )
544 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
548 public boolean hasLock( Type type, Scope scope )
550 return getLock( type, scope ) != null;
554 public ActiveLock getLock( Type type, Scope scope )
556 ActiveLock lock = null;
557 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
559 lock = lockManager.getLock( type, scope, this );
565 public ActiveLock[] getLocks()
567 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
568 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
572 public ActiveLock lock( LockInfo lockInfo )
575 ActiveLock lock = null;
576 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
578 lock = lockManager.createLock( lockInfo, this );
582 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
588 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
593 throw new DavException( DavServletResponse.SC_NOT_FOUND );
595 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
598 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
599 "No lock with the given type/scope present on resource " + getResourcePath() );
602 lock = lockManager.refreshLock( lockInfo, lockToken, this );
608 public void unlock( String lockToken )
611 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
614 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
616 else if ( lock.isLockedByToken( lockToken ) )
618 lockManager.releaseLock( lockToken, this );
622 throw new DavException( DavServletResponse.SC_LOCKED );
627 public void addLockManager( LockManager lockManager )
629 this.lockManager = lockManager;
633 public DavResourceFactory getFactory()
639 public DavSession getSession()
645 * Fill the set of properties
647 protected DavPropertySet initProperties()
651 properties = new DavPropertySet();
654 if ( properties != null )
659 DavPropertySet properties = new DavPropertySet();
661 // set (or reset) fundamental properties
662 if ( getDisplayName() != null )
664 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
666 if ( isCollection() )
668 properties.add( new ResourceType( ResourceType.COLLECTION ) );
669 // Windows XP support
670 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
674 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
676 // Windows XP support
677 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
680 // Need to get the ISO8601 date for properties
684 dt = new DateTime( Files.getLastModifiedTime( localResource ).toMillis() );
686 catch ( IOException e )
688 log.error("Could not get modification time of {}: {}", localResource, e.getMessage(), e);
691 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
692 String modifiedDate = fmt.print( dt );
694 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
696 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
700 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, Files.size(localResource) ) );
702 catch ( IOException e )
704 log.error("Could not get file size of {}: {}", localResource, e.getMessage(), e);
705 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, 0 ) );
708 this.properties = properties;
713 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
716 if ( !( resource instanceof ArchivaDavResource ) )
718 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
719 "DavResource is not instance of ArchivaDavResource" );
721 return (ArchivaDavResource) resource;
724 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
726 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
727 event.setRemoteIP( remoteIP );
729 for ( AuditListener listener : auditListeners )
731 listener.auditEvent( event );
735 private void queueRepositoryTask( Path localFile )
737 RepositoryTask task = new RepositoryTask();
738 task.setRepositoryId( repository.getId() );
739 task.setResourceFile( localFile );
740 task.setUpdateRelatedArtifacts( false );
741 task.setScanAll( false );
745 scheduler.queueTask( task );
747 catch ( TaskQueueException e )
749 log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
750 + "'].", localFile.getFileName() );