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