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