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

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