You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ArchivaDavResourceFactory.java 64KB

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