]> source.dussan.org Git - archiva.git/blob
ec4f1b97bbba1300a5a12e6c85068cbe79b59062
[archiva.git] /
1 package org.apache.maven.archiva.webdav;
2
3 /*
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
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Calendar;
28 import java.util.List;
29
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.apache.commons.io.FileUtils;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.jackrabbit.util.Text;
35 import org.apache.jackrabbit.webdav.DavException;
36 import org.apache.jackrabbit.webdav.DavResource;
37 import org.apache.jackrabbit.webdav.DavResourceFactory;
38 import org.apache.jackrabbit.webdav.DavResourceIterator;
39 import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
40 import org.apache.jackrabbit.webdav.DavResourceLocator;
41 import org.apache.jackrabbit.webdav.DavServletResponse;
42 import org.apache.jackrabbit.webdav.DavSession;
43 import org.apache.jackrabbit.webdav.MultiStatusResponse;
44 import org.apache.jackrabbit.webdav.io.InputContext;
45 import org.apache.jackrabbit.webdav.io.OutputContext;
46 import org.apache.jackrabbit.webdav.lock.ActiveLock;
47 import org.apache.jackrabbit.webdav.lock.LockInfo;
48 import org.apache.jackrabbit.webdav.lock.LockManager;
49 import org.apache.jackrabbit.webdav.lock.Scope;
50 import org.apache.jackrabbit.webdav.lock.Type;
51 import org.apache.jackrabbit.webdav.property.DavProperty;
52 import org.apache.jackrabbit.webdav.property.DavPropertyName;
53 import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
54 import org.apache.jackrabbit.webdav.property.DavPropertySet;
55 import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
56 import org.apache.jackrabbit.webdav.property.ResourceType;
57 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
58 import org.apache.maven.archiva.database.ArchivaAuditLogsDao;
59 import org.apache.maven.archiva.model.ArchivaAuditLogs;
60 import org.apache.maven.archiva.repository.audit.AuditEvent;
61 import org.apache.maven.archiva.repository.audit.AuditListener;
62 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
63 import org.apache.maven.archiva.scheduled.tasks.RepositoryTask;
64 import org.apache.maven.archiva.scheduled.tasks.TaskCreator;
65 import org.apache.maven.archiva.webdav.util.IndexWriter;
66 import org.apache.maven.archiva.webdav.util.MimeTypes;
67 import org.codehaus.plexus.taskqueue.TaskQueueException;
68 import org.joda.time.DateTime;
69 import org.joda.time.format.DateTimeFormatter;
70 import org.joda.time.format.ISODateTimeFormat;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 /**
75  */
76 public class ArchivaDavResource
77     implements DavResource
78 {
79     public static final String HIDDEN_PATH_PREFIX = ".";
80
81     private final ArchivaDavResourceLocator locator;
82
83     private final DavResourceFactory factory;
84
85     private final File localResource;
86
87     private final String logicalResource;
88
89     private DavPropertySet properties = null;
90
91     private LockManager lockManager;
92     
93     private final DavSession session;
94     
95     private String remoteAddr;
96
97     private final ManagedRepositoryConfiguration repository;
98
99     private final MimeTypes mimeTypes;
100
101     private List<AuditListener> auditListeners;
102
103     private String principal;
104     
105     public static final String COMPLIANCE_CLASS = "1, 2";
106     
107     private ArchivaTaskScheduler scheduler;
108     
109     private Logger log = LoggerFactory.getLogger( ArchivaDavResource.class );
110     
111     private ArchivaAuditLogsDao auditLogsDao;
112
113     public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
114                                DavSession session, ArchivaDavResourceLocator locator, DavResourceFactory factory,
115                                MimeTypes mimeTypes, List<AuditListener> auditListeners,
116                                ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
117     {
118         this.localResource = new File( localResource ); 
119         this.logicalResource = logicalResource;
120         this.locator = locator;
121         this.factory = factory;
122         this.session = session;
123         
124         // TODO: push into locator as well as moving any references out of the resource factory
125         this.repository = repository;
126         
127         // TODO: these should be pushed into the repository layer, along with the physical file operations in this class
128         this.mimeTypes = mimeTypes;        
129         this.auditListeners = auditListeners;
130         this.scheduler = scheduler;
131         this.auditLogsDao = auditLogsDao;
132     }
133
134     public ArchivaDavResource( String localResource, String logicalResource, ManagedRepositoryConfiguration repository,
135                                String remoteAddr, String principal, DavSession session, ArchivaDavResourceLocator locator,
136                                DavResourceFactory factory, MimeTypes mimeTypes, List<AuditListener> auditListeners,
137                                ArchivaTaskScheduler scheduler, ArchivaAuditLogsDao auditLogsDao )
138     {
139         this( localResource, logicalResource, repository, session, locator, factory, mimeTypes, auditListeners,
140               scheduler, auditLogsDao );
141
142         this.remoteAddr = remoteAddr;
143         this.principal = principal;
144     }
145
146     public String getComplianceClass()
147     {
148         return COMPLIANCE_CLASS;
149     }
150
151     public String getSupportedMethods()
152     {
153         return METHODS;
154     }
155
156     public boolean exists()
157     {
158         return localResource.exists();
159     }
160
161     public boolean isCollection()
162     {
163         return localResource.isDirectory();
164     }
165
166     public String getDisplayName()
167     {
168         String resPath = getResourcePath();
169         return ( resPath != null ) ? Text.getName( resPath ) : resPath;
170     }
171
172     public DavResourceLocator getLocator()
173     {
174         return locator;
175     }
176
177     public File getLocalResource()
178     {
179         return localResource;
180     }
181
182     public String getResourcePath()
183     {
184         return locator.getResourcePath();
185     }
186
187     public String getHref()
188     {
189         return locator.getHref( isCollection() );
190     }
191
192     public long getModificationTime()
193     {
194         return localResource.lastModified();
195     }
196
197     public void spool( OutputContext outputContext )
198         throws IOException
199     {
200         if ( !isCollection())
201         {
202             outputContext.setContentLength( localResource.length() );
203             outputContext.setContentType( mimeTypes.getMimeType( localResource.getName() ) );
204         }
205         
206         if ( !isCollection() && outputContext.hasStream() )
207         {
208             FileInputStream is = null;
209             try
210             {
211                 // Write content to stream
212                 is = new FileInputStream( localResource );
213                 IOUtils.copy( is, outputContext.getOutputStream() );
214             }
215             finally
216             {
217                 IOUtils.closeQuietly( is );
218             }
219         }
220         else if (outputContext.hasStream())
221         {
222             IndexWriter writer = new IndexWriter( this, localResource, logicalResource );
223             writer.write( outputContext );
224         }
225     }
226
227     public DavPropertyName[] getPropertyNames()
228     {
229         return getProperties().getPropertyNames();
230     }
231
232     public DavProperty getProperty( DavPropertyName name )
233     {
234         return getProperties().get( name );
235     }
236
237     public DavPropertySet getProperties()
238     {
239         return initProperties();
240     }
241
242     public void setProperty( DavProperty property )
243         throws DavException
244     {
245     }
246
247     public void removeProperty( DavPropertyName propertyName )
248         throws DavException
249     {
250     }
251
252     public MultiStatusResponse alterProperties( DavPropertySet setProperties, DavPropertyNameSet removePropertyNames )
253         throws DavException
254     {
255         return null;
256     }
257
258     @SuppressWarnings("unchecked")
259     public MultiStatusResponse alterProperties( List changeList )
260         throws DavException
261     {
262         return null;
263     }
264
265     public DavResource getCollection()
266     {
267         DavResource parent = null;
268         if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
269         {
270             String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
271             if ( parentPath.equals( "" ) )
272             {
273                 parentPath = "/";
274             }
275             DavResourceLocator parentloc = locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
276             try
277             {
278                 parent = factory.createResource( parentloc, session );
279             }
280             catch ( DavException e )
281             {
282                 // should not occur
283             }
284         }
285         return parent;
286     }
287
288     public void addMember( DavResource resource, InputContext inputContext )
289         throws DavException
290     {
291         File localFile = new File( localResource, resource.getDisplayName() );
292         boolean exists = localFile.exists();
293
294         if ( isCollection() && inputContext.hasStream() ) // New File
295         {
296             FileOutputStream stream = null;
297             try
298             {
299                 stream = new FileOutputStream( localFile );
300                 IOUtils.copy( inputContext.getInputStream(), stream );
301             }
302             catch ( IOException e )
303             {
304                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
305             }
306             finally
307             {
308                 IOUtils.closeQuietly( stream );
309             }
310             
311             // TODO: a bad deployment shouldn't delete an existing file - do we need to write to a temporary location first?
312             if ( inputContext.getContentLength() != localFile.length() )
313             {
314                 FileUtils.deleteQuietly( localFile );
315                 
316                 throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Content Header length was " +
317                     inputContext.getContentLength() + " but was " + localFile.length() );
318             }
319             
320             queueRepositoryTask( localFile );           
321             
322             log.debug( "File '" + resource.getDisplayName() + ( exists ? "' modified " : "' created ") + "(current user '" + this.principal + "')" );
323             
324             triggerAuditEvent( resource, exists ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE );
325         }
326         else if ( !inputContext.hasStream() && isCollection() ) // New directory
327         {
328             localFile.mkdir();
329             
330             log.debug( "Directory '" + resource.getDisplayName() + "' (current user '" + this.principal + "')" );
331             
332             triggerAuditEvent( resource, AuditEvent.CREATE_DIR );
333         }
334         else
335         {            
336             throw new DavException( HttpServletResponse.SC_BAD_REQUEST, "Could not write member " +
337                 resource.getResourcePath() + " at " + getResourcePath() );
338         }
339     }
340
341     public DavResourceIterator getMembers()
342     {
343         List<DavResource> list = new ArrayList<DavResource>();
344         if ( exists() && isCollection() )
345         {
346             for ( String item : localResource.list() )
347             {
348                 try
349                 {
350                     if ( !item.startsWith( HIDDEN_PATH_PREFIX ) )
351                     {
352                         String path = locator.getResourcePath() + '/' + item;
353                         DavResourceLocator resourceLocator =
354                             locator.getFactory().createResourceLocator( locator.getPrefix(), path );
355                         DavResource resource = factory.createResource( resourceLocator, session );
356                         
357                         if ( resource != null )
358                         {
359                             list.add( resource );
360                         }
361                         log.debug( "Resource '" + item + "' retrieved by '" + this.principal + "'" );
362                     }
363                 }
364                 catch ( DavException e )
365                 {
366                     // Should not occur
367                 }
368             }
369         }
370         return new DavResourceIteratorImpl( list );
371     }
372
373     public void removeMember( DavResource member )
374         throws DavException
375     {
376         File resource = checkDavResourceIsArchivaDavResource( member ).getLocalResource();
377         
378         if ( resource.exists() )
379         {
380             try
381             {
382                 if ( resource.isDirectory() )
383                 {
384                     FileUtils.deleteDirectory( resource );
385
386                     triggerAuditEvent( member, AuditEvent.REMOVE_DIR );
387                 }
388                 else
389                 {
390                     if ( !resource.delete() )
391                     {
392                         throw new IOException( "Could not remove file" );
393                     }
394
395                     triggerAuditEvent( member, AuditEvent.REMOVE_FILE );
396                 }
397                 log.debug( ( resource.isDirectory() ? "Directory '" : "File '" ) + member.getDisplayName() + "' removed (current user '" + this.principal + "')" );
398             }
399             catch ( IOException e )
400             {
401                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
402             }
403         }
404         else
405         {
406             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
407         }
408     }
409
410     private void triggerAuditEvent( DavResource member, String event ) throws DavException
411     {
412         String path = logicalResource + "/" + member.getDisplayName();
413         
414         triggerAuditEvent( checkDavResourceIsArchivaDavResource( member ).remoteAddr, locator.getRepositoryId(), path,
415                            event );
416     }
417
418     public void move( DavResource destination )
419         throws DavException
420     {
421         if ( !exists() )
422         {
423             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
424         }
425
426         try
427         {
428             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
429             if ( isCollection() )
430             {
431                 FileUtils.moveDirectory( getLocalResource(), resource.getLocalResource() );
432
433                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_DIRECTORY );
434             }
435             else
436             {
437                 FileUtils.moveFile( getLocalResource(), resource.getLocalResource() );
438
439                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.MOVE_FILE );
440             }
441             
442             log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' moved to '" +
443                            destination + "' (current user '" + this.principal + "')" );
444         }
445         catch ( IOException e )
446         {
447             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
448         }
449     }
450
451     public void copy( DavResource destination, boolean shallow )
452         throws DavException
453     {
454         if ( !exists() )
455         {
456             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource to copy does not exist." );
457         }
458
459         if ( shallow && isCollection() )
460         {
461             throw new DavException( DavServletResponse.SC_FORBIDDEN, "Unable to perform shallow copy for collection" );
462         }
463
464         try
465         {
466             ArchivaDavResource resource = checkDavResourceIsArchivaDavResource( destination );
467             if ( isCollection() )
468             {
469                 FileUtils.copyDirectory( getLocalResource(), resource.getLocalResource() );
470
471                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_DIRECTORY );
472             }
473             else
474             {
475                 FileUtils.copyFile( getLocalResource(), resource.getLocalResource() );
476
477                 triggerAuditEvent( remoteAddr, locator.getRepositoryId(), logicalResource, AuditEvent.COPY_FILE );
478             }
479             log.debug( ( isCollection() ? "Directory '" : "File '" ) + getLocalResource().getName() + "' copied to '" +
480                            destination + "' (current user '" + this.principal + "')" );
481         }
482         catch ( IOException e )
483         {
484             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
485         }
486     }
487
488     public boolean isLockable( Type type, Scope scope )
489     {
490         return Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope);
491     }
492
493     public boolean hasLock( Type type, Scope scope )
494     {
495         return getLock(type, scope) != null;
496     }
497
498     public ActiveLock getLock( Type type, Scope scope )
499     {
500         ActiveLock lock = null;
501         if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope)) 
502         {
503             lock = lockManager.getLock(type, scope, this);
504         }
505         return lock;
506     }
507
508     public ActiveLock[] getLocks()
509     {
510         ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
511         return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
512     }
513
514     public ActiveLock lock( LockInfo lockInfo )
515         throws DavException
516     {
517         ActiveLock lock = null;
518         if (isLockable(lockInfo.getType(), lockInfo.getScope())) 
519         {
520             lock = lockManager.createLock(lockInfo, this);
521         }
522         else 
523         {
524             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
525         }
526         return lock;
527     }
528
529     public ActiveLock refreshLock( LockInfo lockInfo, String lockToken )
530         throws DavException
531     {
532         if (!exists()) {
533             throw new DavException(DavServletResponse.SC_NOT_FOUND);
534         }
535         ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
536         if (lock == null) {
537             throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
538         }
539
540         lock = lockManager.refreshLock(lockInfo, lockToken, this);
541
542         return lock;
543     }
544
545     public void unlock( String lockToken )
546         throws DavException
547     {
548         ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
549         if (lock == null)
550         {
551             throw new DavException(HttpServletResponse.SC_PRECONDITION_FAILED);
552         }
553         else if (lock.isLockedByToken(lockToken))
554         {
555             lockManager.releaseLock(lockToken, this);
556         }
557         else
558         {
559             throw new DavException(DavServletResponse.SC_LOCKED);
560         }
561     }
562
563     public void addLockManager( LockManager lockManager )
564     {
565         this.lockManager = lockManager;
566     }
567
568     public DavResourceFactory getFactory()
569     {
570         return factory;
571     }
572
573     public DavSession getSession()
574     {
575         return session;
576     }
577
578     /**
579      * Fill the set of properties
580      */
581     protected DavPropertySet initProperties()
582     {
583         if ( !exists() )
584         {
585             properties = new DavPropertySet();
586         }
587         
588         if ( properties != null )
589         {
590             return properties;
591         }
592
593         DavPropertySet properties = new DavPropertySet();
594         
595         // set (or reset) fundamental properties
596         if ( getDisplayName() != null )
597         {
598             properties.add( new DefaultDavProperty( DavPropertyName.DISPLAYNAME, getDisplayName() ) );
599         }
600         if ( isCollection() )
601         {
602             properties.add( new ResourceType( ResourceType.COLLECTION ) );
603             // Windows XP support
604             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "1" ) );
605         }
606         else
607         {
608             properties.add( new ResourceType( ResourceType.DEFAULT_RESOURCE ) );
609
610             // Windows XP support
611             properties.add( new DefaultDavProperty( DavPropertyName.ISCOLLECTION, "0" ) );
612         }
613
614         // Need to get the ISO8601 date for properties
615         DateTime dt = new DateTime( localResource.lastModified() );
616         DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
617         String modifiedDate = fmt.print( dt );
618
619         properties.add( new DefaultDavProperty( DavPropertyName.GETLASTMODIFIED, modifiedDate ) );
620
621         properties.add( new DefaultDavProperty( DavPropertyName.CREATIONDATE, modifiedDate ) );
622
623         properties.add( new DefaultDavProperty( DavPropertyName.GETCONTENTLENGTH, localResource.length() ) );
624         
625         this.properties = properties;
626         
627         return properties;
628     }
629
630     private ArchivaDavResource checkDavResourceIsArchivaDavResource( DavResource resource )
631         throws DavException
632     {
633         if ( !( resource instanceof ArchivaDavResource ) )
634         {
635             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
636                                     "DavResource is not instance of ArchivaDavResource" );
637         }
638         return (ArchivaDavResource) resource;
639     }
640
641     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action )
642     {
643         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
644         event.setRemoteIP( remoteIP );
645
646         for ( AuditListener listener : auditListeners )
647         {
648             listener.auditEvent( event );
649         }
650         
651         // identify as artifact deployment/upload
652         if( action.equals( AuditEvent.CREATE_FILE ) )
653         {
654             action = AuditEvent.UPLOAD_FILE;
655         }
656         
657         String user = principal;
658         if( principal == null )
659         {
660             user = "guest";
661         }
662         
663         ArchivaAuditLogs auditLogs = new ArchivaAuditLogs();
664         auditLogs.setArtifact( resource );
665         auditLogs.setEvent( action );
666         auditLogs.setEventDate( Calendar.getInstance().getTime() );
667         auditLogs.setRepositoryId( repositoryId );
668         auditLogs.setUsername( user );
669         
670         auditLogsDao.saveAuditLogs( auditLogs );
671     }
672     
673     private void queueRepositoryTask( File localFile )
674     {        
675         RepositoryTask task = TaskCreator.createRepositoryTask( repository.getId(), localFile, false, true );
676         
677         try
678         {
679             scheduler.queueRepositoryTask( task );
680         }
681         catch ( TaskQueueException e )
682         {
683             log.error( "Unable to queue repository task to execute consumers on resource file ['" +
684                 localFile.getName() + "']." );
685         }
686     }
687 }