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

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