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