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

GitBlit.java 131KB

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