Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

GitblitReceivePack.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * Copyright 2013 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.git;
  17. import static org.eclipse.jgit.transport.BasePackPushConnection.CAPABILITY_SIDE_BAND_64K;
  18. import groovy.lang.Binding;
  19. import groovy.util.GroovyScriptEngine;
  20. import java.io.File;
  21. import java.io.IOException;
  22. import java.text.MessageFormat;
  23. import java.util.Collection;
  24. import java.util.LinkedHashSet;
  25. import java.util.List;
  26. import java.util.Set;
  27. import java.util.concurrent.TimeUnit;
  28. import org.eclipse.jgit.lib.BatchRefUpdate;
  29. import org.eclipse.jgit.lib.NullProgressMonitor;
  30. import org.eclipse.jgit.lib.PersonIdent;
  31. import org.eclipse.jgit.lib.ProgressMonitor;
  32. import org.eclipse.jgit.lib.Repository;
  33. import org.eclipse.jgit.revwalk.RevCommit;
  34. import org.eclipse.jgit.transport.PostReceiveHook;
  35. import org.eclipse.jgit.transport.PreReceiveHook;
  36. import org.eclipse.jgit.transport.ReceiveCommand;
  37. import org.eclipse.jgit.transport.ReceiveCommand.Result;
  38. import org.eclipse.jgit.transport.ReceivePack;
  39. import org.slf4j.Logger;
  40. import org.slf4j.LoggerFactory;
  41. import com.gitblit.Constants;
  42. import com.gitblit.Constants.AccessRestrictionType;
  43. import com.gitblit.GitBlit;
  44. import com.gitblit.IStoredSettings;
  45. import com.gitblit.Keys;
  46. import com.gitblit.client.Translation;
  47. import com.gitblit.models.RepositoryModel;
  48. import com.gitblit.models.UserModel;
  49. import com.gitblit.utils.ArrayUtils;
  50. import com.gitblit.utils.ClientLogger;
  51. import com.gitblit.utils.CommitCache;
  52. import com.gitblit.utils.JGitUtils;
  53. import com.gitblit.utils.RefLogUtils;
  54. import com.gitblit.utils.StringUtils;
  55. /**
  56. * GitblitReceivePack processes receive commands. It also executes Groovy pre-
  57. * and post- receive hooks.
  58. *
  59. * The general execution flow is:
  60. * <ol>
  61. * <li>onPreReceive()</li>
  62. * <li>executeCommands()</li>
  63. * <li>onPostReceive()</li>
  64. * </ol>
  65. *
  66. * @author Android Open Source Project
  67. * @author James Moger
  68. *
  69. */
  70. public class GitblitReceivePack extends ReceivePack implements PreReceiveHook, PostReceiveHook {
  71. private static final Logger LOGGER = LoggerFactory.getLogger(GitblitReceivePack.class);
  72. protected final RepositoryModel repository;
  73. protected final UserModel user;
  74. protected final File groovyDir;
  75. protected String gitblitUrl;
  76. protected String repositoryUrl;
  77. protected GroovyScriptEngine gse;
  78. private final IStoredSettings settings;
  79. private final GitBlit gitblit;
  80. public GitblitReceivePack(
  81. GitBlit gitblit,
  82. Repository db,
  83. RepositoryModel repository,
  84. UserModel user) {
  85. super(db);
  86. this.settings = gitblit.getSettings();
  87. this.gitblit = gitblit;
  88. this.repository = repository;
  89. this.user = user;
  90. this.groovyDir = gitblit.getHooksFolder();
  91. try {
  92. // set Grape root
  93. File grapeRoot = gitblit.getGrapesFolder();
  94. grapeRoot.mkdirs();
  95. System.setProperty("grape.root", grapeRoot.getAbsolutePath());
  96. this.gse = new GroovyScriptEngine(groovyDir.getAbsolutePath());
  97. } catch (IOException e) {
  98. }
  99. // set advanced ref permissions
  100. setAllowCreates(user.canCreateRef(repository));
  101. setAllowDeletes(user.canDeleteRef(repository));
  102. setAllowNonFastForwards(user.canRewindRef(repository));
  103. // setup pre and post receive hook
  104. setPreReceiveHook(this);
  105. setPostReceiveHook(this);
  106. }
  107. /**
  108. * Instrumentation point where the incoming push event has been parsed,
  109. * validated, objects created BUT refs have not been updated. You might
  110. * use this to enforce a branch-write permissions model.
  111. */
  112. @Override
  113. public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  114. if (repository.isMirror) {
  115. // repository is a mirror
  116. for (ReceiveCommand cmd : commands) {
  117. sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is a mirror!", repository.name);
  118. }
  119. return;
  120. }
  121. if (repository.isFrozen) {
  122. // repository is frozen/readonly
  123. for (ReceiveCommand cmd : commands) {
  124. sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name);
  125. }
  126. return;
  127. }
  128. if (!repository.isBare) {
  129. // repository has a working copy
  130. for (ReceiveCommand cmd : commands) {
  131. sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name);
  132. }
  133. return;
  134. }
  135. if (!user.canPush(repository)) {
  136. // user does not have push permissions
  137. for (ReceiveCommand cmd : commands) {
  138. sendRejection(cmd, "User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name);
  139. }
  140. return;
  141. }
  142. if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) {
  143. // enforce committer verification
  144. if (StringUtils.isEmpty(user.emailAddress)) {
  145. // reject the push because the pushing account does not have an email address
  146. for (ReceiveCommand cmd : commands) {
  147. sendRejection(cmd, "Sorry, the account \"{0}\" does not have an email address set for committer verification!", user.username);
  148. }
  149. return;
  150. }
  151. // Optionally enforce that the committer of first parent chain
  152. // match the account being used to push the commits.
  153. //
  154. // This requires all merge commits are executed with the "--no-ff"
  155. // option to force a merge commit even if fast-forward is possible.
  156. // This ensures that the chain first parents has the commit
  157. // identity of the merging user.
  158. boolean allRejected = false;
  159. for (ReceiveCommand cmd : commands) {
  160. String firstParent = null;
  161. try {
  162. List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name());
  163. for (RevCommit commit : commits) {
  164. if (firstParent != null) {
  165. if (!commit.getName().equals(firstParent)) {
  166. // ignore: commit is right-descendant of a merge
  167. continue;
  168. }
  169. }
  170. // update expected next commit id
  171. if (commit.getParentCount() == 0) {
  172. firstParent = null;
  173. } else {
  174. firstParent = commit.getParents()[0].getId().getName();
  175. }
  176. PersonIdent committer = commit.getCommitterIdent();
  177. if (!user.is(committer.getName(), committer.getEmailAddress())) {
  178. // verification failed
  179. String reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>",
  180. commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?":committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress);
  181. LOGGER.warn(reason);
  182. cmd.setResult(Result.REJECTED_OTHER_REASON, reason);
  183. allRejected &= true;
  184. break;
  185. } else {
  186. allRejected = false;
  187. }
  188. }
  189. } catch (Exception e) {
  190. LOGGER.error("Failed to verify commits were made by pushing user", e);
  191. }
  192. }
  193. if (allRejected) {
  194. // all ref updates rejected, abort
  195. return;
  196. }
  197. }
  198. // reset branch commit cache on REWIND and DELETE
  199. for (ReceiveCommand cmd : commands) {
  200. String ref = cmd.getRefName();
  201. if (ref.startsWith(Constants.R_HEADS)) {
  202. switch (cmd.getType()) {
  203. case UPDATE_NONFASTFORWARD:
  204. case DELETE:
  205. CommitCache.instance().clear(repository.name, ref);
  206. break;
  207. default:
  208. break;
  209. }
  210. }
  211. }
  212. Set<String> scripts = new LinkedHashSet<String>();
  213. scripts.addAll(gitblit.getPreReceiveScriptsInherited(repository));
  214. if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) {
  215. scripts.addAll(repository.preReceiveScripts);
  216. }
  217. runGroovy(commands, scripts);
  218. for (ReceiveCommand cmd : commands) {
  219. if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) {
  220. LOGGER.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId()
  221. .getName(), cmd.getResult(), cmd.getMessage()));
  222. }
  223. }
  224. }
  225. /**
  226. * Instrumentation point where the incoming push has been applied to the
  227. * repository. This is the point where we would trigger a Jenkins build
  228. * or send an email.
  229. */
  230. @Override
  231. public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) {
  232. if (commands.size() == 0) {
  233. LOGGER.debug("skipping post-receive hooks, no refs created, updated, or removed");
  234. return;
  235. }
  236. // log ref changes
  237. for (ReceiveCommand cmd : commands) {
  238. if (Result.OK.equals(cmd.getResult())) {
  239. // add some logging for important ref changes
  240. switch (cmd.getType()) {
  241. case DELETE:
  242. LOGGER.info(MessageFormat.format("{0} DELETED {1} in {2} ({3})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name()));
  243. break;
  244. case CREATE:
  245. LOGGER.info(MessageFormat.format("{0} CREATED {1} in {2}", user.username, cmd.getRefName(), repository.name));
  246. break;
  247. case UPDATE:
  248. LOGGER.info(MessageFormat.format("{0} UPDATED {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name()));
  249. break;
  250. case UPDATE_NONFASTFORWARD:
  251. LOGGER.info(MessageFormat.format("{0} UPDATED NON-FAST-FORWARD {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name()));
  252. break;
  253. default:
  254. break;
  255. }
  256. }
  257. }
  258. if (repository.useIncrementalPushTags) {
  259. // tag each pushed branch tip
  260. String emailAddress = user.emailAddress == null ? rp.getRefLogIdent().getEmailAddress() : user.emailAddress;
  261. PersonIdent userIdent = new PersonIdent(user.getDisplayName(), emailAddress);
  262. for (ReceiveCommand cmd : commands) {
  263. if (!cmd.getRefName().startsWith(Constants.R_HEADS)) {
  264. // only tag branch ref changes
  265. continue;
  266. }
  267. if (!ReceiveCommand.Type.DELETE.equals(cmd.getType())
  268. && ReceiveCommand.Result.OK.equals(cmd.getResult())) {
  269. String objectId = cmd.getNewId().getName();
  270. String branch = cmd.getRefName().substring(Constants.R_HEADS.length());
  271. // get translation based on the server's locale setting
  272. String template = Translation.get("gb.incrementalPushTagMessage");
  273. String msg = MessageFormat.format(template, branch);
  274. String prefix;
  275. if (StringUtils.isEmpty(repository.incrementalPushTagPrefix)) {
  276. prefix = settings.getString(Keys.git.defaultIncrementalPushTagPrefix, "r");
  277. } else {
  278. prefix = repository.incrementalPushTagPrefix;
  279. }
  280. JGitUtils.createIncrementalRevisionTag(
  281. rp.getRepository(),
  282. objectId,
  283. userIdent,
  284. prefix,
  285. "0",
  286. msg);
  287. }
  288. }
  289. }
  290. // update push log
  291. try {
  292. RefLogUtils.updateRefLog(user, rp.getRepository(), commands);
  293. LOGGER.debug(MessageFormat.format("{0} push log updated", repository.name));
  294. } catch (Exception e) {
  295. LOGGER.error(MessageFormat.format("Failed to update {0} pushlog", repository.name), e);
  296. }
  297. // run Groovy hook scripts
  298. Set<String> scripts = new LinkedHashSet<String>();
  299. scripts.addAll(gitblit.getPostReceiveScriptsInherited(repository));
  300. if (!ArrayUtils.isEmpty(repository.postReceiveScripts)) {
  301. scripts.addAll(repository.postReceiveScripts);
  302. }
  303. runGroovy(commands, scripts);
  304. }
  305. /** Execute commands to update references. */
  306. @Override
  307. protected void executeCommands() {
  308. List<ReceiveCommand> toApply = filterCommands(Result.NOT_ATTEMPTED);
  309. if (toApply.isEmpty()) {
  310. return;
  311. }
  312. ProgressMonitor updating = NullProgressMonitor.INSTANCE;
  313. boolean sideBand = isCapabilityEnabled(CAPABILITY_SIDE_BAND_64K);
  314. if (sideBand) {
  315. SideBandProgressMonitor pm = new SideBandProgressMonitor(msgOut);
  316. pm.setDelayStart(250, TimeUnit.MILLISECONDS);
  317. updating = pm;
  318. }
  319. BatchRefUpdate batch = getRepository().getRefDatabase().newBatchUpdate();
  320. batch.setAllowNonFastForwards(isAllowNonFastForwards());
  321. batch.setRefLogIdent(getRefLogIdent());
  322. batch.setRefLogMessage("push", true);
  323. for (ReceiveCommand cmd : toApply) {
  324. if (Result.NOT_ATTEMPTED != cmd.getResult()) {
  325. // Already rejected by the core receive process.
  326. continue;
  327. }
  328. batch.addCommand(cmd);
  329. }
  330. if (!batch.getCommands().isEmpty()) {
  331. try {
  332. batch.execute(getRevWalk(), updating);
  333. } catch (IOException err) {
  334. for (ReceiveCommand cmd : toApply) {
  335. if (cmd.getResult() == Result.NOT_ATTEMPTED) {
  336. sendRejection(cmd, "lock error: {0}", err.getMessage());
  337. }
  338. }
  339. }
  340. }
  341. }
  342. protected void setGitblitUrl(String url) {
  343. this.gitblitUrl = url;
  344. }
  345. protected void setRepositoryUrl(String url) {
  346. this.repositoryUrl = url;
  347. }
  348. protected void sendRejection(final ReceiveCommand cmd, final String why, Object... objects) {
  349. String text;
  350. if (ArrayUtils.isEmpty(objects)) {
  351. text = why;
  352. } else {
  353. text = MessageFormat.format(why, objects);
  354. }
  355. cmd.setResult(Result.REJECTED_OTHER_REASON, text);
  356. LOGGER.error(text + " (" + user.username + ")");
  357. }
  358. protected void sendHeader(String msg, Object... objects) {
  359. sendMessage("--->", msg, objects);
  360. }
  361. protected void sendMessage(String msg, Object... objects) {
  362. sendMessage(" ", msg, objects);
  363. }
  364. protected void sendMessage(String prefix, String msg, Object... objects) {
  365. String text;
  366. if (ArrayUtils.isEmpty(objects)) {
  367. text = msg;
  368. super.sendMessage(prefix + msg);
  369. } else {
  370. text = MessageFormat.format(msg, objects);
  371. super.sendMessage(prefix + text);
  372. }
  373. LOGGER.info(text + " (" + user.username + ")");
  374. }
  375. protected void sendError(String msg, Object... objects) {
  376. String text;
  377. if (ArrayUtils.isEmpty(objects)) {
  378. text = msg;
  379. super.sendError(msg);
  380. } else {
  381. text = MessageFormat.format(msg, objects);
  382. super.sendError(text);
  383. }
  384. LOGGER.error(text + " (" + user.username + ")");
  385. }
  386. /**
  387. * Runs the specified Groovy hook scripts.
  388. *
  389. * @param repository
  390. * @param user
  391. * @param commands
  392. * @param scripts
  393. */
  394. private void runGroovy(Collection<ReceiveCommand> commands, Set<String> scripts) {
  395. if (scripts == null || scripts.size() == 0) {
  396. // no Groovy scripts to execute
  397. return;
  398. }
  399. Binding binding = new Binding();
  400. binding.setVariable("gitblit", gitblit);
  401. binding.setVariable("repository", repository);
  402. binding.setVariable("receivePack", this);
  403. binding.setVariable("user", user);
  404. binding.setVariable("commands", commands);
  405. binding.setVariable("url", gitblitUrl);
  406. binding.setVariable("logger", LOGGER);
  407. binding.setVariable("clientLogger", new ClientLogger(this));
  408. for (String script : scripts) {
  409. if (StringUtils.isEmpty(script)) {
  410. continue;
  411. }
  412. // allow script to be specified without .groovy extension
  413. // this is easier to read in the settings
  414. File file = new File(groovyDir, script);
  415. if (!file.exists() && !script.toLowerCase().endsWith(".groovy")) {
  416. file = new File(groovyDir, script + ".groovy");
  417. if (file.exists()) {
  418. script = file.getName();
  419. }
  420. }
  421. try {
  422. Object result = gse.run(script, binding);
  423. if (result instanceof Boolean) {
  424. if (!((Boolean) result)) {
  425. LOGGER.error(MessageFormat.format(
  426. "Groovy script {0} has failed! Hook scripts aborted.", script));
  427. break;
  428. }
  429. }
  430. } catch (Exception e) {
  431. LOGGER.error(
  432. MessageFormat.format("Failed to execute Groovy script {0}", script), e);
  433. }
  434. }
  435. }
  436. }