Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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