]> source.dussan.org Git - archiva.git/blob
730371db3f35017b175856fb9c13de633820711e
[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.FileNotFoundException;
24 import java.io.FileReader;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.jackrabbit.webdav.DavException;
34 import org.apache.jackrabbit.webdav.DavResource;
35 import org.apache.jackrabbit.webdav.DavResourceFactory;
36 import org.apache.jackrabbit.webdav.DavResourceLocator;
37 import org.apache.jackrabbit.webdav.DavServletRequest;
38 import org.apache.jackrabbit.webdav.DavServletResponse;
39 import org.apache.jackrabbit.webdav.DavSession;
40 import org.apache.jackrabbit.webdav.lock.LockManager;
41 import org.apache.jackrabbit.webdav.lock.SimpleLockManager;
42 import org.apache.maven.archiva.common.utils.PathUtil;
43 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
44 import org.apache.maven.archiva.configuration.RepositoryGroupConfiguration;
45 import org.apache.maven.archiva.model.ArchivaRepositoryMetadata;
46 import org.apache.maven.archiva.model.ArtifactReference;
47 import org.apache.maven.archiva.policies.ProxyDownloadException;
48 import org.apache.maven.archiva.proxy.RepositoryProxyConnectors;
49 import org.apache.maven.archiva.repository.ManagedRepositoryContent;
50 import org.apache.maven.archiva.repository.RepositoryContentFactory;
51 import org.apache.maven.archiva.repository.RepositoryException;
52 import org.apache.maven.archiva.repository.RepositoryNotFoundException;
53 import org.apache.maven.archiva.repository.audit.AuditEvent;
54 import org.apache.maven.archiva.repository.audit.AuditListener;
55 import org.apache.maven.archiva.repository.audit.Auditable;
56 import org.apache.maven.archiva.repository.content.RepositoryRequest;
57 import org.apache.maven.archiva.repository.layout.LayoutException;
58 import org.apache.maven.archiva.repository.metadata.MetadataTools;
59 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataException;
60 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataMerge;
61 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataReader;
62 import org.apache.maven.archiva.repository.metadata.RepositoryMetadataWriter;
63 import org.apache.maven.archiva.repository.scanner.RepositoryContentConsumers;
64 import org.apache.maven.archiva.scheduled.ArchivaTaskScheduler;
65 import org.apache.maven.archiva.security.ServletAuthenticator;
66 import org.apache.maven.archiva.webdav.util.MimeTypes;
67 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
68 import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
69 import org.apache.maven.model.DistributionManagement;
70 import org.apache.maven.model.Model;
71 import org.apache.maven.model.Relocation;
72 import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
73 import org.codehaus.plexus.digest.ChecksumFile;
74 import org.codehaus.plexus.digest.Digester;
75 import org.codehaus.plexus.digest.DigesterException;
76 import org.codehaus.plexus.redback.authentication.AuthenticationException;
77 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
78 import org.codehaus.plexus.redback.authorization.AuthorizationException;
79 import org.codehaus.plexus.redback.authorization.UnauthorizedException;
80 import org.codehaus.plexus.redback.policy.AccountLockedException;
81 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
82 import org.codehaus.plexus.redback.system.SecuritySession;
83 import org.codehaus.plexus.redback.users.User;
84 import org.codehaus.plexus.redback.users.UserManager;
85 import org.codehaus.plexus.taskqueue.execution.TaskExecutor;
86 import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor;
87 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
88 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91
92 /**
93  * @plexus.component role="org.apache.maven.archiva.webdav.ArchivaDavResourceFactory"
94  */
95 public class ArchivaDavResourceFactory
96     implements DavResourceFactory, Auditable
97 {
98     private static final String PROXIED_SUFFIX = " (proxied)";
99
100     private static final String HTTP_PUT_METHOD = "PUT";
101
102     private Logger log = LoggerFactory.getLogger( ArchivaDavResourceFactory.class );
103
104     /**
105      * @plexus.requirement role="org.apache.maven.archiva.repository.audit.AuditListener"
106      */
107     private List<AuditListener> auditListeners = new ArrayList<AuditListener>();
108
109     /**
110      * @plexus.requirement
111      */
112     private RepositoryContentFactory repositoryFactory;
113
114     /**
115      * @plexus.requirement
116      */
117     private RepositoryRequest repositoryRequest;
118
119     /**
120      * @plexus.requirement role-hint="default"
121      */
122     private RepositoryProxyConnectors connectors;
123
124     /**
125      * @plexus.requirement
126      */
127     private MetadataTools metadataTools;
128
129     /**
130      * @plexus.requirement
131      */
132     private MimeTypes mimeTypes;
133
134     /**
135      * @plexus.requirement
136      */
137     private ArchivaConfiguration archivaConfiguration;
138
139     /**
140      * @plexus.requirement
141      */
142     private ServletAuthenticator servletAuth;
143
144     /**
145      * @plexus.requirement role-hint="basic"
146      */
147     private HttpAuthenticator httpAuth;
148
149     /**
150      * Lock Manager - use simple implementation from JackRabbit
151      */
152     private final LockManager lockManager = new SimpleLockManager();
153
154     /**
155      * @plexus.requirement
156      */
157     private RepositoryContentConsumers consumers;
158
159     /**
160      * @plexus.requirement
161      */
162     private ChecksumFile checksum;
163
164     /**
165      * @plexus.requirement role-hint="sha1"
166      */
167     private Digester digestSha1;
168
169     /**
170      * @plexus.requirement role-hint="md5";
171      */
172     private Digester digestMd5;
173     
174     /**
175      * @plexus.requirement role-hint="repository-scanning"
176      */
177     private TaskExecutor taskExecutor;
178     
179     /**
180      * @plexus.requirement
181      */
182     private ArchivaTaskScheduler scheduler;
183     
184     /**
185      * @plexus.requirement role-hint="repository-scanning"
186      */
187     private TaskQueueExecutor repoScanningTaskQueueExecutor;
188
189     public DavResource createResource( final DavResourceLocator locator, final DavServletRequest request,
190                                        final DavServletResponse response )
191         throws DavException
192     {
193         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
194
195         RepositoryGroupConfiguration repoGroupConfig =
196             archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
197
198         String activePrincipal = getActivePrincipal( request );
199
200         List<String> resourcesInAbsolutePath = new ArrayList<String>();
201
202         boolean readMethod = WebdavMethodUtil.isReadMethod( request.getMethod() );
203         DavResource resource;
204         if ( repoGroupConfig != null )
205         {
206             if ( !readMethod )
207             {
208                 throw new DavException( HttpServletResponse.SC_METHOD_NOT_ALLOWED,
209                                         "Write method not allowed for repository groups." );
210             }
211
212             // handle browse requests for virtual repos
213             if ( RepositoryPathUtil.getLogicalResource( archivaLocator.getOrigResourcePath() ).endsWith( "/" ) )
214             {
215                 return getResource( request, repoGroupConfig.getRepositories(), archivaLocator );
216             }
217             else
218             {
219                 resource =
220                     processRepositoryGroup( request, archivaLocator, repoGroupConfig.getRepositories(),
221                                             activePrincipal, resourcesInAbsolutePath );
222             }
223         }
224         else
225         {
226             ManagedRepositoryContent managedRepository = null;
227
228             try
229             {
230                 managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
231             }
232             catch ( RepositoryNotFoundException e )
233             {
234                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
235                     + archivaLocator.getRepositoryId() );
236             }
237             catch ( RepositoryException e )
238             {
239                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
240             }
241
242             resource = processRepository( request, archivaLocator, activePrincipal, managedRepository );
243
244             String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
245             resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
246         }
247
248         String requestedResource = request.getRequestURI();
249
250         // MRM-872 : merge all available metadata
251         // merge metadata only when requested via the repo group
252         if ( ( repositoryRequest.isMetadata( requestedResource ) || ( requestedResource.endsWith( "metadata.xml.sha1" ) || requestedResource.endsWith( "metadata.xml.md5" ) ) )
253             && repoGroupConfig != null )
254         {
255             // this should only be at the project level not version level!
256             if ( isProjectReference( requestedResource ) )
257             {
258                 String artifactId = StringUtils.substringBeforeLast( requestedResource.replace( '\\', '/' ), "/" );
259                 artifactId = StringUtils.substringAfterLast( artifactId, "/" );
260
261                 ArchivaDavResource res = (ArchivaDavResource) resource;
262                 String filePath =
263                     StringUtils.substringBeforeLast( res.getLocalResource().getAbsolutePath().replace( '\\', '/' ), "/" );
264                 filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";
265
266                 // for MRM-872 handle checksums of the merged metadata files
267                 if ( repositoryRequest.isSupportFile( requestedResource ) )
268                 {
269                     File metadataChecksum =
270                         new File( filePath + "." + StringUtils.substringAfterLast( requestedResource, "." ) );
271                     if ( metadataChecksum.exists() )
272                     {
273                         LogicalResource logicalResource =
274                             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
275
276                         resource =
277                             new ArchivaDavResource( metadataChecksum.getAbsolutePath(), logicalResource.getPath(),
278                                                     null, request.getRemoteAddr(), activePrincipal,
279                                                     request.getDavSession(), archivaLocator, this, mimeTypes,
280                                                     auditListeners, scheduler );
281                     }
282                 }
283                 else
284                 {
285                     if ( resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1 )
286                     {
287                         // merge the metadata of all repos under group
288                         ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
289                         for ( String resourceAbsPath : resourcesInAbsolutePath )
290                         {
291                             try
292                             {
293                                 File metadataFile = new File( resourceAbsPath );
294                                 ArchivaRepositoryMetadata repoMetadata = RepositoryMetadataReader.read( metadataFile );
295                                 mergedMetadata = RepositoryMetadataMerge.merge( mergedMetadata, repoMetadata );
296                             }
297                             catch ( RepositoryMetadataException r )
298                             {
299                                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
300                                                         "Error occurred while reading metadata file." );
301                             }
302                         }
303
304                         try
305                         {
306                             File resourceFile = writeMergedMetadataToFile( mergedMetadata, filePath );
307
308                             LogicalResource logicalResource =
309                                 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
310
311                             resource =
312                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
313                                                         null, request.getRemoteAddr(), activePrincipal,
314                                                         request.getDavSession(), archivaLocator, this, mimeTypes,
315                                                         auditListeners, scheduler );
316                         }
317                         catch ( RepositoryMetadataException r )
318                         {
319                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
320                                                     "Error occurred while writing metadata file." );
321                         }
322                         catch ( IOException ie )
323                         {
324                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
325                                                     "Error occurred while generating checksum files." );
326                         }
327                         catch ( DigesterException de )
328                         {
329                             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
330                                                     "Error occurred while generating checksum files." );
331                         }
332                     }
333                 }
334             }
335         }
336
337         setHeaders( response, locator, resource );
338
339         // compatibility with MRM-440 to ensure browsing the repository works ok
340         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
341         {
342             throw new BrowserRedirectException( resource.getHref() );
343         }
344         resource.addLockManager( lockManager );
345         return resource;
346     }
347
348     private DavResource processRepositoryGroup( final DavServletRequest request,
349                                                 ArchivaDavResourceLocator archivaLocator, List<String> repositories,
350                                                 String activePrincipal, List<String> resourcesInAbsolutePath )
351         throws DavException
352     {
353         DavResource resource = null;
354         DavException storedException = null;
355
356         for ( String repositoryId : repositories )
357         {
358             ManagedRepositoryContent managedRepository = null;
359
360             try
361             {
362                 managedRepository = repositoryFactory.getManagedRepositoryContent( repositoryId );
363             }
364             catch ( RepositoryNotFoundException e )
365             {
366                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
367             }
368             catch ( RepositoryException e )
369             {
370                 throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
371             }
372
373             try
374             {
375                 DavResource updatedResource =
376                     processRepository( request, archivaLocator, activePrincipal, managedRepository );
377                 if ( resource == null )
378                 {
379                     resource = updatedResource;
380                 }
381
382                 String logicalResource = RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() );
383                 resourcesInAbsolutePath.add( new File( managedRepository.getRepoRoot(), logicalResource ).getAbsolutePath() );
384             }
385             catch ( DavException e )
386             {
387                 storedException = e;
388             }
389         }
390
391         if ( resource == null )
392         {
393             if ( storedException != null )
394             {
395                 throw storedException;
396             }
397             else
398             {
399                 throw new DavException( HttpServletResponse.SC_NOT_FOUND );
400             }
401         }
402         return resource;
403     }
404
405     private DavResource processRepository( final DavServletRequest request, ArchivaDavResourceLocator archivaLocator,
406                                            String activePrincipal, ManagedRepositoryContent managedRepository )
407         throws DavException
408     {
409         DavResource resource = null;
410         if ( isAuthorized( request, managedRepository.getId() ) )
411         {
412             LogicalResource logicalResource =
413                 new LogicalResource( RepositoryPathUtil.getLogicalResource( archivaLocator.getResourcePath() ) );
414
415             File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
416             resource =
417                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
418                                         managedRepository.getRepository(), request.getRemoteAddr(), activePrincipal,
419                                         request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners,
420                                         scheduler );
421
422             if ( WebdavMethodUtil.isReadMethod( request.getMethod() ) )
423             {
424                 if ( archivaLocator.getHref( false ).endsWith( "/" ) && !resourceFile.isDirectory() )
425                 {
426                     // force a resource not found
427                     throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
428                 }
429                 else
430                 {
431                     if ( !resource.isCollection() )
432                     {
433                         boolean previouslyExisted = resourceFile.exists();
434
435                         // Attempt to fetch the resource from any defined proxy.
436                         boolean fromProxy = fetchContentFromProxies( managedRepository, request, logicalResource );
437
438                         // At this point the incoming request can either be in default or
439                         // legacy layout format.
440                         try
441                         {
442                             // Perform an adjustment of the resource to the managed
443                             // repository expected path.
444                             String localResourcePath =
445                                 repositoryRequest.toNativePath( logicalResource.getPath(), managedRepository );
446                             resourceFile = new File( managedRepository.getRepoRoot(), localResourcePath );
447                             resource =
448                                 new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
449                                                         managedRepository.getRepository(), request.getRemoteAddr(),
450                                                         activePrincipal, request.getDavSession(), archivaLocator, this,
451                                                         mimeTypes, auditListeners, scheduler );
452                         }
453                         catch ( LayoutException e )
454                         {
455                             if ( !resourceFile.exists() )
456                             {
457                                 throw new DavException( HttpServletResponse.SC_NOT_FOUND, e );
458                             }
459                         }
460
461                         if ( fromProxy )
462                         {
463                             String event =
464                                 ( previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE )
465                                     + PROXIED_SUFFIX;
466                             triggerAuditEvent( request.getRemoteAddr(), archivaLocator.getRepositoryId(),
467                                                logicalResource.getPath(), event, activePrincipal );
468                         }
469
470                         if ( !resourceFile.exists() )
471                         {
472                             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
473                         }
474                     }
475                 }
476             }
477
478             if ( request.getMethod().equals( HTTP_PUT_METHOD ) )
479             {
480                 /*
481                  * Create parent directories that don't exist when writing a file This actually makes this
482                  * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the
483                  * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly
484                  * create the collections themselves.
485                  */
486
487                 File rootDirectory = new File( managedRepository.getRepoRoot() );
488                 File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
489
490                 if ( !destDir.exists() )
491                 {
492                     destDir.mkdirs();
493                     String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
494                     triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath,
495                                        AuditEvent.CREATE_DIR, activePrincipal );
496                 }
497             }
498         }
499         return resource;
500     }
501
502     public DavResource createResource( final DavResourceLocator locator, final DavSession davSession )
503         throws DavException
504     {
505         ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator( locator );
506
507         ManagedRepositoryContent managedRepository;
508         try
509         {
510             managedRepository = repositoryFactory.getManagedRepositoryContent( archivaLocator.getRepositoryId() );
511         }
512         catch ( RepositoryNotFoundException e )
513         {
514             throw new DavException( HttpServletResponse.SC_NOT_FOUND, "Invalid repository: "
515                 + archivaLocator.getRepositoryId() );
516         }
517         catch ( RepositoryException e )
518         {
519             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e );
520         }
521
522         String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
523         File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource );
524         DavResource resource =
525             new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource, managedRepository.getRepository(),
526                                     davSession, archivaLocator, this, mimeTypes, auditListeners, scheduler );
527
528         resource.addLockManager( lockManager );
529         return resource;
530     }
531
532     private boolean fetchContentFromProxies( ManagedRepositoryContent managedRepository, DavServletRequest request,
533                                              LogicalResource resource )
534         throws DavException
535     {
536         String path = resource.getPath();
537         if ( repositoryRequest.isSupportFile( path ) )
538         {
539             File proxiedFile = connectors.fetchFromProxies( managedRepository, path );
540
541             return ( proxiedFile != null );
542         }
543
544         // Is it a Metadata resource?
545         if ( repositoryRequest.isDefault( path ) && repositoryRequest.isMetadata( path ) )
546         {
547             return connectors.fetchMetatadaFromProxies( managedRepository, path ) != null;
548         }
549
550         // Not any of the above? Then it's gotta be an artifact reference.
551         try
552         {
553             // Get the artifact reference in a layout neutral way.
554             ArtifactReference artifact = repositoryRequest.toArtifactReference( path );
555
556             if ( artifact != null )
557             {
558                 applyServerSideRelocation( managedRepository, artifact );
559
560                 File proxiedFile = connectors.fetchFromProxies( managedRepository, artifact );
561
562                 resource.setPath( managedRepository.toPath( artifact ) );
563
564                 return ( proxiedFile != null );
565             }
566         }
567         catch ( LayoutException e )
568         {
569             /* eat it */
570         }
571         catch ( ProxyDownloadException e )
572         {
573             log.error( e.getMessage(), e );
574             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to fetch artifact resource." );
575         }
576         return false;
577     }
578
579     /**
580      * A relocation capable client will request the POM prior to the artifact, and will then read meta-data and do
581      * client side relocation. A simplier client (like maven 1) will only request the artifact and not use the
582      * metadatas.
583      * <p>
584      * For such clients, archiva does server-side relocation by reading itself the &lt;relocation&gt; element in
585      * metadatas and serving the expected artifact.
586      */
587     protected void applyServerSideRelocation( ManagedRepositoryContent managedRepository, ArtifactReference artifact )
588         throws ProxyDownloadException
589     {
590         if ( "pom".equals( artifact.getType() ) )
591         {
592             return;
593         }
594
595         // Build the artifact POM reference
596         ArtifactReference pomReference = new ArtifactReference();
597         pomReference.setGroupId( artifact.getGroupId() );
598         pomReference.setArtifactId( artifact.getArtifactId() );
599         pomReference.setVersion( artifact.getVersion() );
600         pomReference.setType( "pom" );
601
602         // Get the artifact POM from proxied repositories if needed
603         connectors.fetchFromProxies( managedRepository, pomReference );
604
605         // Open and read the POM from the managed repo
606         File pom = managedRepository.toFile( pomReference );
607
608         if ( !pom.exists() )
609         {
610             return;
611         }
612
613         try
614         {
615             // MavenXpp3Reader leaves the file open, so we need to close it ourselves.
616             FileReader reader = new FileReader( pom );
617             Model model = null;
618             try
619             {
620                 model = new MavenXpp3Reader().read( reader );
621             }
622             finally
623             {
624                 if ( reader != null )
625                 {
626                     reader.close();
627                 }
628             }
629
630             DistributionManagement dist = model.getDistributionManagement();
631             if ( dist != null )
632             {
633                 Relocation relocation = dist.getRelocation();
634                 if ( relocation != null )
635                 {
636                     // artifact is relocated : update the repositoryPath
637                     if ( relocation.getGroupId() != null )
638                     {
639                         artifact.setGroupId( relocation.getGroupId() );
640                     }
641                     if ( relocation.getArtifactId() != null )
642                     {
643                         artifact.setArtifactId( relocation.getArtifactId() );
644                     }
645                     if ( relocation.getVersion() != null )
646                     {
647                         artifact.setVersion( relocation.getVersion() );
648                     }
649                 }
650             }
651         }
652         catch ( FileNotFoundException e )
653         {
654             // Artifact has no POM in repo : ignore
655         }
656         catch ( IOException e )
657         {
658             // Unable to read POM : ignore.
659         }
660         catch ( XmlPullParserException e )
661         {
662             // Invalid POM : ignore
663         }
664     }
665
666     // TODO: remove?
667     private void triggerAuditEvent( String remoteIP, String repositoryId, String resource, String action,
668                                     String principal )
669     {
670         AuditEvent event = new AuditEvent( repositoryId, principal, resource, action );
671         event.setRemoteIP( remoteIP );
672
673         for ( AuditListener listener : auditListeners )
674         {
675             listener.auditEvent( event );
676         }
677     }
678
679     public void addAuditListener( AuditListener listener )
680     {
681         this.auditListeners.add( listener );
682     }
683
684     public void clearAuditListeners()
685     {
686         this.auditListeners.clear();
687     }
688
689     public void removeAuditListener( AuditListener listener )
690     {
691         this.auditListeners.remove( listener );
692     }
693
694     private void setHeaders( DavServletResponse response, DavResourceLocator locator, DavResource resource )
695     {
696         // [MRM-503] - Metadata file need Pragma:no-cache response
697         // header.
698         if ( locator.getResourcePath().endsWith( "/maven-metadata.xml" ) )
699         {
700             response.addHeader( "Pragma", "no-cache" );
701             response.addHeader( "Cache-Control", "no-cache" );
702         }
703
704         // We need to specify this so connecting wagons can work correctly
705         response.addDateHeader( "last-modified", resource.getModificationTime() );
706
707         // TODO: [MRM-524] determine http caching options for other types of files (artifacts, sha1, md5, snapshots)
708     }
709
710     private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator( DavResourceLocator locator )
711         throws DavException
712     {
713         if ( !( locator instanceof ArchivaDavResourceLocator ) )
714         {
715             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
716                                     "Locator does not implement RepositoryLocator" );
717         }
718
719         // Hidden paths
720         if ( locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
721         {
722             throw new DavException( HttpServletResponse.SC_NOT_FOUND );
723         }
724
725         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
726
727         // MRM-419 - Windows Webdav support. Should not 404 if there is no content.
728         if ( StringUtils.isEmpty( archivaLocator.getRepositoryId() ) )
729         {
730             throw new DavException( HttpServletResponse.SC_NO_CONTENT );
731         }
732         return archivaLocator;
733     }
734
735     private static class LogicalResource
736     {
737         private String path;
738
739         public LogicalResource( String path )
740         {
741             this.path = path;
742         }
743
744         public String getPath()
745         {
746             return path;
747         }
748
749         public void setPath( String path )
750         {
751             this.path = path;
752         }
753     }
754
755     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
756         throws DavException
757     {
758         try
759         {
760             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
761             SecuritySession securitySession = httpAuth.getSecuritySession( request.getSession( true ) );
762
763             return servletAuth.isAuthenticated( request, result )
764                 && servletAuth.isAuthorized( request, securitySession, repositoryId,
765                                              WebdavMethodUtil.getMethodPermission( request.getMethod() ) );
766         }
767         catch ( AuthenticationException e )
768         {
769             // safety check for MRM-911
770             String guest = UserManager.GUEST_USERNAME;
771             try
772             {
773                 if ( servletAuth.isAuthorized(
774                                                guest,
775                                                ( (ArchivaDavResourceLocator) request.getRequestLocator() ).getRepositoryId(),
776                                                WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
777                 {
778                     return true;
779                 }
780             }
781             catch ( UnauthorizedException ae )
782             {
783                 throw new UnauthorizedDavException( repositoryId,
784                                                     "You are not authenticated and authorized to access any repository." );
785             }
786
787             throw new UnauthorizedDavException( repositoryId, "You are not authenticated" );
788         }
789         catch ( MustChangePasswordException e )
790         {
791             throw new UnauthorizedDavException( repositoryId, "You must change your password." );
792         }
793         catch ( AccountLockedException e )
794         {
795             throw new UnauthorizedDavException( repositoryId, "User account is locked." );
796         }
797         catch ( AuthorizationException e )
798         {
799             throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
800                                     "Fatal Authorization Subsystem Error." );
801         }
802         catch ( UnauthorizedException e )
803         {
804             throw new UnauthorizedDavException( repositoryId, e.getMessage() );
805         }
806     }
807
808     private DavResource getResource( DavServletRequest request, List<String> repositories,
809                                      ArchivaDavResourceLocator locator )
810         throws DavException
811     {
812         List<File> mergedRepositoryContents = new ArrayList<File>();
813         LogicalResource logicalResource =
814             new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
815
816         // flow:
817         // if the current user logged in has permission to any of the repositories, allow user to
818         // browse the repo group but displaying only the repositories which the user has permission to access.
819         // otherwise, prompt for authentication.
820
821         String activePrincipal = getActivePrincipal( request );
822
823         boolean allow = isAllowedToContinue( request, repositories, activePrincipal );
824
825         if ( allow )
826         {
827             for ( String repository : repositories )
828             {
829                 ManagedRepositoryContent managedRepository = null;
830
831                 try
832                 {
833                     managedRepository = repositoryFactory.getManagedRepositoryContent( repository );
834                 }
835                 catch ( RepositoryNotFoundException e )
836                 {
837                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
838                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
839                 }
840                 catch ( RepositoryException e )
841                 {
842                     throw new DavException( HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
843                                             "Invalid managed repository <" + repository + ">: " + e.getMessage() );
844                 }
845
846                 File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
847                 if ( resourceFile.exists() )
848                 {
849                     // for prompted authentication
850                     if ( httpAuth.getSecuritySession( request.getSession( true ) ) != null )
851                     {
852                         try
853                         {
854                             if ( isAuthorized( request, repository ) )
855                             {
856                                 mergedRepositoryContents.add( resourceFile );
857                             }
858                         }
859                         catch ( DavException e )
860                         {
861                             // TODO: review exception handling
862                             log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
863                                 + "': " + e.getMessage() );
864                         }
865                     }
866                     else
867                     {
868                         // for the current user logged in
869                         try
870                         {
871                             if ( servletAuth.isAuthorized( activePrincipal, repository,
872                                                            WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
873                             {
874                                 mergedRepositoryContents.add( resourceFile );
875                             }
876                         }
877                         catch ( UnauthorizedException e )
878                         {
879                             // TODO: review exception handling
880                             log.debug( "Skipping repository '" + managedRepository + "' for user '" + activePrincipal
881                                 + "': " + e.getMessage() );
882                         }
883                     }
884                 }
885             }
886         }
887         else
888         {
889             throw new UnauthorizedDavException( locator.getRepositoryId(), "User not authorized." );
890         }
891
892         ArchivaVirtualDavResource resource =
893             new ArchivaVirtualDavResource( mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator,
894                                            this );
895
896         // compatibility with MRM-440 to ensure browsing the repository group works ok
897         if ( resource.isCollection() && !request.getRequestURI().endsWith( "/" ) )
898         {
899             throw new BrowserRedirectException( resource.getHref() );
900         }
901
902         return resource;
903     }
904
905     private String getActivePrincipal( DavServletRequest request )
906     {
907         User sessionUser = httpAuth.getSessionUser( request.getSession() );
908         return sessionUser != null ? sessionUser.getUsername() : UserManager.GUEST_USERNAME;
909     }
910
911     /**
912      * Check if the current user is authorized to access any of the repos
913      * 
914      * @param request
915      * @param repositories
916      * @param activePrincipal
917      * @return
918      */
919     private boolean isAllowedToContinue( DavServletRequest request, List<String> repositories, String activePrincipal )
920     {
921         boolean allow = false;
922
923         // if securitySession != null, it means that the user was prompted for authentication
924         if ( httpAuth.getSecuritySession( request.getSession() ) != null )
925         {
926             for ( String repository : repositories )
927             {
928                 try
929                 {
930                     if ( isAuthorized( request, repository ) )
931                     {
932                         allow = true;
933                         break;
934                     }
935                 }
936                 catch ( DavException e )
937                 {
938                     continue;
939                 }
940             }
941         }
942         else
943         {
944             for ( String repository : repositories )
945             {
946                 try
947                 {
948                     if ( servletAuth.isAuthorized( activePrincipal, repository,
949                                                    WebdavMethodUtil.getMethodPermission( request.getMethod() ) ) )
950                     {
951                         allow = true;
952                         break;
953                     }
954                 }
955                 catch ( UnauthorizedException e )
956                 {
957                     continue;
958                 }
959             }
960         }
961
962         return allow;
963     }
964
965     private File writeMergedMetadataToFile( ArchivaRepositoryMetadata mergedMetadata, String outputFilename )
966         throws RepositoryMetadataException, DigesterException, IOException
967     {
968         File outputFile = new File( outputFilename );
969         if ( outputFile.exists() )
970         {
971             FileUtils.deleteQuietly( outputFile );
972         }
973
974         outputFile.getParentFile().mkdirs();
975         RepositoryMetadataWriter.write( mergedMetadata, outputFile );
976
977         createChecksumFile( outputFilename, digestSha1 );
978         createChecksumFile( outputFilename, digestMd5 );
979
980         return outputFile;
981     }
982
983     private void createChecksumFile( String path, Digester digester )
984         throws DigesterException, IOException
985     {
986         File checksumFile = new File( path + digester.getFilenameExtension() );
987         if ( !checksumFile.exists() )
988         {
989             FileUtils.deleteQuietly( checksumFile );
990             checksum.createChecksum( new File( path ), digester );
991         }
992         else if ( !checksumFile.isFile() )
993         {
994             log.error( "Checksum file is not a file." );
995         }
996     }
997
998     private boolean isProjectReference( String requestedResource )
999     {
1000         try
1001         {
1002             metadataTools.toVersionedReference( requestedResource );
1003             return false;
1004         }
1005         catch ( RepositoryMetadataException re )
1006         {
1007             return true;
1008         }
1009     }
1010
1011     public void setServletAuth( ServletAuthenticator servletAuth )
1012     {
1013         this.servletAuth = servletAuth;
1014     }
1015
1016     public void setHttpAuth( HttpAuthenticator httpAuth )
1017     {
1018         this.httpAuth = httpAuth;
1019     }
1020
1021     public void setTaskExecutor( TaskExecutor taskExecutor )
1022     {
1023         this.taskExecutor = taskExecutor;
1024     }
1025
1026     public void setScheduler( ArchivaTaskScheduler scheduler )
1027     {
1028         this.scheduler = scheduler;
1029     }
1030 }