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.DavConstants;
39 import org.apache.jackrabbit.webdav.DavException;
40 import org.apache.jackrabbit.webdav.DavResource;
41 import org.apache.jackrabbit.webdav.DavResourceFactory;
42 import org.apache.jackrabbit.webdav.DavResourceIterator;
43 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
44 import org.apache.jackrabbit.webdav.DavResourceLocator;
45 import org.apache.jackrabbit.webdav.DavServletResponse;
46 import org.apache.jackrabbit.webdav.DavSession;
47 import org.apache.jackrabbit.webdav.MultiStatusResponse;
48 import org.apache.jackrabbit.webdav.io.InputContext;
49 import org.apache.jackrabbit.webdav.io.OutputContext;
50 import org.apache.jackrabbit.webdav.lock.ActiveLock;
51 import org.apache.jackrabbit.webdav.lock.LockInfo;
52 import org.apache.jackrabbit.webdav.lock.LockManager;
53 import org.apache.jackrabbit.webdav.lock.Scope;
54 import org.apache.jackrabbit.webdav.lock.Type;
55 import org.apache.jackrabbit.webdav.property.DavProperty;
56 import org.apache.jackrabbit.webdav.property.DavPropertyName;
57 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
58 import org.apache.jackrabbit.webdav.property.DavPropertySet;
59 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
60 import org.apache.jackrabbit.webdav.property.ResourceType;
61 import org.joda.time.DateTime;
62 import org.joda.time.format.DateTimeFormatter;
63 import org.joda.time.format.ISODateTimeFormat;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 import javax.servlet.http.HttpServletResponse;
69 import java.io.IOException;
70 import java.io.InputStream;
71 import java.io.OutputStream;
72 import java.nio.file.Files;
73 import java.util.ArrayList;
74 import java.util.List;
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 File 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 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, ManagedRepository repository,
116 DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
117 MimeTypes mimeTypes, List<AuditListener> auditListeners,
118 RepositoryArchivaTaskScheduler scheduler, FileLockManager fileLockManager )
120 this.localResource = new File( 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, 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 localResource.exists();
168 public boolean isCollection()
170 return localResource.isDirectory();
174 public String getDisplayName()
176 String resPath = getResourcePath();
177 return ( resPath != null ) ? Text.getName( resPath ) : resPath;
181 public DavResourceLocator getLocator()
186 public File 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()
206 return localResource.lastModified();
210 public void spool( OutputContext outputContext )
213 if ( !isCollection() )
215 //outputContext.setContentLength( localResource.length() );
216 outputContext.setProperty( DavConstants.HEADER_CONTENT_LENGTH, Long.toString( localResource.length() ) );
217 outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
222 if ( !isCollection() && outputContext.hasStream() )
224 Lock lock = fileLockManager.readFileLock( localResource );
225 try (InputStream is = Files.newInputStream( lock.getFile().toPath() ))
227 IOUtils.copy( is, outputContext.getOutputStream() );
230 else if ( outputContext.hasStream() )
232 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
233 writer.write( outputContext );
236 catch ( FileLockException e )
238 throw new IOException( e.getMessage(), e );
240 catch ( FileLockTimeoutException e )
242 throw new IOException( e.getMessage(), e );
247 public DavPropertyName[] getPropertyNames()
249 return getProperties().getPropertyNames();
253 public DavProperty getProperty( DavPropertyName name )
255 return getProperties().get( name );
259 public DavPropertySet getProperties()
261 return initProperties();
265 public void setProperty( DavProperty property )
271 public void removeProperty( DavPropertyName propertyName )
276 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
282 @SuppressWarnings("unchecked")
284 public MultiStatusResponse alterProperties( List changeList )
291 public DavResource getCollection()
293 DavResource parent = null;
294 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
296 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
297 if ( parentPath.equals( "" ) )
301 DavResourceLocator parentloc =
302 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
305 parent = factory.createResource( parentloc, session );
307 catch ( DavException e )
316 public void addMember( DavResource resource, InputContext inputContext )
319 File localFile = new File( localResource, resource.getDisplayName() );
320 boolean exists = localFile.exists();
322 if ( isCollection() && inputContext.hasStream() ) // New File
324 try (OutputStream stream = Files.newOutputStream( localFile.toPath() ))
326 IOUtils.copy( inputContext.getInputStream(), stream );
328 catch ( IOException e )
330 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
333 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
334 //long expectedContentLength = inputContext.getContentLength();
335 long expectedContentLength = Long.parseLong( inputContext.getProperty( DavConstants.HEADER_CONTENT_LENGTH ) );
336 long actualContentLength = localFile.length();
337 // length of -1 is given for a chunked request or unknown length, in which case we accept what was uploaded
338 if ( expectedContentLength >= 0 && expectedContentLength != actualContentLength )
340 String msg = "Content Header length was " + expectedContentLength + " but was " + actualContentLength;
341 log.debug( "Upload failed: {}", msg );
343 FileUtils.deleteQuietly( localFile );
344 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
347 queueRepositoryTask( localFile );
349 log.debug( "File '{}{}(current user '{}')", resource.getDisplayName(),
350 ( exists ? "' modified " : "' created " ), this.principal );
352 triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
354 else if ( !inputContext.hasStream() && isCollection() ) // New directory
358 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
360 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
364 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
365 + " as this is not a DAV collection";
367 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
372 public DavResourceIterator getMembers()
374 List<DavResource> list = new ArrayList<>();
375 if ( exists() && isCollection() )
377 for ( String item : localResource.list() )
381 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
383 String path = locator.getResourcePath() + '/' + item;
384 DavResourceLocator resourceLocator =
385 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
386 DavResource resource = factory.createResource( resourceLocator, session );
388 if ( resource != null )
390 list.add( resource );
392 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
395 catch ( DavException e )
401 return new DavResourceIteratorImpl( list );
405 public void removeMember( DavResource member )
408 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
410 if ( resource.exists() )
414 if ( resource.isDirectory() )
416 if ( !FileUtils.deleteQuietly( resource ) )
418 throw new IOException( "Could not remove directory" );
421 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
425 if ( !resource.delete() )
427 throw new IOException( "Could not remove file" );
430 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
433 log.debug( "{}{}' removed (current user '{}')", ( resource.isDirectory() ? "Directory '" : "File '" ),
434 member.getDisplayName(), this.principal );
437 catch ( IOException e )
439 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
444 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
448 private void triggerAuditEvent( DavResource member, String event )
451 String path = logicalResource + "/" + member.getDisplayName();
453 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
454 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, event );
455 auditEvent.setRemoteIP( resource.remoteAddr );
457 for ( AuditListener listener : auditListeners )
459 listener.auditEvent( auditEvent );
464 public void move( DavResource destination )
469 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
474 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
475 if ( isCollection() )
477 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
479 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
483 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
485 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
488 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
489 getLocalResource().getName(), destination, this.principal );
492 catch ( IOException e )
494 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
499 public void copy( DavResource destination, boolean shallow )
504 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
507 if ( shallow && isCollection() )
509 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
514 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
515 if ( isCollection() )
517 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
519 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
523 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
525 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
528 log.debug( "{}{}' copied to '{}' (current user '{)')", ( isCollection() ? "Directory '" : "File '" ),
529 getLocalResource().getName(), destination, this.principal );
532 catch ( IOException e )
534 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
539 public boolean isLockable( Type type, Scope scope )
541 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
545 public boolean hasLock( Type type, Scope scope )
547 return getLock( type, scope ) != null;
551 public ActiveLock getLock( Type type, Scope scope )
553 ActiveLock lock = null;
554 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
556 lock = lockManager.getLock( type, scope, this );
562 public ActiveLock[] getLocks()
564 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
565 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
569 public ActiveLock lock( LockInfo lockInfo )
572 ActiveLock lock = null;
573 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
575 lock = lockManager.createLock( lockInfo, this );
579 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
585 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
590 throw new DavException( DavServletResponse.SC_NOT_FOUND );
592 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
595 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
596 "No lock with the given type/scope present on resource " + getResourcePath() );
599 lock = lockManager.refreshLock( lockInfo, lockToken, this );
605 public void unlock( String lockToken )
608 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
611 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
613 else if ( lock.isLockedByToken( lockToken ) )
615 lockManager.releaseLock( lockToken, this );
619 throw new DavException( DavServletResponse.SC_LOCKED );
624 public void addLockManager( LockManager lockManager )
626 this.lockManager = lockManager;
630 public DavResourceFactory getFactory()
636 public DavSession getSession()
642 * Fill the set of properties
644 protected DavPropertySet initProperties()
648 properties = new DavPropertySet();
651 if ( properties != null )
656 DavPropertySet properties = new DavPropertySet();
658 // set (or reset) fundamental properties
659 if ( getDisplayName() != null )
661 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
663 if ( isCollection() )
665 properties.add( new ResourceType( ResourceType.COLLECTION ) );
666 // Windows XP support
667 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
671 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
673 // Windows XP support
674 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
677 // Need to get the ISO8601 date for properties
678 DateTime dt = new DateTime( localResource.lastModified() );
679 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
680 String modifiedDate = fmt.print( dt );
682 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
684 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
686 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
688 this.properties = properties;
693 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
696 if ( !( resource instanceof ArchivaDavResource ) )
698 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
699 "DavResource is not instance of ArchivaDavResource" );
701 return (ArchivaDavResource) resource;
704 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
706 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
707 event.setRemoteIP( remoteIP );
709 for ( AuditListener listener : auditListeners )
711 listener.auditEvent( event );
715 private void queueRepositoryTask( File localFile )
717 RepositoryTask task = new RepositoryTask();
718 task.setRepositoryId( repository.getId() );
719 task.setResourceFile( localFile );
720 task.setUpdateRelatedArtifacts( false );
721 task.setScanAll( false );
725 scheduler.queueTask( task );
727 catch ( TaskQueueException e )
729 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()