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