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