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

GitBlit.java 129KB

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