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