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.audit.AuditEvent;
24 import org.apache.archiva.audit.AuditListener;
25 import org.apache.archiva.common.filelock.FileLockException;
26 import org.apache.archiva.common.filelock.FileLockManager;
27 import org.apache.archiva.common.filelock.FileLockTimeoutException;
28 import org.apache.archiva.common.filelock.Lock;
29 import org.apache.archiva.redback.components.taskqueue.TaskQueueException;
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.DavException;
39 import org.apache.jackrabbit.webdav.DavResource;
40 import org.apache.jackrabbit.webdav.DavResourceFactory;
41 import org.apache.jackrabbit.webdav.DavResourceIterator;
42 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
43 import org.apache.jackrabbit.webdav.DavResourceLocator;
44 import org.apache.jackrabbit.webdav.DavServletResponse;
45 import org.apache.jackrabbit.webdav.DavSession;
46 import org.apache.jackrabbit.webdav.MultiStatusResponse;
47 import org.apache.jackrabbit.webdav.io.InputContext;
48 import org.apache.jackrabbit.webdav.io.OutputContext;
49 import org.apache.jackrabbit.webdav.lock.ActiveLock;
50 import org.apache.jackrabbit.webdav.lock.LockInfo;
51 import org.apache.jackrabbit.webdav.lock.LockManager;
52 import org.apache.jackrabbit.webdav.lock.Scope;
53 import org.apache.jackrabbit.webdav.lock.Type;
54 import org.apache.jackrabbit.webdav.property.DavProperty;
55 import org.apache.jackrabbit.webdav.property.DavPropertyName;
56 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
57 import org.apache.jackrabbit.webdav.property.DavPropertySet;
58 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
59 import org.apache.jackrabbit.webdav.property.ResourceType;
60 import org.joda.time.DateTime;
61 import org.joda.time.format.DateTimeFormatter;
62 import org.joda.time.format.ISODateTimeFormat;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 import javax.servlet.http.HttpServletResponse;
68 import java.io.IOException;
69 import java.io.InputStream;
70 import java.io.OutputStream;
71 import java.nio.file.Files;
72 import java.util.ArrayList;
73 import java.util.List;
77 public class ArchivaDavResource
78 implements DavResource
80 public static final String HIDDEN_PATH_PREFIX = ".";
82 private final ArchivaDavResourceLocator locator;
84 private final DavResourceFactory factory;
86 private final File localResource;
88 private final String logicalResource;
90 private DavPropertySet properties = null;
92 private LockManager lockManager;
94 private final DavSession session;
96 private String remoteAddr;
98 private final ManagedRepository repository;
100 private final MimeTypes mimeTypes;
102 private List<AuditListener> auditListeners;
104 private String principal;
106 public static final String COMPLIANCE_CLASS = "1, 2";
108 private final ArchivaTaskScheduler scheduler;
110 private final FileLockManager fileLockManager;
112 private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
114 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
115 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
116 MimeTypes mimeTypes, List<AuditListener> auditListeners,
117 RepositoryArchivaTaskScheduler scheduler, FileLockManager fileLockManager )
119 this.localResource = new File( localResource );
120 this.logicalResource = logicalResource;
121 this.locator = locator;
122 this.factory = factory;
123 this.session = session;
125 // TODO: push into locator as well as moving any references out of the resource factory
126 this.repository = repository;
128 // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
129 this.mimeTypes = mimeTypes;
130 this.auditListeners = auditListeners;
131 this.scheduler = scheduler;
132 this.fileLockManager = fileLockManager;
135 public ArchivaDavResource( String localResource, String logicalResource, ManagedRepository repository,
136 String remoteAddr, String principal, DavSession session,
137 ArchivaDavResourceLocator locator, DavResourceFactory factory, MimeTypes mimeTypes,
138 List<AuditListener> auditListeners, RepositoryArchivaTaskScheduler scheduler,
139 FileLockManager fileLockManager )
141 this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
142 scheduler, fileLockManager );
144 this.remoteAddr = remoteAddr;
145 this.principal = principal;
149 public String getComplianceClass()
151 return COMPLIANCE_CLASS;
155 public String getSupportedMethods()
161 public boolean exists()
163 return localResource.exists();
167 public boolean isCollection()
169 return localResource.isDirectory();
173 public String getDisplayName()
175 String resPath = getResourcePath();
176 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
180 public DavResourceLocator getLocator()
185 public File getLocalResource()
187 return localResource;
191 public String getResourcePath()
193 return locator.getResourcePath();
197 public String getHref()
199 return locator.getHref( isCollection() );
203 public long getModificationTime()
205 return localResource.lastModified();
209 public void spool( OutputContext outputContext )
212 if ( !isCollection() )
214 outputContext.setContentLength( localResource.length() );
215 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
220 if ( !isCollection() && outputContext.hasStream() )
222 Lock lock = fileLockManager.readFileLock( localResource );
223 try (InputStream is = Files.newInputStream( lock.getFile().toPath() ))
225 IOUtils.copy( is, outputContext.getOutputStream() );
228 else if ( outputContext.hasStream() )
230 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
231 writer.write( outputContext );
234 catch ( FileLockException e )
236 throw new IOException( e.getMessage(), e );
238 catch ( FileLockTimeoutException e )
240 throw new IOException( e.getMessage(), e );
245 public DavPropertyName[] getPropertyNames()
247 return getProperties().getPropertyNames();
251 public DavProperty getProperty( DavPropertyName name )
253 return getProperties().get( name );
257 public DavPropertySet getProperties()
259 return initProperties();
263 public void setProperty( DavProperty property )
269 public void removeProperty( DavPropertyName propertyName )
274 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
280 @SuppressWarnings("unchecked")
282 public MultiStatusResponse alterProperties( List changeList )
289 public DavResource getCollection()
291 DavResource parent = null;
292 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
294 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
295 if ( parentPath.equals( "" ) )
299 DavResourceLocator parentloc =
300 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
303 parent = factory.createResource( parentloc, session );
305 catch ( DavException e )
314 public void addMember( DavResource resource, InputContext inputContext )
317 File localFile = new File( localResource, resource.getDisplayName() );
318 boolean exists = localFile.exists();
320 if ( isCollection() && inputContext.hasStream() ) // New File
322 try (OutputStream stream = Files.newOutputStream( localFile.toPath() ))
324 IOUtils.copy( inputContext.getInputStream(), stream );
326 catch ( IOException e )
328 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
331 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
332 long expectedContentLength = inputContext.getContentLength();
333 long actualContentLength = localFile.length();
334 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
335 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
337 String msg = "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
338 log.debug( "Upload failed: {}", msg );
340 FileUtils.deleteQuietly( localFile );
341 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
344 queueRepositoryTask( localFile );
346 log.debug( "File '{}{}(current user '{}')", resource.getDisplayName(),
347 ( exists ? "' modified " : "' created " ), this.principal );
349 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
351 else if ( !inputContext.hasStream() && isCollection() ) // New directory
355 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
357 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
361 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
362 + " as this is not a DAV collection";
364 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
369 public DavResourceIterator getMembers()
371 List<DavResource> list = new ArrayList<>();
372 if ( exists() && isCollection() )
374 for ( String item : localResource.list() )
378 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
380 String path = locator.getResourcePath() + '/' + item;
381 DavResourceLocator resourceLocator =
382 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
383 DavResource resource = factory.createResource( resourceLocator, session );
385 if ( resource != null )
387 list.add( resource );
389 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
392 catch ( DavException e )
398 return new DavResourceIteratorImpl( list );
402 public void removeMember( DavResource member )
405 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
407 if ( resource.exists() )
411 if ( resource.isDirectory() )
413 if ( !FileUtils.deleteQuietly( resource ) )
415 throw new IOException( "Could not remove directory" );
418 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
422 if ( !resource.delete() )
424 throw new IOException( "Could not remove file" );
427 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
430 log.debug( "{}{}' removed (current user '{}')", ( resource.isDirectory() ? "Directory '" : "File '" ),
431 member.getDisplayName(), this.principal );
434 catch ( IOException e )
436 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
441 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
445 private void triggerAuditEvent( DavResource member, String event )
448 String path = logicalResource + "/" + member.getDisplayName();
450 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
451 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, event );
452 auditEvent.setRemoteIP( resource.remoteAddr );
454 for ( AuditListener listener : auditListeners )
456 listener.auditEvent( auditEvent );
461 public void move( DavResource destination )
466 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
471 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
472 if ( isCollection() )
474 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
476 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
480 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
482 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
485 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
486 getLocalResource().getName(), destination, this.principal );
489 catch ( IOException e )
491 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
496 public void copy( DavResource destination, boolean shallow )
501 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
504 if ( shallow && isCollection() )
506 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
511 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
512 if ( isCollection() )
514 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
516 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
520 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
522 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
525 log.debug( "{}{}' copied to '{}' (current user '{)')", ( isCollection() ? "Directory '" : "File '" ),
526 getLocalResource().getName(), destination, this.principal );
529 catch ( IOException e )
531 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
536 public boolean isLockable( Type type, Scope scope )
538 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
542 public boolean hasLock( Type type, Scope scope )
544 return getLock( type, scope ) != null;
548 public ActiveLock getLock( Type type, Scope scope )
550 ActiveLock lock = null;
551 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
553 lock = lockManager.getLock( type, scope, this );
559 public ActiveLock[] getLocks()
561 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
562 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
566 public ActiveLock lock( LockInfo lockInfo )
569 ActiveLock lock = null;
570 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
572 lock = lockManager.createLock( lockInfo, this );
576 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
582 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
587 throw new DavException( DavServletResponse.SC_NOT_FOUND );
589 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
592 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
593 "No lock with the given type/scope present on resource " + getResourcePath() );
596 lock = lockManager.refreshLock( lockInfo, lockToken, this );
602 public void unlock( String lockToken )
605 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
608 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
610 else if ( lock.isLockedByToken( lockToken ) )
612 lockManager.releaseLock( lockToken, this );
616 throw new DavException( DavServletResponse.SC_LOCKED );
621 public void addLockManager( LockManager lockManager )
623 this.lockManager = lockManager;
627 public DavResourceFactory getFactory()
633 public DavSession getSession()
639 * Fill the set of properties
641 protected DavPropertySet initProperties()
645 properties = new DavPropertySet();
648 if ( properties != null )
653 DavPropertySet properties = new DavPropertySet();
655 // set (or reset) fundamental properties
656 if ( getDisplayName() != null )
658 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
660 if ( isCollection() )
662 properties.add( new ResourceType( ResourceType.COLLECTION ) );
663 // Windows XP support
664 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
668 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
670 // Windows XP support
671 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
674 // Need to get the ISO8601 date for properties
675 DateTime dt = new DateTime( localResource.lastModified() );
676 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
677 String modifiedDate = fmt.print( dt );
679 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
681 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
683 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
685 this.properties = properties;
690 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
693 if ( !( resource instanceof ArchivaDavResource ) )
695 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
696 "DavResource is not instance of ArchivaDavResource" );
698 return (ArchivaDavResource) resource;
701 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
703 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
704 event.setRemoteIP( remoteIP );
706 for ( AuditListener listener : auditListeners )
708 listener.auditEvent( event );
712 private void queueRepositoryTask( File localFile )
714 RepositoryTask task = new RepositoryTask();
715 task.setRepositoryId( repository.getId() );
716 task.setResourceFile( localFile );
717 task.setUpdateRelatedArtifacts( false );
718 task.setScanAll( false );
722 scheduler.queueTask( task );
724 catch ( TaskQueueException e )
726 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()