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

GitBlit.java 129KB

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