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.

GitBlit.java 85KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  1. /*
  2. * Copyright 2011 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;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileFilter;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.InputStreamReader;
  23. import java.lang.reflect.Field;
  24. import java.net.URI;
  25. import java.net.URISyntaxException;
  26. import java.text.MessageFormat;
  27. import java.text.SimpleDateFormat;
  28. import java.util.ArrayList;
  29. import java.util.Arrays;
  30. import java.util.Collection;
  31. import java.util.Collections;
  32. import java.util.Date;
  33. import java.util.HashMap;
  34. import java.util.LinkedHashMap;
  35. import java.util.LinkedHashSet;
  36. import java.util.List;
  37. import java.util.Map;
  38. import java.util.Map.Entry;
  39. import java.util.Set;
  40. import java.util.TimeZone;
  41. import java.util.TreeMap;
  42. import java.util.TreeSet;
  43. import java.util.concurrent.ConcurrentHashMap;
  44. import java.util.concurrent.Executors;
  45. import java.util.concurrent.ScheduledExecutorService;
  46. import java.util.concurrent.TimeUnit;
  47. import java.util.concurrent.atomic.AtomicInteger;
  48. import java.util.concurrent.atomic.AtomicReference;
  49. import javax.mail.Message;
  50. import javax.mail.MessagingException;
  51. import javax.servlet.ServletContext;
  52. import javax.servlet.ServletContextEvent;
  53. import javax.servlet.ServletContextListener;
  54. import javax.servlet.http.Cookie;
  55. import org.apache.wicket.protocol.http.WebResponse;
  56. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  57. import org.eclipse.jgit.lib.Repository;
  58. import org.eclipse.jgit.lib.RepositoryCache.FileKey;
  59. import org.eclipse.jgit.lib.StoredConfig;
  60. import org.eclipse.jgit.storage.file.FileBasedConfig;
  61. import org.eclipse.jgit.storage.file.WindowCache;
  62. import org.eclipse.jgit.storage.file.WindowCacheConfig;
  63. import org.eclipse.jgit.transport.ServiceMayNotContinueException;
  64. import org.eclipse.jgit.transport.resolver.FileResolver;
  65. import org.eclipse.jgit.transport.resolver.RepositoryResolver;
  66. import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
  67. import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;
  68. import org.eclipse.jgit.util.FS;
  69. import org.eclipse.jgit.util.FileUtils;
  70. import org.slf4j.Logger;
  71. import org.slf4j.LoggerFactory;
  72. import com.gitblit.Constants.AccessRestrictionType;
  73. import com.gitblit.Constants.AuthorizationControl;
  74. import com.gitblit.Constants.FederationRequest;
  75. import com.gitblit.Constants.FederationStrategy;
  76. import com.gitblit.Constants.FederationToken;
  77. import com.gitblit.models.FederationModel;
  78. import com.gitblit.models.FederationProposal;
  79. import com.gitblit.models.FederationSet;
  80. import com.gitblit.models.Metric;
  81. import com.gitblit.models.ProjectModel;
  82. import com.gitblit.models.RepositoryModel;
  83. import com.gitblit.models.SearchResult;
  84. import com.gitblit.models.ServerSettings;
  85. import com.gitblit.models.ServerStatus;
  86. import com.gitblit.models.SettingModel;
  87. import com.gitblit.models.TeamModel;
  88. import com.gitblit.models.UserModel;
  89. import com.gitblit.utils.ArrayUtils;
  90. import com.gitblit.utils.ByteFormat;
  91. import com.gitblit.utils.ContainerUtils;
  92. import com.gitblit.utils.DeepCopier;
  93. import com.gitblit.utils.FederationUtils;
  94. import com.gitblit.utils.JGitUtils;
  95. import com.gitblit.utils.JsonUtils;
  96. import com.gitblit.utils.MetricUtils;
  97. import com.gitblit.utils.ObjectCache;
  98. import com.gitblit.utils.StringUtils;
  99. /**
  100. * GitBlit is the servlet context listener singleton that acts as the core for
  101. * the web ui and the servlets. This class is either directly instantiated by
  102. * the GitBlitServer class (Gitblit GO) or is reflectively instantiated from the
  103. * definition in the web.xml file (Gitblit WAR).
  104. *
  105. * This class is the central logic processor for Gitblit. All settings, user
  106. * object, and repository object operations pass through this class.
  107. *
  108. * Repository Resolution. There are two pathways for finding repositories. One
  109. * pathway, for web ui display and repository authentication & authorization, is
  110. * within this class. The other pathway is through the standard GitServlet.
  111. *
  112. * @author James Moger
  113. *
  114. */
  115. public class GitBlit implements ServletContextListener {
  116. private static GitBlit gitblit;
  117. private final Logger logger = LoggerFactory.getLogger(GitBlit.class);
  118. private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
  119. private final List<FederationModel> federationRegistrations = Collections
  120. .synchronizedList(new ArrayList<FederationModel>());
  121. private final Map<String, FederationModel> federationPullResults = new ConcurrentHashMap<String, FederationModel>();
  122. private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
  123. private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
  124. private final Map<String, RepositoryModel> repositoryListCache = new ConcurrentHashMap<String, RepositoryModel>();
  125. private final Map<String, ProjectModel> projectCache = new ConcurrentHashMap<String, ProjectModel>();
  126. private final AtomicReference<String> repositoryListSettingsChecksum = new AtomicReference<String>("");
  127. private RepositoryResolver<Void> repositoryResolver;
  128. private ServletContext servletContext;
  129. private File repositoriesFolder;
  130. private IUserService userService;
  131. private IStoredSettings settings;
  132. private ServerSettings settingsModel;
  133. private ServerStatus serverStatus;
  134. private MailExecutor mailExecutor;
  135. private LuceneExecutor luceneExecutor;
  136. private TimeZone timezone;
  137. private FileBasedConfig projectConfigs;
  138. public GitBlit() {
  139. if (gitblit == null) {
  140. // set the static singleton reference
  141. gitblit = this;
  142. }
  143. }
  144. /**
  145. * Returns the Gitblit singleton.
  146. *
  147. * @return gitblit singleton
  148. */
  149. public static GitBlit self() {
  150. if (gitblit == null) {
  151. new GitBlit();
  152. }
  153. return gitblit;
  154. }
  155. /**
  156. * Determine if this is the GO variant of Gitblit.
  157. *
  158. * @return true if this is the GO variant of Gitblit.
  159. */
  160. public static boolean isGO() {
  161. return self().settings instanceof FileSettings;
  162. }
  163. /**
  164. * Returns the preferred timezone for the Gitblit instance.
  165. *
  166. * @return a timezone
  167. */
  168. public static TimeZone getTimezone() {
  169. if (self().timezone == null) {
  170. String tzid = getString("web.timezone", null);
  171. if (StringUtils.isEmpty(tzid)) {
  172. self().timezone = TimeZone.getDefault();
  173. return self().timezone;
  174. }
  175. self().timezone = TimeZone.getTimeZone(tzid);
  176. }
  177. return self().timezone;
  178. }
  179. /**
  180. * Returns the user-defined blob encodings.
  181. *
  182. * @return an array of encodings, may be empty
  183. */
  184. public static String [] getEncodings() {
  185. return getStrings(Keys.web.blobEncodings).toArray(new String[0]);
  186. }
  187. /**
  188. * Returns the boolean value for the specified key. If the key does not
  189. * exist or the value for the key can not be interpreted as a boolean, the
  190. * defaultValue is returned.
  191. *
  192. * @see IStoredSettings.getBoolean(String, boolean)
  193. * @param key
  194. * @param defaultValue
  195. * @return key value or defaultValue
  196. */
  197. public static boolean getBoolean(String key, boolean defaultValue) {
  198. return self().settings.getBoolean(key, defaultValue);
  199. }
  200. /**
  201. * Returns the integer value for the specified key. If the key does not
  202. * exist or the value for the key can not be interpreted as an integer, the
  203. * defaultValue is returned.
  204. *
  205. * @see IStoredSettings.getInteger(String key, int defaultValue)
  206. * @param key
  207. * @param defaultValue
  208. * @return key value or defaultValue
  209. */
  210. public static int getInteger(String key, int defaultValue) {
  211. return self().settings.getInteger(key, defaultValue);
  212. }
  213. /**
  214. * Returns the char value for the specified key. If the key does not exist
  215. * or the value for the key can not be interpreted as a character, the
  216. * defaultValue is returned.
  217. *
  218. * @see IStoredSettings.getChar(String key, char defaultValue)
  219. * @param key
  220. * @param defaultValue
  221. * @return key value or defaultValue
  222. */
  223. public static char getChar(String key, char defaultValue) {
  224. return self().settings.getChar(key, defaultValue);
  225. }
  226. /**
  227. * Returns the string value for the specified key. If the key does not exist
  228. * or the value for the key can not be interpreted as a string, the
  229. * defaultValue is returned.
  230. *
  231. * @see IStoredSettings.getString(String key, String defaultValue)
  232. * @param key
  233. * @param defaultValue
  234. * @return key value or defaultValue
  235. */
  236. public static String getString(String key, String defaultValue) {
  237. return self().settings.getString(key, defaultValue);
  238. }
  239. /**
  240. * Returns a list of space-separated strings from the specified key.
  241. *
  242. * @see IStoredSettings.getStrings(String key)
  243. * @param name
  244. * @return list of strings
  245. */
  246. public static List<String> getStrings(String key) {
  247. return self().settings.getStrings(key);
  248. }
  249. /**
  250. * Returns a map of space-separated key-value pairs from the specified key.
  251. *
  252. * @see IStoredSettings.getStrings(String key)
  253. * @param name
  254. * @return map of string, string
  255. */
  256. public static Map<String, String> getMap(String key) {
  257. return self().settings.getMap(key);
  258. }
  259. /**
  260. * Returns the list of keys whose name starts with the specified prefix. If
  261. * the prefix is null or empty, all key names are returned.
  262. *
  263. * @see IStoredSettings.getAllKeys(String key)
  264. * @param startingWith
  265. * @return list of keys
  266. */
  267. public static List<String> getAllKeys(String startingWith) {
  268. return self().settings.getAllKeys(startingWith);
  269. }
  270. /**
  271. * Is Gitblit running in debug mode?
  272. *
  273. * @return true if Gitblit is running in debug mode
  274. */
  275. public static boolean isDebugMode() {
  276. return self().settings.getBoolean(Keys.web.debugMode, false);
  277. }
  278. /**
  279. * Returns the file object for the specified configuration key.
  280. *
  281. * @return the file
  282. */
  283. public static File getFileOrFolder(String key, String defaultFileOrFolder) {
  284. String fileOrFolder = GitBlit.getString(key, defaultFileOrFolder);
  285. return getFileOrFolder(fileOrFolder);
  286. }
  287. /**
  288. * Returns the file object which may have it's base-path determined by
  289. * environment variables for running on a cloud hosting service. All Gitblit
  290. * file or folder retrievals are (at least initially) funneled through this
  291. * method so it is the correct point to globally override/alter filesystem
  292. * access based on environment or some other indicator.
  293. *
  294. * @return the file
  295. */
  296. public static File getFileOrFolder(String fileOrFolder) {
  297. String openShift = System.getenv("OPENSHIFT_DATA_DIR");
  298. if (!StringUtils.isEmpty(openShift)) {
  299. // running on RedHat OpenShift
  300. return new File(openShift, fileOrFolder);
  301. }
  302. return new File(fileOrFolder);
  303. }
  304. /**
  305. * Returns the path of the repositories folder. This method checks to see if
  306. * Gitblit is running on a cloud service and may return an adjusted path.
  307. *
  308. * @return the repositories folder path
  309. */
  310. public static File getRepositoriesFolder() {
  311. return getFileOrFolder(Keys.git.repositoriesFolder, "git");
  312. }
  313. /**
  314. * Returns the path of the proposals folder. This method checks to see if
  315. * Gitblit is running on a cloud service and may return an adjusted path.
  316. *
  317. * @return the proposals folder path
  318. */
  319. public static File getProposalsFolder() {
  320. return getFileOrFolder(Keys.federation.proposalsFolder, "proposals");
  321. }
  322. /**
  323. * Returns the path of the Groovy folder. This method checks to see if
  324. * Gitblit is running on a cloud service and may return an adjusted path.
  325. *
  326. * @return the Groovy scripts folder path
  327. */
  328. public static File getGroovyScriptsFolder() {
  329. return getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
  330. }
  331. /**
  332. * Updates the list of server settings.
  333. *
  334. * @param settings
  335. * @return true if the update succeeded
  336. */
  337. public boolean updateSettings(Map<String, String> updatedSettings) {
  338. return settings.saveSettings(updatedSettings);
  339. }
  340. public ServerStatus getStatus() {
  341. // update heap memory status
  342. serverStatus.heapAllocated = Runtime.getRuntime().totalMemory();
  343. serverStatus.heapFree = Runtime.getRuntime().freeMemory();
  344. return serverStatus;
  345. }
  346. /**
  347. * Returns the list of non-Gitblit clone urls. This allows Gitblit to
  348. * advertise alternative urls for Git client repository access.
  349. *
  350. * @param repositoryName
  351. * @return list of non-gitblit clone urls
  352. */
  353. public List<String> getOtherCloneUrls(String repositoryName) {
  354. List<String> cloneUrls = new ArrayList<String>();
  355. for (String url : settings.getStrings(Keys.web.otherUrls)) {
  356. cloneUrls.add(MessageFormat.format(url, repositoryName));
  357. }
  358. return cloneUrls;
  359. }
  360. /**
  361. * Set the user service. The user service authenticates all users and is
  362. * responsible for managing user permissions.
  363. *
  364. * @param userService
  365. */
  366. public void setUserService(IUserService userService) {
  367. logger.info("Setting up user service " + userService.toString());
  368. this.userService = userService;
  369. this.userService.setup(settings);
  370. }
  371. /**
  372. *
  373. * @return true if the user service supports credential changes
  374. */
  375. public boolean supportsCredentialChanges() {
  376. return userService.supportsCredentialChanges();
  377. }
  378. /**
  379. *
  380. * @return true if the user service supports display name changes
  381. */
  382. public boolean supportsDisplayNameChanges() {
  383. return userService.supportsDisplayNameChanges();
  384. }
  385. /**
  386. *
  387. * @return true if the user service supports email address changes
  388. */
  389. public boolean supportsEmailAddressChanges() {
  390. return userService.supportsEmailAddressChanges();
  391. }
  392. /**
  393. *
  394. * @return true if the user service supports team membership changes
  395. */
  396. public boolean supportsTeamMembershipChanges() {
  397. return userService.supportsTeamMembershipChanges();
  398. }
  399. /**
  400. * Authenticate a user based on a username and password.
  401. *
  402. * @see IUserService.authenticate(String, char[])
  403. * @param username
  404. * @param password
  405. * @return a user object or null
  406. */
  407. public UserModel authenticate(String username, char[] password) {
  408. if (StringUtils.isEmpty(username)) {
  409. // can not authenticate empty username
  410. return null;
  411. }
  412. String pw = new String(password);
  413. if (StringUtils.isEmpty(pw)) {
  414. // can not authenticate empty password
  415. return null;
  416. }
  417. // check to see if this is the federation user
  418. if (canFederate()) {
  419. if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
  420. List<String> tokens = getFederationTokens();
  421. if (tokens.contains(pw)) {
  422. // the federation user is an administrator
  423. UserModel federationUser = new UserModel(Constants.FEDERATION_USER);
  424. federationUser.canAdmin = true;
  425. return federationUser;
  426. }
  427. }
  428. }
  429. // delegate authentication to the user service
  430. if (userService == null) {
  431. return null;
  432. }
  433. return userService.authenticate(username, password);
  434. }
  435. /**
  436. * Authenticate a user based on their cookie.
  437. *
  438. * @param cookies
  439. * @return a user object or null
  440. */
  441. public UserModel authenticate(Cookie[] cookies) {
  442. if (userService == null) {
  443. return null;
  444. }
  445. if (userService.supportsCookies()) {
  446. if (cookies != null && cookies.length > 0) {
  447. for (Cookie cookie : cookies) {
  448. if (cookie.getName().equals(Constants.NAME)) {
  449. String value = cookie.getValue();
  450. return userService.authenticate(value.toCharArray());
  451. }
  452. }
  453. }
  454. }
  455. return null;
  456. }
  457. /**
  458. * Sets a cookie for the specified user.
  459. *
  460. * @param response
  461. * @param user
  462. */
  463. public void setCookie(WebResponse response, UserModel user) {
  464. if (userService == null) {
  465. return;
  466. }
  467. if (userService.supportsCookies()) {
  468. Cookie userCookie;
  469. if (user == null) {
  470. // clear cookie for logout
  471. userCookie = new Cookie(Constants.NAME, "");
  472. } else {
  473. // set cookie for login
  474. String cookie = userService.getCookie(user);
  475. if (StringUtils.isEmpty(cookie)) {
  476. // create empty cookie
  477. userCookie = new Cookie(Constants.NAME, "");
  478. } else {
  479. // create real cookie
  480. userCookie = new Cookie(Constants.NAME, cookie);
  481. userCookie.setMaxAge(Integer.MAX_VALUE);
  482. }
  483. }
  484. userCookie.setPath("/");
  485. response.addCookie(userCookie);
  486. }
  487. }
  488. /**
  489. * Logout a user.
  490. *
  491. * @param user
  492. */
  493. public void logout(UserModel user) {
  494. if (userService == null) {
  495. return;
  496. }
  497. userService.logout(user);
  498. }
  499. /**
  500. * Returns the list of all users available to the login service.
  501. *
  502. * @see IUserService.getAllUsernames()
  503. * @return list of all usernames
  504. */
  505. public List<String> getAllUsernames() {
  506. List<String> names = new ArrayList<String>(userService.getAllUsernames());
  507. return names;
  508. }
  509. /**
  510. * Returns the list of all users available to the login service.
  511. *
  512. * @see IUserService.getAllUsernames()
  513. * @return list of all usernames
  514. */
  515. public List<UserModel> getAllUsers() {
  516. List<UserModel> users = userService.getAllUsers();
  517. return users;
  518. }
  519. /**
  520. * Delete the user object with the specified username
  521. *
  522. * @see IUserService.deleteUser(String)
  523. * @param username
  524. * @return true if successful
  525. */
  526. public boolean deleteUser(String username) {
  527. return userService.deleteUser(username);
  528. }
  529. /**
  530. * Retrieve the user object for the specified username.
  531. *
  532. * @see IUserService.getUserModel(String)
  533. * @param username
  534. * @return a user object or null
  535. */
  536. public UserModel getUserModel(String username) {
  537. UserModel user = userService.getUserModel(username);
  538. return user;
  539. }
  540. /**
  541. * Returns the list of all users who are allowed to bypass the access
  542. * restriction placed on the specified repository.
  543. *
  544. * @see IUserService.getUsernamesForRepositoryRole(String)
  545. * @param repository
  546. * @return list of all usernames that can bypass the access restriction
  547. */
  548. public List<String> getRepositoryUsers(RepositoryModel repository) {
  549. return userService.getUsernamesForRepositoryRole(repository.name);
  550. }
  551. /**
  552. * Sets the list of all uses who are allowed to bypass the access
  553. * restriction placed on the specified repository.
  554. *
  555. * @see IUserService.setUsernamesForRepositoryRole(String, List<String>)
  556. * @param repository
  557. * @param usernames
  558. * @return true if successful
  559. */
  560. public boolean setRepositoryUsers(RepositoryModel repository, List<String> repositoryUsers) {
  561. return userService.setUsernamesForRepositoryRole(repository.name, repositoryUsers);
  562. }
  563. /**
  564. * Adds/updates a complete user object keyed by username. This method allows
  565. * for renaming a user.
  566. *
  567. * @see IUserService.updateUserModel(String, UserModel)
  568. * @param username
  569. * @param user
  570. * @param isCreate
  571. * @throws GitBlitException
  572. */
  573. public void updateUserModel(String username, UserModel user, boolean isCreate)
  574. throws GitBlitException {
  575. if (!username.equalsIgnoreCase(user.username)) {
  576. if (userService.getUserModel(user.username) != null) {
  577. throw new GitBlitException(MessageFormat.format(
  578. "Failed to rename ''{0}'' because ''{1}'' already exists.", username,
  579. user.username));
  580. }
  581. }
  582. if (!userService.updateUserModel(username, user)) {
  583. throw new GitBlitException(isCreate ? "Failed to add user!" : "Failed to update user!");
  584. }
  585. }
  586. /**
  587. * Returns the list of available teams that a user or repository may be
  588. * assigned to.
  589. *
  590. * @return the list of teams
  591. */
  592. public List<String> getAllTeamnames() {
  593. List<String> teams = new ArrayList<String>(userService.getAllTeamNames());
  594. return teams;
  595. }
  596. /**
  597. * Returns the list of available teams that a user or repository may be
  598. * assigned to.
  599. *
  600. * @return the list of teams
  601. */
  602. public List<TeamModel> getAllTeams() {
  603. List<TeamModel> teams = userService.getAllTeams();
  604. return teams;
  605. }
  606. /**
  607. * Returns the TeamModel object for the specified name.
  608. *
  609. * @param teamname
  610. * @return a TeamModel object or null
  611. */
  612. public TeamModel getTeamModel(String teamname) {
  613. return userService.getTeamModel(teamname);
  614. }
  615. /**
  616. * Returns the list of all teams who are allowed to bypass the access
  617. * restriction placed on the specified repository.
  618. *
  619. * @see IUserService.getTeamnamesForRepositoryRole(String)
  620. * @param repository
  621. * @return list of all teamnames that can bypass the access restriction
  622. */
  623. public List<String> getRepositoryTeams(RepositoryModel repository) {
  624. return userService.getTeamnamesForRepositoryRole(repository.name);
  625. }
  626. /**
  627. * Sets the list of all uses who are allowed to bypass the access
  628. * restriction placed on the specified repository.
  629. *
  630. * @see IUserService.setTeamnamesForRepositoryRole(String, List<String>)
  631. * @param repository
  632. * @param teamnames
  633. * @return true if successful
  634. */
  635. public boolean setRepositoryTeams(RepositoryModel repository, List<String> repositoryTeams) {
  636. return userService.setTeamnamesForRepositoryRole(repository.name, repositoryTeams);
  637. }
  638. /**
  639. * Updates the TeamModel object for the specified name.
  640. *
  641. * @param teamname
  642. * @param team
  643. * @param isCreate
  644. */
  645. public void updateTeamModel(String teamname, TeamModel team, boolean isCreate)
  646. throws GitBlitException {
  647. if (!teamname.equalsIgnoreCase(team.name)) {
  648. if (userService.getTeamModel(team.name) != null) {
  649. throw new GitBlitException(MessageFormat.format(
  650. "Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
  651. team.name));
  652. }
  653. }
  654. if (!userService.updateTeamModel(teamname, team)) {
  655. throw new GitBlitException(isCreate ? "Failed to add team!" : "Failed to update team!");
  656. }
  657. }
  658. /**
  659. * Delete the team object with the specified teamname
  660. *
  661. * @see IUserService.deleteTeam(String)
  662. * @param teamname
  663. * @return true if successful
  664. */
  665. public boolean deleteTeam(String teamname) {
  666. return userService.deleteTeam(teamname);
  667. }
  668. /**
  669. * Adds the repository to the list of cached repositories if Gitblit is
  670. * configured to cache the repository list.
  671. *
  672. * @param name
  673. */
  674. private void addToCachedRepositoryList(String name, RepositoryModel model) {
  675. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  676. repositoryListCache.put(name, model);
  677. // update the fork origin repository with this repository clone
  678. if (!StringUtils.isEmpty(model.originRepository)) {
  679. if (repositoryListCache.containsKey(model.originRepository)) {
  680. RepositoryModel origin = repositoryListCache.get(model.originRepository);
  681. origin.addFork(name);
  682. }
  683. }
  684. }
  685. }
  686. /**
  687. * Removes the repository from the list of cached repositories.
  688. *
  689. * @param name
  690. * @return the model being removed
  691. */
  692. private RepositoryModel removeFromCachedRepositoryList(String name) {
  693. if (StringUtils.isEmpty(name)) {
  694. return null;
  695. }
  696. return repositoryListCache.remove(name);
  697. }
  698. /**
  699. * Clears all the cached metadata for the specified repository.
  700. *
  701. * @param repositoryName
  702. */
  703. private void clearRepositoryMetadataCache(String repositoryName) {
  704. repositorySizeCache.remove(repositoryName);
  705. repositoryMetricsCache.remove(repositoryName);
  706. }
  707. /**
  708. * Resets the repository list cache.
  709. *
  710. */
  711. public void resetRepositoryListCache() {
  712. logger.info("Repository cache manually reset");
  713. repositoryListCache.clear();
  714. }
  715. /**
  716. * Calculate the checksum of settings that affect the repository list cache.
  717. * @return a checksum
  718. */
  719. private String getRepositoryListSettingsChecksum() {
  720. StringBuilder ns = new StringBuilder();
  721. ns.append(settings.getString(Keys.git.cacheRepositoryList, "")).append('\n');
  722. ns.append(settings.getString(Keys.git.onlyAccessBareRepositories, "")).append('\n');
  723. ns.append(settings.getString(Keys.git.searchRepositoriesSubfolders, "")).append('\n');
  724. ns.append(settings.getString(Keys.git.searchRecursionDepth, "")).append('\n');
  725. ns.append(settings.getString(Keys.git.searchExclusions, "")).append('\n');
  726. String checksum = StringUtils.getSHA1(ns.toString());
  727. return checksum;
  728. }
  729. /**
  730. * Compare the last repository list setting checksum to the current checksum.
  731. * If different then clear the cache so that it may be rebuilt.
  732. *
  733. * @return true if the cached repository list is valid since the last check
  734. */
  735. private boolean isValidRepositoryList() {
  736. String newChecksum = getRepositoryListSettingsChecksum();
  737. boolean valid = newChecksum.equals(repositoryListSettingsChecksum.get());
  738. repositoryListSettingsChecksum.set(newChecksum);
  739. if (!valid && settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  740. logger.info("Repository list settings have changed. Clearing repository list cache.");
  741. repositoryListCache.clear();
  742. }
  743. return valid;
  744. }
  745. /**
  746. * Returns the list of all repositories available to Gitblit. This method
  747. * does not consider user access permissions.
  748. *
  749. * @return list of all repositories
  750. */
  751. public List<String> getRepositoryList() {
  752. if (repositoryListCache.size() == 0 || !isValidRepositoryList()) {
  753. // we are not caching OR we have not yet cached OR the cached list is invalid
  754. long startTime = System.currentTimeMillis();
  755. List<String> repositories = JGitUtils.getRepositoryList(repositoriesFolder,
  756. settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
  757. settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true),
  758. settings.getInteger(Keys.git.searchRecursionDepth, -1),
  759. settings.getStrings(Keys.git.searchExclusions));
  760. if (!settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  761. // we are not caching
  762. StringUtils.sortRepositorynames(repositories);
  763. return repositories;
  764. } else {
  765. // we are caching this list
  766. String msg = "{0} repositories identified in {1} msecs";
  767. // optionally (re)calculate repository sizes
  768. if (getBoolean(Keys.web.showRepositorySizes, true)) {
  769. msg = "{0} repositories identified with calculated folder sizes in {1} msecs";
  770. for (String repository : repositories) {
  771. RepositoryModel model = getRepositoryModel(repository);
  772. if (!model.skipSizeCalculation) {
  773. calculateSize(model);
  774. }
  775. }
  776. } else {
  777. // update cache
  778. for (String repository : repositories) {
  779. getRepositoryModel(repository);
  780. }
  781. }
  782. long duration = System.currentTimeMillis() - startTime;
  783. logger.info(MessageFormat.format(msg, repositoryListCache.size(), duration));
  784. }
  785. }
  786. // return sorted copy of cached list
  787. List<String> list = new ArrayList<String>(repositoryListCache.keySet());
  788. StringUtils.sortRepositorynames(list);
  789. return list;
  790. }
  791. /**
  792. * Returns the JGit repository for the specified name.
  793. *
  794. * @param repositoryName
  795. * @return repository or null
  796. */
  797. public Repository getRepository(String repositoryName) {
  798. return getRepository(repositoryName, true);
  799. }
  800. /**
  801. * Returns the JGit repository for the specified name.
  802. *
  803. * @param repositoryName
  804. * @param logError
  805. * @return repository or null
  806. */
  807. public Repository getRepository(String repositoryName, boolean logError) {
  808. Repository r = null;
  809. try {
  810. r = repositoryResolver.open(null, repositoryName);
  811. } catch (RepositoryNotFoundException e) {
  812. r = null;
  813. if (logError) {
  814. logger.error("GitBlit.getRepository(String) failed to find "
  815. + new File(repositoriesFolder, repositoryName).getAbsolutePath());
  816. }
  817. } catch (ServiceNotAuthorizedException e) {
  818. r = null;
  819. if (logError) {
  820. logger.error("GitBlit.getRepository(String) failed to find "
  821. + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
  822. }
  823. } catch (ServiceNotEnabledException e) {
  824. r = null;
  825. if (logError) {
  826. logger.error("GitBlit.getRepository(String) failed to find "
  827. + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
  828. }
  829. } catch (ServiceMayNotContinueException e) {
  830. r = null;
  831. if (logError) {
  832. logger.error("GitBlit.getRepository(String) failed to find "
  833. + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
  834. }
  835. }
  836. return r;
  837. }
  838. /**
  839. * Returns the list of repository models that are accessible to the user.
  840. *
  841. * @param user
  842. * @return list of repository models accessible to user
  843. */
  844. public List<RepositoryModel> getRepositoryModels(UserModel user) {
  845. long methodStart = System.currentTimeMillis();
  846. List<String> list = getRepositoryList();
  847. List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
  848. for (String repo : list) {
  849. RepositoryModel model = getRepositoryModel(user, repo);
  850. if (model != null) {
  851. repositories.add(model);
  852. }
  853. }
  854. if (getBoolean(Keys.web.showRepositorySizes, true)) {
  855. int repoCount = 0;
  856. long startTime = System.currentTimeMillis();
  857. ByteFormat byteFormat = new ByteFormat();
  858. for (RepositoryModel model : repositories) {
  859. if (!model.skipSizeCalculation) {
  860. repoCount++;
  861. model.size = byteFormat.format(calculateSize(model));
  862. }
  863. }
  864. long duration = System.currentTimeMillis() - startTime;
  865. if (duration > 250) {
  866. // only log calcualtion time if > 250 msecs
  867. logger.info(MessageFormat.format("{0} repository sizes calculated in {1} msecs",
  868. repoCount, duration));
  869. }
  870. }
  871. long duration = System.currentTimeMillis() - methodStart;
  872. logger.info(MessageFormat.format("{0} repository models loaded for {1} in {2} msecs",
  873. repositories.size(), user == null ? "anonymous" : user.username, duration));
  874. return repositories;
  875. }
  876. /**
  877. * Returns a repository model if the repository exists and the user may
  878. * access the repository.
  879. *
  880. * @param user
  881. * @param repositoryName
  882. * @return repository model or null
  883. */
  884. public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
  885. RepositoryModel model = getRepositoryModel(repositoryName);
  886. if (model == null) {
  887. return null;
  888. }
  889. if (model.accessRestriction.atLeast(AccessRestrictionType.VIEW)) {
  890. if (user != null && user.canAccessRepository(model)) {
  891. return model;
  892. }
  893. return null;
  894. } else {
  895. return model;
  896. }
  897. }
  898. /**
  899. * Returns the repository model for the specified repository. This method
  900. * does not consider user access permissions.
  901. *
  902. * @param repositoryName
  903. * @return repository model or null
  904. */
  905. public RepositoryModel getRepositoryModel(String repositoryName) {
  906. if (!repositoryListCache.containsKey(repositoryName)) {
  907. RepositoryModel model = loadRepositoryModel(repositoryName);
  908. if (model == null) {
  909. return null;
  910. }
  911. addToCachedRepositoryList(repositoryName, model);
  912. return model;
  913. }
  914. // cached model
  915. RepositoryModel model = repositoryListCache.get(repositoryName);
  916. // check for updates
  917. Repository r = getRepository(repositoryName);
  918. if (r == null) {
  919. // repository is missing
  920. removeFromCachedRepositoryList(repositoryName);
  921. logger.error(MessageFormat.format("Repository \"{0}\" is missing! Removing from cache.", repositoryName));
  922. return null;
  923. }
  924. FileBasedConfig config = (FileBasedConfig) getRepositoryConfig(r);
  925. if (config.isOutdated()) {
  926. // reload model
  927. logger.info(MessageFormat.format("Config for \"{0}\" has changed. Reloading model and updating cache.", repositoryName));
  928. model = loadRepositoryModel(repositoryName);
  929. removeFromCachedRepositoryList(repositoryName);
  930. addToCachedRepositoryList(repositoryName, model);
  931. } else {
  932. // update a few repository parameters
  933. if (!model.hasCommits) {
  934. // update hasCommits, assume a repository only gains commits :)
  935. model.hasCommits = JGitUtils.hasCommits(r);
  936. }
  937. model.lastChange = JGitUtils.getLastChange(r);
  938. }
  939. r.close();
  940. // return a copy of the cached model
  941. return DeepCopier.copy(model);
  942. }
  943. /**
  944. * Returns the map of project config. This map is cached and reloaded if
  945. * the underlying projects.conf file changes.
  946. *
  947. * @return project config map
  948. */
  949. private Map<String, ProjectModel> getProjectConfigs() {
  950. if (projectCache.isEmpty() || projectConfigs.isOutdated()) {
  951. try {
  952. projectConfigs.load();
  953. } catch (Exception e) {
  954. }
  955. // project configs
  956. String rootName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main");
  957. ProjectModel rootProject = new ProjectModel(rootName, true);
  958. Map<String, ProjectModel> configs = new HashMap<String, ProjectModel>();
  959. // cache the root project under its alias and an empty path
  960. configs.put("", rootProject);
  961. configs.put(rootProject.name.toLowerCase(), rootProject);
  962. for (String name : projectConfigs.getSubsections("project")) {
  963. ProjectModel project;
  964. if (name.equalsIgnoreCase(rootName)) {
  965. project = rootProject;
  966. } else {
  967. project = new ProjectModel(name);
  968. }
  969. project.title = projectConfigs.getString("project", name, "title");
  970. project.description = projectConfigs.getString("project", name, "description");
  971. // TODO add more interesting metadata
  972. // project manager?
  973. // commit message regex?
  974. // RW+
  975. // RW
  976. // R
  977. configs.put(name.toLowerCase(), project);
  978. }
  979. projectCache.clear();
  980. projectCache.putAll(configs);
  981. }
  982. return projectCache;
  983. }
  984. /**
  985. * Returns a list of project models for the user.
  986. *
  987. * @param user
  988. * @param includeUsers
  989. * @return list of projects that are accessible to the user
  990. */
  991. public List<ProjectModel> getProjectModels(UserModel user, boolean includeUsers) {
  992. Map<String, ProjectModel> configs = getProjectConfigs();
  993. // per-user project lists, this accounts for security and visibility
  994. Map<String, ProjectModel> map = new TreeMap<String, ProjectModel>();
  995. // root project
  996. map.put("", configs.get(""));
  997. for (RepositoryModel model : getRepositoryModels(user)) {
  998. String rootPath = StringUtils.getRootPath(model.name).toLowerCase();
  999. if (!map.containsKey(rootPath)) {
  1000. ProjectModel project;
  1001. if (configs.containsKey(rootPath)) {
  1002. // clone the project model because it's repository list will
  1003. // be tailored for the requesting user
  1004. project = DeepCopier.copy(configs.get(rootPath));
  1005. } else {
  1006. project = new ProjectModel(rootPath);
  1007. }
  1008. map.put(rootPath, project);
  1009. }
  1010. map.get(rootPath).addRepository(model);
  1011. }
  1012. // sort projects, root project first
  1013. List<ProjectModel> projects;
  1014. if (includeUsers) {
  1015. // all projects
  1016. projects = new ArrayList<ProjectModel>(map.values());
  1017. Collections.sort(projects);
  1018. projects.remove(map.get(""));
  1019. projects.add(0, map.get(""));
  1020. } else {
  1021. // all non-user projects
  1022. projects = new ArrayList<ProjectModel>();
  1023. ProjectModel root = map.remove("");
  1024. for (ProjectModel model : map.values()) {
  1025. if (!model.isUserProject()) {
  1026. projects.add(model);
  1027. }
  1028. }
  1029. Collections.sort(projects);
  1030. projects.add(0, root);
  1031. }
  1032. return projects;
  1033. }
  1034. /**
  1035. * Returns the project model for the specified user.
  1036. *
  1037. * @param name
  1038. * @param user
  1039. * @return a project model, or null if it does not exist
  1040. */
  1041. public ProjectModel getProjectModel(String name, UserModel user) {
  1042. for (ProjectModel project : getProjectModels(user, true)) {
  1043. if (project.name.equalsIgnoreCase(name)) {
  1044. return project;
  1045. }
  1046. }
  1047. return null;
  1048. }
  1049. /**
  1050. * Returns a project model for the Gitblit/system user.
  1051. *
  1052. * @param name a project name
  1053. * @return a project model or null if the project does not exist
  1054. */
  1055. public ProjectModel getProjectModel(String name) {
  1056. Map<String, ProjectModel> configs = getProjectConfigs();
  1057. ProjectModel project = configs.get(name.toLowerCase());
  1058. if (project == null) {
  1059. project = new ProjectModel(name);
  1060. if (name.length() > 0 && name.charAt(0) == '~') {
  1061. UserModel user = getUserModel(name.substring(1));
  1062. if (user != null) {
  1063. project.title = user.getDisplayName();
  1064. project.description = "personal repositories";
  1065. }
  1066. }
  1067. } else {
  1068. // clone the object
  1069. project = DeepCopier.copy(project);
  1070. }
  1071. if (StringUtils.isEmpty(name)) {
  1072. // get root repositories
  1073. for (String repository : getRepositoryList()) {
  1074. if (repository.indexOf('/') == -1) {
  1075. project.addRepository(repository);
  1076. }
  1077. }
  1078. } else {
  1079. // get repositories in subfolder
  1080. String folder = name.toLowerCase() + "/";
  1081. for (String repository : getRepositoryList()) {
  1082. if (repository.toLowerCase().startsWith(folder)) {
  1083. project.addRepository(repository);
  1084. }
  1085. }
  1086. }
  1087. if (project.repositories.size() == 0) {
  1088. // no repositories == no project
  1089. return null;
  1090. }
  1091. return project;
  1092. }
  1093. /**
  1094. * Workaround JGit. I need to access the raw config object directly in order
  1095. * to see if the config is dirty so that I can reload a repository model.
  1096. * If I use the stock JGit method to get the config it already reloads the
  1097. * config. If the config changes are made within Gitblit this is fine as
  1098. * the returned config will still be flagged as dirty. BUT... if the config
  1099. * is manipulated outside Gitblit then it fails to recognize this as dirty.
  1100. *
  1101. * @param r
  1102. * @return a config
  1103. */
  1104. private StoredConfig getRepositoryConfig(Repository r) {
  1105. try {
  1106. Field f = r.getClass().getDeclaredField("repoConfig");
  1107. f.setAccessible(true);
  1108. StoredConfig config = (StoredConfig) f.get(r);
  1109. return config;
  1110. } catch (Exception e) {
  1111. logger.error("Failed to retrieve \"repoConfig\" via reflection", e);
  1112. }
  1113. return r.getConfig();
  1114. }
  1115. /**
  1116. * Create a repository model from the configuration and repository data.
  1117. *
  1118. * @param repositoryName
  1119. * @return a repositoryModel or null if the repository does not exist
  1120. */
  1121. private RepositoryModel loadRepositoryModel(String repositoryName) {
  1122. Repository r = getRepository(repositoryName);
  1123. if (r == null) {
  1124. return null;
  1125. }
  1126. RepositoryModel model = new RepositoryModel();
  1127. model.name = repositoryName;
  1128. model.hasCommits = JGitUtils.hasCommits(r);
  1129. model.lastChange = JGitUtils.getLastChange(r);
  1130. model.isBare = r.isBare();
  1131. if (repositoryName.indexOf('/') == -1) {
  1132. model.projectPath = "";
  1133. } else {
  1134. model.projectPath = repositoryName.substring(0, repositoryName.indexOf('/'));
  1135. }
  1136. StoredConfig config = r.getConfig();
  1137. boolean hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
  1138. if (config != null) {
  1139. model.description = getConfig(config, "description", "");
  1140. model.owner = getConfig(config, "owner", "");
  1141. model.useTickets = getConfig(config, "useTickets", false);
  1142. model.useDocs = getConfig(config, "useDocs", false);
  1143. model.allowForks = getConfig(config, "allowForks", true);
  1144. model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
  1145. "accessRestriction", settings.getString(Keys.git.defaultAccessRestriction, null)));
  1146. model.authorizationControl = AuthorizationControl.fromName(getConfig(config,
  1147. "authorizationControl", settings.getString(Keys.git.defaultAuthorizationControl, null)));
  1148. model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
  1149. model.isFrozen = getConfig(config, "isFrozen", false);
  1150. model.showReadme = getConfig(config, "showReadme", false);
  1151. model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
  1152. model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
  1153. model.federationStrategy = FederationStrategy.fromName(getConfig(config,
  1154. "federationStrategy", null));
  1155. model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
  1156. Constants.CONFIG_GITBLIT, null, "federationSets")));
  1157. model.isFederated = getConfig(config, "isFederated", false);
  1158. model.origin = config.getString("remote", "origin", "url");
  1159. model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
  1160. Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
  1161. model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
  1162. Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
  1163. model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
  1164. Constants.CONFIG_GITBLIT, null, "mailingList")));
  1165. model.indexedBranches = new ArrayList<String>(Arrays.asList(config.getStringList(
  1166. Constants.CONFIG_GITBLIT, null, "indexBranch")));
  1167. // Custom defined properties
  1168. model.customFields = new LinkedHashMap<String, String>();
  1169. for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
  1170. model.customFields.put(aProperty, config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
  1171. }
  1172. }
  1173. model.HEAD = JGitUtils.getHEADRef(r);
  1174. model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
  1175. r.close();
  1176. if (model.origin != null && model.origin.startsWith("file://")) {
  1177. // repository was cloned locally... perhaps as a fork
  1178. try {
  1179. File folder = new File(new URI(model.origin));
  1180. String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
  1181. if (!StringUtils.isEmpty(originRepo)) {
  1182. // ensure origin still exists
  1183. File repoFolder = new File(getRepositoriesFolder(), originRepo);
  1184. if (repoFolder.exists()) {
  1185. model.originRepository = originRepo;
  1186. }
  1187. }
  1188. } catch (URISyntaxException e) {
  1189. logger.error("Failed to determine fork for " + model, e);
  1190. }
  1191. }
  1192. return model;
  1193. }
  1194. /**
  1195. * Determines if this server has the requested repository.
  1196. *
  1197. * @param name
  1198. * @return true if the repository exists
  1199. */
  1200. public boolean hasRepository(String repositoryName) {
  1201. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  1202. // if we are caching use the cache to determine availability
  1203. // otherwise we end up adding a phantom repository to the cache
  1204. return repositoryListCache.containsKey(repositoryName);
  1205. }
  1206. Repository r = getRepository(repositoryName, false);
  1207. if (r == null) {
  1208. return false;
  1209. }
  1210. r.close();
  1211. return true;
  1212. }
  1213. /**
  1214. * Returns the size in bytes of the repository. Gitblit caches the
  1215. * repository sizes to reduce the performance penalty of recursive
  1216. * calculation. The cache is updated if the repository has been changed
  1217. * since the last calculation.
  1218. *
  1219. * @param model
  1220. * @return size in bytes
  1221. */
  1222. public long calculateSize(RepositoryModel model) {
  1223. if (repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
  1224. return repositorySizeCache.getObject(model.name);
  1225. }
  1226. File gitDir = FileKey.resolve(new File(repositoriesFolder, model.name), FS.DETECTED);
  1227. long size = com.gitblit.utils.FileUtils.folderSize(gitDir);
  1228. repositorySizeCache.updateObject(model.name, model.lastChange, size);
  1229. return size;
  1230. }
  1231. /**
  1232. * Ensure that a cached repository is completely closed and its resources
  1233. * are properly released.
  1234. *
  1235. * @param repositoryName
  1236. */
  1237. private void closeRepository(String repositoryName) {
  1238. Repository repository = getRepository(repositoryName);
  1239. // assume 2 uses in case reflection fails
  1240. int uses = 2;
  1241. try {
  1242. // The FileResolver caches repositories which is very useful
  1243. // for performance until you want to delete a repository.
  1244. // I have to use reflection to call close() the correct
  1245. // number of times to ensure that the object and ref databases
  1246. // are properly closed before I can delete the repository from
  1247. // the filesystem.
  1248. Field useCnt = Repository.class.getDeclaredField("useCnt");
  1249. useCnt.setAccessible(true);
  1250. uses = ((AtomicInteger) useCnt.get(repository)).get();
  1251. } catch (Exception e) {
  1252. logger.warn(MessageFormat
  1253. .format("Failed to reflectively determine use count for repository {0}",
  1254. repositoryName), e);
  1255. }
  1256. if (uses > 0) {
  1257. logger.info(MessageFormat
  1258. .format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
  1259. repositoryName, uses, uses));
  1260. for (int i = 0; i < uses; i++) {
  1261. repository.close();
  1262. }
  1263. }
  1264. // close any open index writer/searcher in the Lucene executor
  1265. luceneExecutor.close(repositoryName);
  1266. }
  1267. /**
  1268. * Returns the metrics for the default branch of the specified repository.
  1269. * This method builds a metrics cache. The cache is updated if the
  1270. * repository is updated. A new copy of the metrics list is returned on each
  1271. * call so that modifications to the list are non-destructive.
  1272. *
  1273. * @param model
  1274. * @param repository
  1275. * @return a new array list of metrics
  1276. */
  1277. public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
  1278. if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
  1279. return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
  1280. }
  1281. List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null, getTimezone());
  1282. repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
  1283. return new ArrayList<Metric>(metrics);
  1284. }
  1285. /**
  1286. * Returns the gitblit string value for the specified key. If key is not
  1287. * set, returns defaultValue.
  1288. *
  1289. * @param config
  1290. * @param field
  1291. * @param defaultValue
  1292. * @return field value or defaultValue
  1293. */
  1294. private String getConfig(StoredConfig config, String field, String defaultValue) {
  1295. String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
  1296. if (StringUtils.isEmpty(value)) {
  1297. return defaultValue;
  1298. }
  1299. return value;
  1300. }
  1301. /**
  1302. * Returns the gitblit boolean value for the specified key. If key is not
  1303. * set, returns defaultValue.
  1304. *
  1305. * @param config
  1306. * @param field
  1307. * @param defaultValue
  1308. * @return field value or defaultValue
  1309. */
  1310. private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
  1311. return config.getBoolean(Constants.CONFIG_GITBLIT, field, defaultValue);
  1312. }
  1313. /**
  1314. * Creates/updates the repository model keyed by reopsitoryName. Saves all
  1315. * repository settings in .git/config. This method allows for renaming
  1316. * repositories and will update user access permissions accordingly.
  1317. *
  1318. * All repositories created by this method are bare and automatically have
  1319. * .git appended to their names, which is the standard convention for bare
  1320. * repositories.
  1321. *
  1322. * @param repositoryName
  1323. * @param repository
  1324. * @param isCreate
  1325. * @throws GitBlitException
  1326. */
  1327. public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
  1328. boolean isCreate) throws GitBlitException {
  1329. Repository r = null;
  1330. if (isCreate) {
  1331. // ensure created repository name ends with .git
  1332. if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
  1333. repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
  1334. }
  1335. if (new File(repositoriesFolder, repository.name).exists()) {
  1336. throw new GitBlitException(MessageFormat.format(
  1337. "Can not create repository ''{0}'' because it already exists.",
  1338. repository.name));
  1339. }
  1340. // create repository
  1341. logger.info("create repository " + repository.name);
  1342. r = JGitUtils.createRepository(repositoriesFolder, repository.name);
  1343. } else {
  1344. // rename repository
  1345. if (!repositoryName.equalsIgnoreCase(repository.name)) {
  1346. if (!repository.name.toLowerCase().endsWith(
  1347. org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
  1348. repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
  1349. }
  1350. if (new File(repositoriesFolder, repository.name).exists()) {
  1351. throw new GitBlitException(MessageFormat.format(
  1352. "Failed to rename ''{0}'' because ''{1}'' already exists.",
  1353. repositoryName, repository.name));
  1354. }
  1355. closeRepository(repositoryName);
  1356. File folder = new File(repositoriesFolder, repositoryName);
  1357. File destFolder = new File(repositoriesFolder, repository.name);
  1358. if (destFolder.exists()) {
  1359. throw new GitBlitException(
  1360. MessageFormat
  1361. .format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
  1362. repositoryName, repository.name));
  1363. }
  1364. File parentFile = destFolder.getParentFile();
  1365. if (!parentFile.exists() && !parentFile.mkdirs()) {
  1366. throw new GitBlitException(MessageFormat.format(
  1367. "Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
  1368. }
  1369. if (!folder.renameTo(destFolder)) {
  1370. throw new GitBlitException(MessageFormat.format(
  1371. "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
  1372. repository.name));
  1373. }
  1374. // rename the roles
  1375. if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
  1376. throw new GitBlitException(MessageFormat.format(
  1377. "Failed to rename repository permissions ''{0}'' to ''{1}''.",
  1378. repositoryName, repository.name));
  1379. }
  1380. // rename fork origins in their configs
  1381. if (!ArrayUtils.isEmpty(repository.forks)) {
  1382. for (String fork : repository.forks) {
  1383. Repository rf = getRepository(fork);
  1384. try {
  1385. StoredConfig config = rf.getConfig();
  1386. String origin = config.getString("remote", "origin", "url");
  1387. origin = origin.replace(repositoryName, repository.name);
  1388. config.setString("remote", "origin", "url", origin);
  1389. config.save();
  1390. } catch (Exception e) {
  1391. logger.error("Failed to update repository fork config for " + fork, e);
  1392. }
  1393. rf.close();
  1394. }
  1395. }
  1396. // clear the cache
  1397. clearRepositoryMetadataCache(repositoryName);
  1398. repository.resetDisplayName();
  1399. }
  1400. // load repository
  1401. logger.info("edit repository " + repository.name);
  1402. try {
  1403. r = repositoryResolver.open(null, repository.name);
  1404. } catch (RepositoryNotFoundException e) {
  1405. logger.error("Repository not found", e);
  1406. } catch (ServiceNotAuthorizedException e) {
  1407. logger.error("Service not authorized", e);
  1408. } catch (ServiceNotEnabledException e) {
  1409. logger.error("Service not enabled", e);
  1410. } catch (ServiceMayNotContinueException e) {
  1411. logger.error("Service may not continue", e);
  1412. }
  1413. }
  1414. // update settings
  1415. if (r != null) {
  1416. updateConfiguration(r, repository);
  1417. // only update symbolic head if it changes
  1418. String currentRef = JGitUtils.getHEADRef(r);
  1419. if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
  1420. logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}",
  1421. repository.name, currentRef, repository.HEAD));
  1422. if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
  1423. // clear the cache
  1424. clearRepositoryMetadataCache(repository.name);
  1425. }
  1426. }
  1427. // close the repository object
  1428. r.close();
  1429. }
  1430. // update repository cache
  1431. removeFromCachedRepositoryList(repositoryName);
  1432. // model will actually be replaced on next load because config is stale
  1433. addToCachedRepositoryList(repository.name, repository);
  1434. }
  1435. /**
  1436. * Updates the Gitblit configuration for the specified repository.
  1437. *
  1438. * @param r
  1439. * the Git repository
  1440. * @param repository
  1441. * the Gitblit repository model
  1442. */
  1443. public void updateConfiguration(Repository r, RepositoryModel repository) {
  1444. StoredConfig config = r.getConfig();
  1445. config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
  1446. config.setString(Constants.CONFIG_GITBLIT, null, "owner", repository.owner);
  1447. config.setBoolean(Constants.CONFIG_GITBLIT, null, "useTickets", repository.useTickets);
  1448. config.setBoolean(Constants.CONFIG_GITBLIT, null, "useDocs", repository.useDocs);
  1449. config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks);
  1450. config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
  1451. config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl", repository.authorizationControl.name());
  1452. config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
  1453. config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
  1454. config.setBoolean(Constants.CONFIG_GITBLIT, null, "showReadme", repository.showReadme);
  1455. config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
  1456. config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
  1457. config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
  1458. repository.federationStrategy.name());
  1459. config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
  1460. updateList(config, "federationSets", repository.federationSets);
  1461. updateList(config, "preReceiveScript", repository.preReceiveScripts);
  1462. updateList(config, "postReceiveScript", repository.postReceiveScripts);
  1463. updateList(config, "mailingList", repository.mailingLists);
  1464. updateList(config, "indexBranch", repository.indexedBranches);
  1465. // User Defined Properties
  1466. if (repository.customFields != null) {
  1467. if (repository.customFields.size() == 0) {
  1468. // clear section
  1469. config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
  1470. } else {
  1471. for (Entry<String, String> property : repository.customFields.entrySet()) {
  1472. // set field
  1473. String key = property.getKey();
  1474. String value = property.getValue();
  1475. config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
  1476. }
  1477. }
  1478. }
  1479. try {
  1480. config.save();
  1481. } catch (IOException e) {
  1482. logger.error("Failed to save repository config!", e);
  1483. }
  1484. }
  1485. private void updateList(StoredConfig config, String field, List<String> list) {
  1486. // a null list is skipped, not cleared
  1487. // this is for RPC administration where an older manager might be used
  1488. if (list == null) {
  1489. return;
  1490. }
  1491. if (ArrayUtils.isEmpty(list)) {
  1492. config.unset(Constants.CONFIG_GITBLIT, null, field);
  1493. } else {
  1494. config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
  1495. }
  1496. }
  1497. /**
  1498. * Deletes the repository from the file system and removes the repository
  1499. * permission from all repository users.
  1500. *
  1501. * @param model
  1502. * @return true if successful
  1503. */
  1504. public boolean deleteRepositoryModel(RepositoryModel model) {
  1505. return deleteRepository(model.name);
  1506. }
  1507. /**
  1508. * Deletes the repository from the file system and removes the repository
  1509. * permission from all repository users.
  1510. *
  1511. * @param repositoryName
  1512. * @return true if successful
  1513. */
  1514. public boolean deleteRepository(String repositoryName) {
  1515. try {
  1516. closeRepository(repositoryName);
  1517. // clear the repository cache
  1518. clearRepositoryMetadataCache(repositoryName);
  1519. RepositoryModel model = removeFromCachedRepositoryList(repositoryName);
  1520. if (!ArrayUtils.isEmpty(model.forks)) {
  1521. resetRepositoryListCache();
  1522. }
  1523. File folder = new File(repositoriesFolder, repositoryName);
  1524. if (folder.exists() && folder.isDirectory()) {
  1525. FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
  1526. if (userService.deleteRepositoryRole(repositoryName)) {
  1527. logger.info(MessageFormat.format("Repository \"{0}\" deleted", repositoryName));
  1528. return true;
  1529. }
  1530. }
  1531. } catch (Throwable t) {
  1532. logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
  1533. }
  1534. return false;
  1535. }
  1536. /**
  1537. * Returns an html version of the commit message with any global or
  1538. * repository-specific regular expression substitution applied.
  1539. *
  1540. * @param repositoryName
  1541. * @param text
  1542. * @return html version of the commit message
  1543. */
  1544. public String processCommitMessage(String repositoryName, String text) {
  1545. String html = StringUtils.breakLinesForHtml(text);
  1546. Map<String, String> map = new HashMap<String, String>();
  1547. // global regex keys
  1548. if (settings.getBoolean(Keys.regex.global, false)) {
  1549. for (String key : settings.getAllKeys(Keys.regex.global)) {
  1550. if (!key.equals(Keys.regex.global)) {
  1551. String subKey = key.substring(key.lastIndexOf('.') + 1);
  1552. map.put(subKey, settings.getString(key, ""));
  1553. }
  1554. }
  1555. }
  1556. // repository-specific regex keys
  1557. List<String> keys = settings.getAllKeys(Keys.regex._ROOT + "."
  1558. + repositoryName.toLowerCase());
  1559. for (String key : keys) {
  1560. String subKey = key.substring(key.lastIndexOf('.') + 1);
  1561. map.put(subKey, settings.getString(key, ""));
  1562. }
  1563. for (Entry<String, String> entry : map.entrySet()) {
  1564. String definition = entry.getValue().trim();
  1565. String[] chunks = definition.split("!!!");
  1566. if (chunks.length == 2) {
  1567. html = html.replaceAll(chunks[0], chunks[1]);
  1568. } else {
  1569. logger.warn(entry.getKey()
  1570. + " improperly formatted. Use !!! to separate match from replacement: "
  1571. + definition);
  1572. }
  1573. }
  1574. return html;
  1575. }
  1576. /**
  1577. * Returns Gitblit's scheduled executor service for scheduling tasks.
  1578. *
  1579. * @return scheduledExecutor
  1580. */
  1581. public ScheduledExecutorService executor() {
  1582. return scheduledExecutor;
  1583. }
  1584. public static boolean canFederate() {
  1585. String passphrase = getString(Keys.federation.passphrase, "");
  1586. return !StringUtils.isEmpty(passphrase);
  1587. }
  1588. /**
  1589. * Configures this Gitblit instance to pull any registered federated gitblit
  1590. * instances.
  1591. */
  1592. private void configureFederation() {
  1593. boolean validPassphrase = true;
  1594. String passphrase = settings.getString(Keys.federation.passphrase, "");
  1595. if (StringUtils.isEmpty(passphrase)) {
  1596. logger.warn("Federation passphrase is blank! This server can not be PULLED from.");
  1597. validPassphrase = false;
  1598. }
  1599. if (validPassphrase) {
  1600. // standard tokens
  1601. for (FederationToken tokenType : FederationToken.values()) {
  1602. logger.info(MessageFormat.format("Federation {0} token = {1}", tokenType.name(),
  1603. getFederationToken(tokenType)));
  1604. }
  1605. // federation set tokens
  1606. for (String set : settings.getStrings(Keys.federation.sets)) {
  1607. logger.info(MessageFormat.format("Federation Set {0} token = {1}", set,
  1608. getFederationToken(set)));
  1609. }
  1610. }
  1611. // Schedule the federation executor
  1612. List<FederationModel> registrations = getFederationRegistrations();
  1613. if (registrations.size() > 0) {
  1614. FederationPullExecutor executor = new FederationPullExecutor(registrations, true);
  1615. scheduledExecutor.schedule(executor, 1, TimeUnit.MINUTES);
  1616. }
  1617. }
  1618. /**
  1619. * Returns the list of federated gitblit instances that this instance will
  1620. * try to pull.
  1621. *
  1622. * @return list of registered gitblit instances
  1623. */
  1624. public List<FederationModel> getFederationRegistrations() {
  1625. if (federationRegistrations.isEmpty()) {
  1626. federationRegistrations.addAll(FederationUtils.getFederationRegistrations(settings));
  1627. }
  1628. return federationRegistrations;
  1629. }
  1630. /**
  1631. * Retrieve the specified federation registration.
  1632. *
  1633. * @param name
  1634. * the name of the registration
  1635. * @return a federation registration
  1636. */
  1637. public FederationModel getFederationRegistration(String url, String name) {
  1638. // check registrations
  1639. for (FederationModel r : getFederationRegistrations()) {
  1640. if (r.name.equals(name) && r.url.equals(url)) {
  1641. return r;
  1642. }
  1643. }
  1644. // check the results
  1645. for (FederationModel r : getFederationResultRegistrations()) {
  1646. if (r.name.equals(name) && r.url.equals(url)) {
  1647. return r;
  1648. }
  1649. }
  1650. return null;
  1651. }
  1652. /**
  1653. * Returns the list of federation sets.
  1654. *
  1655. * @return list of federation sets
  1656. */
  1657. public List<FederationSet> getFederationSets(String gitblitUrl) {
  1658. List<FederationSet> list = new ArrayList<FederationSet>();
  1659. // generate standard tokens
  1660. for (FederationToken type : FederationToken.values()) {
  1661. FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));
  1662. fset.repositories = getRepositories(gitblitUrl, fset.token);
  1663. list.add(fset);
  1664. }
  1665. // generate tokens for federation sets
  1666. for (String set : settings.getStrings(Keys.federation.sets)) {
  1667. FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,
  1668. getFederationToken(set));
  1669. fset.repositories = getRepositories(gitblitUrl, fset.token);
  1670. list.add(fset);
  1671. }
  1672. return list;
  1673. }
  1674. /**
  1675. * Returns the list of possible federation tokens for this Gitblit instance.
  1676. *
  1677. * @return list of federation tokens
  1678. */
  1679. public List<String> getFederationTokens() {
  1680. List<String> tokens = new ArrayList<String>();
  1681. // generate standard tokens
  1682. for (FederationToken type : FederationToken.values()) {
  1683. tokens.add(getFederationToken(type));
  1684. }
  1685. // generate tokens for federation sets
  1686. for (String set : settings.getStrings(Keys.federation.sets)) {
  1687. tokens.add(getFederationToken(set));
  1688. }
  1689. return tokens;
  1690. }
  1691. /**
  1692. * Returns the specified federation token for this Gitblit instance.
  1693. *
  1694. * @param type
  1695. * @return a federation token
  1696. */
  1697. public String getFederationToken(FederationToken type) {
  1698. return getFederationToken(type.name());
  1699. }
  1700. /**
  1701. * Returns the specified federation token for this Gitblit instance.
  1702. *
  1703. * @param value
  1704. * @return a federation token
  1705. */
  1706. public String getFederationToken(String value) {
  1707. String passphrase = settings.getString(Keys.federation.passphrase, "");
  1708. return StringUtils.getSHA1(passphrase + "-" + value);
  1709. }
  1710. /**
  1711. * Compares the provided token with this Gitblit instance's tokens and
  1712. * determines if the requested permission may be granted to the token.
  1713. *
  1714. * @param req
  1715. * @param token
  1716. * @return true if the request can be executed
  1717. */
  1718. public boolean validateFederationRequest(FederationRequest req, String token) {
  1719. String all = getFederationToken(FederationToken.ALL);
  1720. String unr = getFederationToken(FederationToken.USERS_AND_REPOSITORIES);
  1721. String jur = getFederationToken(FederationToken.REPOSITORIES);
  1722. switch (req) {
  1723. case PULL_REPOSITORIES:
  1724. return token.equals(all) || token.equals(unr) || token.equals(jur);
  1725. case PULL_USERS:
  1726. case PULL_TEAMS:
  1727. return token.equals(all) || token.equals(unr);
  1728. case PULL_SETTINGS:
  1729. case PULL_SCRIPTS:
  1730. return token.equals(all);
  1731. }
  1732. return false;
  1733. }
  1734. /**
  1735. * Acknowledge and cache the status of a remote Gitblit instance.
  1736. *
  1737. * @param identification
  1738. * the identification of the pulling Gitblit instance
  1739. * @param registration
  1740. * the registration from the pulling Gitblit instance
  1741. * @return true if acknowledged
  1742. */
  1743. public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
  1744. // reset the url to the identification of the pulling Gitblit instance
  1745. registration.url = identification;
  1746. String id = identification;
  1747. if (!StringUtils.isEmpty(registration.folder)) {
  1748. id += "-" + registration.folder;
  1749. }
  1750. federationPullResults.put(id, registration);
  1751. return true;
  1752. }
  1753. /**
  1754. * Returns the list of registration results.
  1755. *
  1756. * @return the list of registration results
  1757. */
  1758. public List<FederationModel> getFederationResultRegistrations() {
  1759. return new ArrayList<FederationModel>(federationPullResults.values());
  1760. }
  1761. /**
  1762. * Submit a federation proposal. The proposal is cached locally and the
  1763. * Gitblit administrator(s) are notified via email.
  1764. *
  1765. * @param proposal
  1766. * the proposal
  1767. * @param gitblitUrl
  1768. * the url of your gitblit instance to send an email to
  1769. * administrators
  1770. * @return true if the proposal was submitted
  1771. */
  1772. public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
  1773. // convert proposal to json
  1774. String json = JsonUtils.toJsonString(proposal);
  1775. try {
  1776. // make the proposals folder
  1777. File proposalsFolder = getProposalsFolder();
  1778. proposalsFolder.mkdirs();
  1779. // cache json to a file
  1780. File file = new File(proposalsFolder, proposal.token + Constants.PROPOSAL_EXT);
  1781. com.gitblit.utils.FileUtils.writeContent(file, json);
  1782. } catch (Exception e) {
  1783. logger.error(MessageFormat.format("Failed to cache proposal from {0}", proposal.url), e);
  1784. }
  1785. // send an email, if possible
  1786. try {
  1787. Message message = mailExecutor.createMessageForAdministrators();
  1788. if (message != null) {
  1789. message.setSubject("Federation proposal from " + proposal.url);
  1790. message.setText("Please review the proposal @ " + gitblitUrl + "/proposal/"
  1791. + proposal.token);
  1792. mailExecutor.queue(message);
  1793. }
  1794. } catch (Throwable t) {
  1795. logger.error("Failed to notify administrators of proposal", t);
  1796. }
  1797. return true;
  1798. }
  1799. /**
  1800. * Returns the list of pending federation proposals
  1801. *
  1802. * @return list of federation proposals
  1803. */
  1804. public List<FederationProposal> getPendingFederationProposals() {
  1805. List<FederationProposal> list = new ArrayList<FederationProposal>();
  1806. File folder = getProposalsFolder();
  1807. if (folder.exists()) {
  1808. File[] files = folder.listFiles(new FileFilter() {
  1809. @Override
  1810. public boolean accept(File file) {
  1811. return file.isFile()
  1812. && file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
  1813. }
  1814. });
  1815. for (File file : files) {
  1816. String json = com.gitblit.utils.FileUtils.readContent(file, null);
  1817. FederationProposal proposal = JsonUtils.fromJsonString(json,
  1818. FederationProposal.class);
  1819. list.add(proposal);
  1820. }
  1821. }
  1822. return list;
  1823. }
  1824. /**
  1825. * Get repositories for the specified token.
  1826. *
  1827. * @param gitblitUrl
  1828. * the base url of this gitblit instance
  1829. * @param token
  1830. * the federation token
  1831. * @return a map of <cloneurl, RepositoryModel>
  1832. */
  1833. public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
  1834. Map<String, String> federationSets = new HashMap<String, String>();
  1835. for (String set : getStrings(Keys.federation.sets)) {
  1836. federationSets.put(getFederationToken(set), set);
  1837. }
  1838. // Determine the Gitblit clone url
  1839. StringBuilder sb = new StringBuilder();
  1840. sb.append(gitblitUrl);
  1841. sb.append(Constants.GIT_PATH);
  1842. sb.append("{0}");
  1843. String cloneUrl = sb.toString();
  1844. // Retrieve all available repositories
  1845. UserModel user = new UserModel(Constants.FEDERATION_USER);
  1846. user.canAdmin = true;
  1847. List<RepositoryModel> list = getRepositoryModels(user);
  1848. // create the [cloneurl, repositoryModel] map
  1849. Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
  1850. for (RepositoryModel model : list) {
  1851. // by default, setup the url for THIS repository
  1852. String url = MessageFormat.format(cloneUrl, model.name);
  1853. switch (model.federationStrategy) {
  1854. case EXCLUDE:
  1855. // skip this repository
  1856. continue;
  1857. case FEDERATE_ORIGIN:
  1858. // federate the origin, if it is defined
  1859. if (!StringUtils.isEmpty(model.origin)) {
  1860. url = model.origin;
  1861. }
  1862. break;
  1863. }
  1864. if (federationSets.containsKey(token)) {
  1865. // include repositories only for federation set
  1866. String set = federationSets.get(token);
  1867. if (model.federationSets.contains(set)) {
  1868. repositories.put(url, model);
  1869. }
  1870. } else {
  1871. // standard federation token for ALL
  1872. repositories.put(url, model);
  1873. }
  1874. }
  1875. return repositories;
  1876. }
  1877. /**
  1878. * Creates a proposal from the token.
  1879. *
  1880. * @param gitblitUrl
  1881. * the url of this Gitblit instance
  1882. * @param token
  1883. * @return a potential proposal
  1884. */
  1885. public FederationProposal createFederationProposal(String gitblitUrl, String token) {
  1886. FederationToken tokenType = FederationToken.REPOSITORIES;
  1887. for (FederationToken type : FederationToken.values()) {
  1888. if (token.equals(getFederationToken(type))) {
  1889. tokenType = type;
  1890. break;
  1891. }
  1892. }
  1893. Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
  1894. FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token,
  1895. repositories);
  1896. return proposal;
  1897. }
  1898. /**
  1899. * Returns the proposal identified by the supplied token.
  1900. *
  1901. * @param token
  1902. * @return the specified proposal or null
  1903. */
  1904. public FederationProposal getPendingFederationProposal(String token) {
  1905. List<FederationProposal> list = getPendingFederationProposals();
  1906. for (FederationProposal proposal : list) {
  1907. if (proposal.token.equals(token)) {
  1908. return proposal;
  1909. }
  1910. }
  1911. return null;
  1912. }
  1913. /**
  1914. * Deletes a pending federation proposal.
  1915. *
  1916. * @param a
  1917. * proposal
  1918. * @return true if the proposal was deleted
  1919. */
  1920. public boolean deletePendingFederationProposal(FederationProposal proposal) {
  1921. File folder = getProposalsFolder();
  1922. File file = new File(folder, proposal.token + Constants.PROPOSAL_EXT);
  1923. return file.delete();
  1924. }
  1925. /**
  1926. * Returns the list of all Groovy push hook scripts. Script files must have
  1927. * .groovy extension
  1928. *
  1929. * @return list of available hook scripts
  1930. */
  1931. public List<String> getAllScripts() {
  1932. File groovyFolder = getGroovyScriptsFolder();
  1933. File[] files = groovyFolder.listFiles(new FileFilter() {
  1934. @Override
  1935. public boolean accept(File pathname) {
  1936. return pathname.isFile() && pathname.getName().endsWith(".groovy");
  1937. }
  1938. });
  1939. List<String> scripts = new ArrayList<String>();
  1940. if (files != null) {
  1941. for (File file : files) {
  1942. String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
  1943. scripts.add(script);
  1944. }
  1945. }
  1946. return scripts;
  1947. }
  1948. /**
  1949. * Returns the list of pre-receive scripts the repository inherited from the
  1950. * global settings and team affiliations.
  1951. *
  1952. * @param repository
  1953. * if null only the globally specified scripts are returned
  1954. * @return a list of scripts
  1955. */
  1956. public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
  1957. Set<String> scripts = new LinkedHashSet<String>();
  1958. // Globals
  1959. for (String script : getStrings(Keys.groovy.preReceiveScripts)) {
  1960. if (script.endsWith(".groovy")) {
  1961. scripts.add(script.substring(0, script.lastIndexOf('.')));
  1962. } else {
  1963. scripts.add(script);
  1964. }
  1965. }
  1966. // Team Scripts
  1967. if (repository != null) {
  1968. for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
  1969. TeamModel team = userService.getTeamModel(teamname);
  1970. scripts.addAll(team.preReceiveScripts);
  1971. }
  1972. }
  1973. return new ArrayList<String>(scripts);
  1974. }
  1975. /**
  1976. * Returns the list of all available Groovy pre-receive push hook scripts
  1977. * that are not already inherited by the repository. Script files must have
  1978. * .groovy extension
  1979. *
  1980. * @param repository
  1981. * optional parameter
  1982. * @return list of available hook scripts
  1983. */
  1984. public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
  1985. Set<String> inherited = new TreeSet<String>(getPreReceiveScriptsInherited(repository));
  1986. // create list of available scripts by excluding inherited scripts
  1987. List<String> scripts = new ArrayList<String>();
  1988. for (String script : getAllScripts()) {
  1989. if (!inherited.contains(script)) {
  1990. scripts.add(script);
  1991. }
  1992. }
  1993. return scripts;
  1994. }
  1995. /**
  1996. * Returns the list of post-receive scripts the repository inherited from
  1997. * the global settings and team affiliations.
  1998. *
  1999. * @param repository
  2000. * if null only the globally specified scripts are returned
  2001. * @return a list of scripts
  2002. */
  2003. public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
  2004. Set<String> scripts = new LinkedHashSet<String>();
  2005. // Global Scripts
  2006. for (String script : getStrings(Keys.groovy.postReceiveScripts)) {
  2007. if (script.endsWith(".groovy")) {
  2008. scripts.add(script.substring(0, script.lastIndexOf('.')));
  2009. } else {
  2010. scripts.add(script);
  2011. }
  2012. }
  2013. // Team Scripts
  2014. if (repository != null) {
  2015. for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
  2016. TeamModel team = userService.getTeamModel(teamname);
  2017. scripts.addAll(team.postReceiveScripts);
  2018. }
  2019. }
  2020. return new ArrayList<String>(scripts);
  2021. }
  2022. /**
  2023. * Returns the list of unused Groovy post-receive push hook scripts that are
  2024. * not already inherited by the repository. Script files must have .groovy
  2025. * extension
  2026. *
  2027. * @param repository
  2028. * optional parameter
  2029. * @return list of available hook scripts
  2030. */
  2031. public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
  2032. Set<String> inherited = new TreeSet<String>(getPostReceiveScriptsInherited(repository));
  2033. // create list of available scripts by excluding inherited scripts
  2034. List<String> scripts = new ArrayList<String>();
  2035. for (String script : getAllScripts()) {
  2036. if (!inherited.contains(script)) {
  2037. scripts.add(script);
  2038. }
  2039. }
  2040. return scripts;
  2041. }
  2042. /**
  2043. * Search the specified repositories using the Lucene query.
  2044. *
  2045. * @param query
  2046. * @param page
  2047. * @param pageSize
  2048. * @param repositories
  2049. * @return
  2050. */
  2051. public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {
  2052. List<SearchResult> srs = luceneExecutor.search(query, page, pageSize, repositories);
  2053. return srs;
  2054. }
  2055. /**
  2056. * Notify the administrators by email.
  2057. *
  2058. * @param subject
  2059. * @param message
  2060. */
  2061. public void sendMailToAdministrators(String subject, String message) {
  2062. try {
  2063. Message mail = mailExecutor.createMessageForAdministrators();
  2064. if (mail != null) {
  2065. mail.setSubject(subject);
  2066. mail.setText(message);
  2067. mailExecutor.queue(mail);
  2068. }
  2069. } catch (MessagingException e) {
  2070. logger.error("Messaging error", e);
  2071. }
  2072. }
  2073. /**
  2074. * Notify users by email of something.
  2075. *
  2076. * @param subject
  2077. * @param message
  2078. * @param toAddresses
  2079. */
  2080. public void sendMail(String subject, String message, Collection<String> toAddresses) {
  2081. this.sendMail(subject, message, toAddresses.toArray(new String[0]));
  2082. }
  2083. /**
  2084. * Notify users by email of something.
  2085. *
  2086. * @param subject
  2087. * @param message
  2088. * @param toAddresses
  2089. */
  2090. public void sendMail(String subject, String message, String... toAddresses) {
  2091. try {
  2092. Message mail = mailExecutor.createMessage(toAddresses);
  2093. if (mail != null) {
  2094. mail.setSubject(subject);
  2095. mail.setText(message);
  2096. mailExecutor.queue(mail);
  2097. }
  2098. } catch (MessagingException e) {
  2099. logger.error("Messaging error", e);
  2100. }
  2101. }
  2102. /**
  2103. * Returns the descriptions/comments of the Gitblit config settings.
  2104. *
  2105. * @return SettingsModel
  2106. */
  2107. public ServerSettings getSettingsModel() {
  2108. // ensure that the current values are updated in the setting models
  2109. for (String key : settings.getAllKeys(null)) {
  2110. SettingModel setting = settingsModel.get(key);
  2111. if (setting == null) {
  2112. // unreferenced setting, create a setting model
  2113. setting = new SettingModel();
  2114. setting.name = key;
  2115. settingsModel.add(setting);
  2116. }
  2117. setting.currentValue = settings.getString(key, "");
  2118. }
  2119. settingsModel.pushScripts = getAllScripts();
  2120. return settingsModel;
  2121. }
  2122. /**
  2123. * Parse the properties file and aggregate all the comments by the setting
  2124. * key. A setting model tracks the current value, the default value, the
  2125. * description of the setting and and directives about the setting.
  2126. *
  2127. * @return Map<String, SettingModel>
  2128. */
  2129. private ServerSettings loadSettingModels() {
  2130. ServerSettings settingsModel = new ServerSettings();
  2131. settingsModel.supportsCredentialChanges = userService.supportsCredentialChanges();
  2132. settingsModel.supportsDisplayNameChanges = userService.supportsDisplayNameChanges();
  2133. settingsModel.supportsEmailAddressChanges = userService.supportsEmailAddressChanges();
  2134. settingsModel.supportsTeamMembershipChanges = userService.supportsTeamMembershipChanges();
  2135. try {
  2136. // Read bundled Gitblit properties to extract setting descriptions.
  2137. // This copy is pristine and only used for populating the setting
  2138. // models map.
  2139. InputStream is = servletContext.getResourceAsStream("/WEB-INF/reference.properties");
  2140. BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
  2141. StringBuilder description = new StringBuilder();
  2142. SettingModel setting = new SettingModel();
  2143. String line = null;
  2144. while ((line = propertiesReader.readLine()) != null) {
  2145. if (line.length() == 0) {
  2146. description.setLength(0);
  2147. setting = new SettingModel();
  2148. } else {
  2149. if (line.charAt(0) == '#') {
  2150. if (line.length() > 1) {
  2151. String text = line.substring(1).trim();
  2152. if (SettingModel.CASE_SENSITIVE.equals(text)) {
  2153. setting.caseSensitive = true;
  2154. } else if (SettingModel.RESTART_REQUIRED.equals(text)) {
  2155. setting.restartRequired = true;
  2156. } else if (SettingModel.SPACE_DELIMITED.equals(text)) {
  2157. setting.spaceDelimited = true;
  2158. } else if (text.startsWith(SettingModel.SINCE)) {
  2159. try {
  2160. setting.since = text.split(" ")[1];
  2161. } catch (Exception e) {
  2162. setting.since = text;
  2163. }
  2164. } else {
  2165. description.append(text);
  2166. description.append('\n');
  2167. }
  2168. }
  2169. } else {
  2170. String[] kvp = line.split("=", 2);
  2171. String key = kvp[0].trim();
  2172. setting.name = key;
  2173. setting.defaultValue = kvp[1].trim();
  2174. setting.currentValue = setting.defaultValue;
  2175. setting.description = description.toString().trim();
  2176. settingsModel.add(setting);
  2177. description.setLength(0);
  2178. setting = new SettingModel();
  2179. }
  2180. }
  2181. }
  2182. propertiesReader.close();
  2183. } catch (NullPointerException e) {
  2184. logger.error("Failed to find resource copy of gitblit.properties");
  2185. } catch (IOException e) {
  2186. logger.error("Failed to load resource copy of gitblit.properties");
  2187. }
  2188. return settingsModel;
  2189. }
  2190. /**
  2191. * Configure the Gitblit singleton with the specified settings source. This
  2192. * source may be file settings (Gitblit GO) or may be web.xml settings
  2193. * (Gitblit WAR).
  2194. *
  2195. * @param settings
  2196. */
  2197. public void configureContext(IStoredSettings settings, boolean startFederation) {
  2198. logger.info("Reading configuration from " + settings.toString());
  2199. this.settings = settings;
  2200. repositoriesFolder = getRepositoriesFolder();
  2201. logger.info("Git repositories folder " + repositoriesFolder.getAbsolutePath());
  2202. repositoryResolver = new FileResolver<Void>(repositoriesFolder, true);
  2203. // calculate repository list settings checksum for future config changes
  2204. repositoryListSettingsChecksum.set(getRepositoryListSettingsChecksum());
  2205. // build initial repository list
  2206. if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
  2207. logger.info("Identifying available repositories...");
  2208. getRepositoryList();
  2209. }
  2210. logTimezone("JVM", TimeZone.getDefault());
  2211. logTimezone(Constants.NAME, getTimezone());
  2212. serverStatus = new ServerStatus(isGO());
  2213. String realm = settings.getString(Keys.realm.userService, "users.properties");
  2214. IUserService loginService = null;
  2215. try {
  2216. // check to see if this "file" is a login service class
  2217. Class<?> realmClass = Class.forName(realm);
  2218. loginService = (IUserService) realmClass.newInstance();
  2219. } catch (Throwable t) {
  2220. loginService = new GitblitUserService();
  2221. }
  2222. setUserService(loginService);
  2223. // load and cache the project metadata
  2224. projectConfigs = new FileBasedConfig(getFileOrFolder(Keys.web.projectsFile, "projects.conf"), FS.detect());
  2225. getProjectConfigs();
  2226. mailExecutor = new MailExecutor(settings);
  2227. if (mailExecutor.isReady()) {
  2228. logger.info("Mail executor is scheduled to process the message queue every 2 minutes.");
  2229. scheduledExecutor.scheduleAtFixedRate(mailExecutor, 1, 2, TimeUnit.MINUTES);
  2230. } else {
  2231. logger.warn("Mail server is not properly configured. Mail services disabled.");
  2232. }
  2233. luceneExecutor = new LuceneExecutor(settings, repositoriesFolder);
  2234. logger.info("Lucene executor is scheduled to process indexed branches every 2 minutes.");
  2235. scheduledExecutor.scheduleAtFixedRate(luceneExecutor, 1, 2, TimeUnit.MINUTES);
  2236. if (startFederation) {
  2237. configureFederation();
  2238. }
  2239. // Configure JGit
  2240. WindowCacheConfig cfg = new WindowCacheConfig();
  2241. cfg.setPackedGitWindowSize(settings.getFilesize(Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
  2242. cfg.setPackedGitLimit(settings.getFilesize(Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
  2243. cfg.setDeltaBaseCacheLimit(settings.getFilesize(Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
  2244. cfg.setPackedGitOpenFiles(settings.getFilesize(Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
  2245. cfg.setStreamFileThreshold(settings.getFilesize(Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
  2246. cfg.setPackedGitMMAP(settings.getBoolean(Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
  2247. try {
  2248. WindowCache.reconfigure(cfg);
  2249. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
  2250. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
  2251. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
  2252. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
  2253. logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
  2254. logger.debug(MessageFormat.format("{0} = {1}", Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
  2255. } catch (IllegalArgumentException e) {
  2256. logger.error("Failed to configure JGit parameters!", e);
  2257. }
  2258. ContainerUtils.CVE_2007_0450.test();
  2259. }
  2260. private void logTimezone(String type, TimeZone zone) {
  2261. SimpleDateFormat df = new SimpleDateFormat("z Z");
  2262. df.setTimeZone(zone);
  2263. String offset = df.format(new Date());
  2264. logger.info(type + " timezone is " + zone.getID() + " (" + offset + ")");
  2265. }
  2266. /**
  2267. * Configure Gitblit from the web.xml, if no configuration has already been
  2268. * specified.
  2269. *
  2270. * @see ServletContextListener.contextInitialize(ServletContextEvent)
  2271. */
  2272. @Override
  2273. public void contextInitialized(ServletContextEvent contextEvent) {
  2274. servletContext = contextEvent.getServletContext();
  2275. if (settings == null) {
  2276. // Gitblit WAR is running in a servlet container
  2277. ServletContext context = contextEvent.getServletContext();
  2278. WebXmlSettings webxmlSettings = new WebXmlSettings(context);
  2279. // 0.7.0 web.properties in the deployed war folder
  2280. String webProps = context.getRealPath("/WEB-INF/web.properties");
  2281. if (!StringUtils.isEmpty(webProps)) {
  2282. File overrideFile = new File(webProps);
  2283. if (overrideFile.exists()) {
  2284. webxmlSettings.applyOverrides(overrideFile);
  2285. }
  2286. }
  2287. // 0.8.0 gitblit.properties file located outside the deployed war
  2288. // folder lie, for example, on RedHat OpenShift.
  2289. File overrideFile = getFileOrFolder("gitblit.properties");
  2290. if (!overrideFile.getPath().equals("gitblit.properties")) {
  2291. webxmlSettings.applyOverrides(overrideFile);
  2292. }
  2293. configureContext(webxmlSettings, true);
  2294. // Copy the included scripts to the configured groovy folder
  2295. File localScripts = getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
  2296. if (!localScripts.exists()) {
  2297. File includedScripts = new File(context.getRealPath("/WEB-INF/groovy"));
  2298. if (!includedScripts.equals(localScripts)) {
  2299. try {
  2300. com.gitblit.utils.FileUtils.copy(localScripts, includedScripts.listFiles());
  2301. } catch (IOException e) {
  2302. logger.error(MessageFormat.format(
  2303. "Failed to copy included Groovy scripts from {0} to {1}",
  2304. includedScripts, localScripts));
  2305. }
  2306. }
  2307. }
  2308. }
  2309. settingsModel = loadSettingModels();
  2310. serverStatus.servletContainer = servletContext.getServerInfo();
  2311. }
  2312. /**
  2313. * Gitblit is being shutdown either because the servlet container is
  2314. * shutting down or because the servlet container is re-deploying Gitblit.
  2315. */
  2316. @Override
  2317. public void contextDestroyed(ServletContextEvent contextEvent) {
  2318. logger.info("Gitblit context destroyed by servlet container.");
  2319. scheduledExecutor.shutdownNow();
  2320. luceneExecutor.close();
  2321. }
  2322. /**
  2323. * Creates a personal fork of the specified repository. The clone is view
  2324. * restricted by default and the owner of the source repository is given
  2325. * access to the clone.
  2326. *
  2327. * @param repository
  2328. * @param user
  2329. * @return true, if successful
  2330. */
  2331. public boolean fork(RepositoryModel repository, UserModel user) {
  2332. String cloneName = MessageFormat.format("~{0}/{1}.git", user.username, StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name)));
  2333. String fromUrl = MessageFormat.format("file://{0}/{1}", repositoriesFolder.getAbsolutePath(), repository.name);
  2334. try {
  2335. // clone the repository
  2336. JGitUtils.cloneRepository(repositoriesFolder, cloneName, fromUrl, true, null);
  2337. // create a Gitblit repository model for the clone
  2338. RepositoryModel cloneModel = repository.cloneAs(cloneName);
  2339. cloneModel.owner = user.username;
  2340. updateRepositoryModel(cloneName, cloneModel, false);
  2341. if (AuthorizationControl.NAMED.equals(cloneModel.authorizationControl)) {
  2342. // add the owner of the source repository to the clone's access list
  2343. if (!StringUtils.isEmpty(repository.owner)) {
  2344. UserModel owner = getUserModel(repository.owner);
  2345. if (owner != null) {
  2346. owner.repositories.add(cloneName);
  2347. updateUserModel(owner.username, owner, false);
  2348. }
  2349. }
  2350. // inherit origin's access lists
  2351. List<String> users = getRepositoryUsers(repository);
  2352. setRepositoryUsers(cloneModel, users);
  2353. List<String> teams = getRepositoryTeams(repository);
  2354. setRepositoryTeams(cloneModel, teams);
  2355. }
  2356. // add this clone to the cached model
  2357. addToCachedRepositoryList(cloneModel.name, cloneModel);
  2358. return true;
  2359. } catch (Exception e) {
  2360. logger.error("failed to fork", e);
  2361. }
  2362. return false;
  2363. }
  2364. }