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.

GitblitReceivePack.java 16KB

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