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

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