You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GitBlit.java 132KB

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