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.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
221 if ( !isCollection() && outputContext.hasStream() )
223 Lock lock = fileLockManager.readFileLock( localResource );
224 try (InputStream is = Files.newInputStream( lock.getFile().toPath() ))
226 IOUtils.copy( is, outputContext.getOutputStream() );
229 else if ( outputContext.hasStream() )
231 IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
232 writer.write( outputContext );
235 catch ( FileLockException e )
237 throw new IOException( e.getMessage(), e );
239 catch ( FileLockTimeoutException e )
241 throw new IOException( e.getMessage(), e );
246 public DavPropertyName[] getPropertyNames()
248 return getProperties().getPropertyNames();
252 public DavProperty getProperty( DavPropertyName name )
254 return getProperties().get( name );
258 public DavPropertySet getProperties()
260 return initProperties();
264 public void setProperty( DavProperty property )
270 public void removeProperty( DavPropertyName propertyName )
275 public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
281 @SuppressWarnings("unchecked")
283 public MultiStatusResponse alterProperties( List changeList )
290 public DavResource getCollection()
292 DavResource parent = null;
293 if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
295 String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
296 if ( parentPath.equals( "" ) )
300 DavResourceLocator parentloc =
301 locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
304 parent = factory.createResource( parentloc, session );
306 catch ( DavException e )
315 public void addMember( DavResource resource, InputContext inputContext )
318 File localFile = new File( localResource, resource.getDisplayName() );
319 boolean exists = localFile.exists();
321 if ( isCollection() && inputContext.hasStream() ) // New File
323 try (OutputStream stream = Files.newOutputStream( localFile.toPath() ))
325 IOUtils.copy( inputContext.getInputStream(), stream );
327 catch ( IOException e )
329 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
332 // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
333 long expectedContentLength = inputContext.getContentLength();
334 long actualContentLength = localFile.length();
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 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 log.debug( "Directory '{}' (current user '{}')", resource.getDisplayName(), this.principal );
358 triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
362 String msg = "Could not write member " + resource.getResourcePath() + " at " + getResourcePath()
363 + " as this is not a DAV collection";
365 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, msg );
370 public DavResourceIterator getMembers()
372 List<DavResource> list = new ArrayList<>();
373 if ( exists() && isCollection() )
375 for ( String item : localResource.list() )
379 if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
381 String path = locator.getResourcePath() + '/' + item;
382 DavResourceLocator resourceLocator =
383 locator.getFactory().createResourceLocator( locator.getPrefix(), path );
384 DavResource resource = factory.createResource( resourceLocator, session );
386 if ( resource != null )
388 list.add( resource );
390 log.debug( "Resource '{}' retrieved by '{}'", item, this.principal );
393 catch ( DavException e )
399 return new DavResourceIteratorImpl( list );
403 public void removeMember( DavResource member )
406 File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
408 if ( resource.exists() )
412 if ( resource.isDirectory() )
414 if ( !FileUtils.deleteQuietly( resource ) )
416 throw new IOException( "Could not remove directory" );
419 triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
423 if ( !resource.delete() )
425 throw new IOException( "Could not remove file" );
428 triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
431 log.debug( "{}{}' removed (current user '{}')", ( resource.isDirectory() ? "Directory '" : "File '" ),
432 member.getDisplayName(), this.principal );
435 catch ( IOException e )
437 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
442 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
446 private void triggerAuditEvent( DavResource member, String event )
449 String path = logicalResource + "/" + member.getDisplayName();
451 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( member );
452 AuditEvent auditEvent = new AuditEvent( locator.getRepositoryId(), resource.principal, path, event );
453 auditEvent.setRemoteIP( resource.remoteAddr );
455 for ( AuditListener listener : auditListeners )
457 listener.auditEvent( auditEvent );
462 public void move( DavResource destination )
467 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
472 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
473 if ( isCollection() )
475 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
477 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
481 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
483 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
486 log.debug( "{}{}' moved to '{}' (current user '{}')", ( isCollection() ? "Directory '" : "File '" ),
487 getLocalResource().getName(), destination, this.principal );
490 catch ( IOException e )
492 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
497 public void copy( DavResource destination, boolean shallow )
502 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
505 if ( shallow && isCollection() )
507 throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
512 ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
513 if ( isCollection() )
515 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
517 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
521 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
523 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
526 log.debug( "{}{}' copied to '{}' (current user '{)')", ( isCollection() ? "Directory '" : "File '" ),
527 getLocalResource().getName(), destination, this.principal );
530 catch ( IOException e )
532 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
537 public boolean isLockable( Type type, Scope scope )
539 return Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope );
543 public boolean hasLock( Type type, Scope scope )
545 return getLock( type, scope ) != null;
549 public ActiveLock getLock( Type type, Scope scope )
551 ActiveLock lock = null;
552 if ( exists() && Type.WRITE.equals( type ) && Scope.EXCLUSIVE.equals( scope ) )
554 lock = lockManager.getLock( type, scope, this );
560 public ActiveLock[] getLocks()
562 ActiveLock writeLock = getLock( Type.WRITE, Scope.EXCLUSIVE );
563 return ( writeLock != null ) ? new ActiveLock[]{ writeLock } : new ActiveLock[0];
567 public ActiveLock lock( LockInfo lockInfo )
570 ActiveLock lock = null;
571 if ( isLockable( lockInfo.getType(), lockInfo.getScope() ) )
573 lock = lockManager.createLock( lockInfo, this );
577 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope." );
583 public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
588 throw new DavException( DavServletResponse.SC_NOT_FOUND );
590 ActiveLock lock = getLock( lockInfo.getType(), lockInfo.getScope() );
593 throw new DavException( DavServletResponse.SC_PRECONDITION_FAILED,
594 "No lock with the given type/scope present on resource " + getResourcePath() );
597 lock = lockManager.refreshLock( lockInfo, lockToken, this );
603 public void unlock( String lockToken )
606 ActiveLock lock = getLock( Type.WRITE, Scope.EXCLUSIVE );
609 throw new DavException( HttpServletResponse.SC_PRECONDITION_FAILED );
611 else if ( lock.isLockedByToken( lockToken ) )
613 lockManager.releaseLock( lockToken, this );
617 throw new DavException( DavServletResponse.SC_LOCKED );
622 public void addLockManager( LockManager lockManager )
624 this.lockManager = lockManager;
628 public DavResourceFactory getFactory()
634 public DavSession getSession()
640 * Fill the set of properties
642 protected DavPropertySet initProperties()
646 properties = new DavPropertySet();
649 if ( properties != null )
654 DavPropertySet properties = new DavPropertySet();
656 // set (or reset) fundamental properties
657 if ( getDisplayName() != null )
659 properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
661 if ( isCollection() )
663 properties.add( new ResourceType( ResourceType.COLLECTION ) );
664 // Windows XP support
665 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
669 properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
671 // Windows XP support
672 properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
675 // Need to get the ISO8601 date for properties
676 DateTime dt = new DateTime( localResource.lastModified() );
677 DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
678 String modifiedDate = fmt.print( dt );
680 properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
682 properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
684 properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
686 this.properties = properties;
691 private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
694 if ( !( resource instanceof ArchivaDavResource ) )
696 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
697 "DavResource is not instance of ArchivaDavResource" );
699 return (ArchivaDavResource) resource;
702 private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
704 AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
705 event.setRemoteIP( remoteIP );
707 for ( AuditListener listener : auditListeners )
709 listener.auditEvent( event );
713 private void queueRepositoryTask( File localFile )
715 RepositoryTask task = new RepositoryTask();
716 task.setRepositoryId( repository.getId() );
717 task.setResourceFile( localFile );
718 task.setUpdateRelatedArtifacts( false );
719 task.setScanAll( false );
723 scheduler.queueTask( task );
725 catch ( TaskQueueException e )
727 log.error( "Unable to queue repository task to execute consumers on resource file ['" + localFile.getName()