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

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