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 100KB

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