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

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