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

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