Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

GitBlit.java 117KB

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