James Moger
2012-09-10 fabe060d3a435f116128851f828e35c2af5fde67
commit | author | age
f13c4c 1 /*
JM 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  */
fc948c 16 package com.gitblit;
JM 17
b75734 18 import java.io.BufferedReader;
fc948c 19 import java.io.File;
831469 20 import java.io.FileFilter;
f97bf0 21 import java.io.IOException;
b75734 22 import java.io.InputStream;
JM 23 import java.io.InputStreamReader;
dd6f08 24 import java.lang.reflect.Field;
166e6a 25 import java.text.MessageFormat;
6c6e7d 26 import java.text.SimpleDateFormat;
fc948c 27 import java.util.ArrayList;
8f73a7 28 import java.util.Arrays;
0b9119 29 import java.util.Collection;
00afd7 30 import java.util.Collections;
6c6e7d 31 import java.util.Date;
8c9a20 32 import java.util.HashMap;
7c1cdc 33 import java.util.LinkedHashMap;
d7905a 34 import java.util.LinkedHashSet;
fc948c 35 import java.util.List;
8c9a20 36 import java.util.Map;
JM 37 import java.util.Map.Entry;
6cc1d4 38 import java.util.Set;
6c6e7d 39 import java.util.TimeZone;
13a3f5 40 import java.util.TreeMap;
d7905a 41 import java.util.TreeSet;
831469 42 import java.util.concurrent.ConcurrentHashMap;
JM 43 import java.util.concurrent.Executors;
44 import java.util.concurrent.ScheduledExecutorService;
45 import java.util.concurrent.TimeUnit;
dd6f08 46 import java.util.concurrent.atomic.AtomicInteger;
fee060 47 import java.util.concurrent.atomic.AtomicReference;
fc948c 48
831469 49 import javax.mail.Message;
JM 50 import javax.mail.MessagingException;
b75734 51 import javax.servlet.ServletContext;
87cc1e 52 import javax.servlet.ServletContextEvent;
JM 53 import javax.servlet.ServletContextListener;
85c2e6 54 import javax.servlet.http.Cookie;
fc948c 55
85c2e6 56 import org.apache.wicket.protocol.http.WebResponse;
fc948c 57 import org.eclipse.jgit.errors.RepositoryNotFoundException;
JM 58 import org.eclipse.jgit.lib.Repository;
5c2841 59 import org.eclipse.jgit.lib.RepositoryCache.FileKey;
f97bf0 60 import org.eclipse.jgit.lib.StoredConfig;
cdf77b 61 import org.eclipse.jgit.storage.file.FileBasedConfig;
478678 62 import org.eclipse.jgit.storage.file.WindowCache;
JM 63 import org.eclipse.jgit.storage.file.WindowCacheConfig;
5d9bd7 64 import org.eclipse.jgit.transport.ServiceMayNotContinueException;
f5d0ad 65 import org.eclipse.jgit.transport.resolver.FileResolver;
892570 66 import org.eclipse.jgit.transport.resolver.RepositoryResolver;
JM 67 import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException;
f5d0ad 68 import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException;
5c2841 69 import org.eclipse.jgit.util.FS;
8a2e9c 70 import org.eclipse.jgit.util.FileUtils;
fc948c 71 import org.slf4j.Logger;
JM 72 import org.slf4j.LoggerFactory;
73
dfb889 74 import com.gitblit.Constants.AccessRestrictionType;
6adf56 75 import com.gitblit.Constants.AuthorizationControl;
831469 76 import com.gitblit.Constants.FederationRequest;
JM 77 import com.gitblit.Constants.FederationStrategy;
78 import com.gitblit.Constants.FederationToken;
79 import com.gitblit.models.FederationModel;
80 import com.gitblit.models.FederationProposal;
31abc2 81 import com.gitblit.models.FederationSet;
4d44cf 82 import com.gitblit.models.Metric;
13a3f5 83 import com.gitblit.models.ProjectModel;
1f9dae 84 import com.gitblit.models.RepositoryModel;
d896e6 85 import com.gitblit.models.SearchResult;
d03aff 86 import com.gitblit.models.ServerSettings;
b75734 87 import com.gitblit.models.ServerStatus;
JM 88 import com.gitblit.models.SettingModel;
fe24a0 89 import com.gitblit.models.TeamModel;
1f9dae 90 import com.gitblit.models.UserModel;
0db5c4 91 import com.gitblit.utils.ArrayUtils;
72633d 92 import com.gitblit.utils.ByteFormat;
165254 93 import com.gitblit.utils.ContainerUtils;
cdf77b 94 import com.gitblit.utils.DeepCopier;
f6740d 95 import com.gitblit.utils.FederationUtils;
fc948c 96 import com.gitblit.utils.JGitUtils;
93f0b1 97 import com.gitblit.utils.JsonUtils;
4d44cf 98 import com.gitblit.utils.MetricUtils;
9275bd 99 import com.gitblit.utils.ObjectCache;
00afd7 100 import com.gitblit.utils.StringUtils;
fc948c 101
892570 102 /**
JM 103  * GitBlit is the servlet context listener singleton that acts as the core for
104  * the web ui and the servlets. This class is either directly instantiated by
105  * the GitBlitServer class (Gitblit GO) or is reflectively instantiated from the
106  * definition in the web.xml file (Gitblit WAR).
107  * 
108  * This class is the central logic processor for Gitblit. All settings, user
109  * object, and repository object operations pass through this class.
110  * 
111  * Repository Resolution. There are two pathways for finding repositories. One
112  * pathway, for web ui display and repository authentication & authorization, is
113  * within this class. The other pathway is through the standard GitServlet.
114  * 
115  * @author James Moger
116  * 
117  */
87cc1e 118 public class GitBlit implements ServletContextListener {
fc948c 119
5450d0 120     private static GitBlit gitblit;
6c6e7d 121     
fc948c 122     private final Logger logger = LoggerFactory.getLogger(GitBlit.class);
JM 123
831469 124     private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5);
JM 125
126     private final List<FederationModel> federationRegistrations = Collections
127             .synchronizedList(new ArrayList<FederationModel>());
128
129     private final Map<String, FederationModel> federationPullResults = new ConcurrentHashMap<String, FederationModel>();
4d44cf 130
JM 131     private final ObjectCache<Long> repositorySizeCache = new ObjectCache<Long>();
132
133     private final ObjectCache<List<Metric>> repositoryMetricsCache = new ObjectCache<List<Metric>>();
fee060 134     
cdf77b 135     private final Map<String, RepositoryModel> repositoryListCache = new ConcurrentHashMap<String, RepositoryModel>();
fee060 136     
13a3f5 137     private final Map<String, ProjectModel> projectCache = new ConcurrentHashMap<String, ProjectModel>();
JM 138     
fee060 139     private final AtomicReference<String> repositoryListSettingsChecksum = new AtomicReference<String>("");
831469 140
892570 141     private RepositoryResolver<Void> repositoryResolver;
fc948c 142
b75734 143     private ServletContext servletContext;
JM 144
166e6a 145     private File repositoriesFolder;
fc948c 146
85c2e6 147     private IUserService userService;
fc948c 148
892570 149     private IStoredSettings settings;
b75734 150
84c1d5 151     private ServerSettings settingsModel;
b75734 152
JM 153     private ServerStatus serverStatus;
831469 154
JM 155     private MailExecutor mailExecutor;
6c6e7d 156     
e31da0 157     private LuceneExecutor luceneExecutor;
JM 158     
6c6e7d 159     private TimeZone timezone;
13a3f5 160     
JM 161     private FileBasedConfig projectConfigs;
87cc1e 162
5450d0 163     public GitBlit() {
JM 164         if (gitblit == null) {
892570 165             // set the static singleton reference
5450d0 166             gitblit = this;
JM 167         }
87cc1e 168     }
JM 169
892570 170     /**
JM 171      * Returns the Gitblit singleton.
172      * 
173      * @return gitblit singleton
174      */
2a7306 175     public static GitBlit self() {
5450d0 176         if (gitblit == null) {
892570 177             new GitBlit();
5450d0 178         }
JM 179         return gitblit;
831469 180     }
JM 181
182     /**
183      * Determine if this is the GO variant of Gitblit.
184      * 
185      * @return true if this is the GO variant of Gitblit.
186      */
187     public static boolean isGO() {
188         return self().settings instanceof FileSettings;
6c6e7d 189     }
JM 190     
191     /**
192      * Returns the preferred timezone for the Gitblit instance.
193      * 
194      * @return a timezone
195      */
196     public static TimeZone getTimezone() {
197         if (self().timezone == null) {
198             String tzid = getString("web.timezone", null);
199             if (StringUtils.isEmpty(tzid)) {
200                 self().timezone = TimeZone.getDefault();
201                 return self().timezone;
202             }
203             self().timezone = TimeZone.getTimeZone(tzid);
204         }
205         return self().timezone;
2a7306 206     }
3d0494 207     
ae9e15 208     /**
JM 209      * Returns the user-defined blob encodings.
210      * 
211      * @return an array of encodings, may be empty
212      */
213     public static String [] getEncodings() {
214         return getStrings(Keys.web.blobEncodings).toArray(new String[0]);
215     }
216     
2a7306 217
892570 218     /**
JM 219      * Returns the boolean value for the specified key. If the key does not
220      * exist or the value for the key can not be interpreted as a boolean, the
221      * defaultValue is returned.
222      * 
223      * @see IStoredSettings.getBoolean(String, boolean)
224      * @param key
225      * @param defaultValue
226      * @return key value or defaultValue
227      */
2a7306 228     public static boolean getBoolean(String key, boolean defaultValue) {
892570 229         return self().settings.getBoolean(key, defaultValue);
2a7306 230     }
JM 231
892570 232     /**
JM 233      * Returns the integer value for the specified key. If the key does not
234      * exist or the value for the key can not be interpreted as an integer, the
235      * defaultValue is returned.
236      * 
237      * @see IStoredSettings.getInteger(String key, int defaultValue)
238      * @param key
239      * @param defaultValue
240      * @return key value or defaultValue
241      */
2a7306 242     public static int getInteger(String key, int defaultValue) {
892570 243         return self().settings.getInteger(key, defaultValue);
2a7306 244     }
JM 245
892570 246     /**
7e5ee5 247      * Returns the char value for the specified key. If the key does not exist
JM 248      * or the value for the key can not be interpreted as a character, the
249      * defaultValue is returned.
250      * 
251      * @see IStoredSettings.getChar(String key, char defaultValue)
252      * @param key
253      * @param defaultValue
254      * @return key value or defaultValue
255      */
256     public static char getChar(String key, char defaultValue) {
257         return self().settings.getChar(key, defaultValue);
258     }
dd6f08 259
7e5ee5 260     /**
892570 261      * Returns the string value for the specified key. If the key does not exist
JM 262      * or the value for the key can not be interpreted as a string, the
263      * defaultValue is returned.
264      * 
265      * @see IStoredSettings.getString(String key, String defaultValue)
266      * @param key
267      * @param defaultValue
268      * @return key value or defaultValue
269      */
2a7306 270     public static String getString(String key, String defaultValue) {
892570 271         return self().settings.getString(key, defaultValue);
2a7306 272     }
JM 273
892570 274     /**
JM 275      * Returns a list of space-separated strings from the specified key.
276      * 
277      * @see IStoredSettings.getStrings(String key)
278      * @param name
279      * @return list of strings
280      */
2a7306 281     public static List<String> getStrings(String key) {
892570 282         return self().settings.getStrings(key);
7c1cdc 283     }
JM 284
285     /**
286      * Returns a map of space-separated key-value pairs from the specified key.
287      * 
288      * @see IStoredSettings.getStrings(String key)
289      * @param name
290      * @return map of string, string
291      */
292     public static Map<String, String> getMap(String key) {
293         return self().settings.getMap(key);
2a7306 294     }
892570 295
JM 296     /**
297      * Returns the list of keys whose name starts with the specified prefix. If
298      * the prefix is null or empty, all key names are returned.
299      * 
300      * @see IStoredSettings.getAllKeys(String key)
301      * @param startingWith
302      * @return list of keys
303      */
2a7306 304
JM 305     public static List<String> getAllKeys(String startingWith) {
892570 306         return self().settings.getAllKeys(startingWith);
fc948c 307     }
155bf7 308
892570 309     /**
JM 310      * Is Gitblit running in debug mode?
311      * 
312      * @return true if Gitblit is running in debug mode
313      */
8c9a20 314     public static boolean isDebugMode() {
892570 315         return self().settings.getBoolean(Keys.web.debugMode, false);
d03aff 316     }
JM 317
318     /**
b774de 319      * Returns the file object for the specified configuration key.
JM 320      * 
321      * @return the file
322      */
323     public static File getFileOrFolder(String key, String defaultFileOrFolder) {
324         String fileOrFolder = GitBlit.getString(key, defaultFileOrFolder);
325         return getFileOrFolder(fileOrFolder);
326     }
327
328     /**
329      * Returns the file object which may have it's base-path determined by
330      * environment variables for running on a cloud hosting service. All Gitblit
331      * file or folder retrievals are (at least initially) funneled through this
332      * method so it is the correct point to globally override/alter filesystem
333      * access based on environment or some other indicator.
334      * 
335      * @return the file
336      */
337     public static File getFileOrFolder(String fileOrFolder) {
338         String openShift = System.getenv("OPENSHIFT_DATA_DIR");
339         if (!StringUtils.isEmpty(openShift)) {
340             // running on RedHat OpenShift
341             return new File(openShift, fileOrFolder);
342         }
343         return new File(fileOrFolder);
344     }
345
346     /**
347      * Returns the path of the repositories folder. This method checks to see if
348      * Gitblit is running on a cloud service and may return an adjusted path.
349      * 
350      * @return the repositories folder path
351      */
352     public static File getRepositoriesFolder() {
353         return getFileOrFolder(Keys.git.repositoriesFolder, "git");
354     }
355
356     /**
357      * Returns the path of the proposals folder. This method checks to see if
358      * Gitblit is running on a cloud service and may return an adjusted path.
359      * 
360      * @return the proposals folder path
361      */
362     public static File getProposalsFolder() {
363         return getFileOrFolder(Keys.federation.proposalsFolder, "proposals");
6cc1d4 364     }
JM 365
366     /**
367      * Returns the path of the Groovy folder. This method checks to see if
368      * Gitblit is running on a cloud service and may return an adjusted path.
369      * 
370      * @return the Groovy scripts folder path
371      */
372     public static File getGroovyScriptsFolder() {
373         return getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
b774de 374     }
JM 375
376     /**
d03aff 377      * Updates the list of server settings.
JM 378      * 
379      * @param settings
380      * @return true if the update succeeded
381      */
97a20e 382     public boolean updateSettings(Map<String, String> updatedSettings) {
486ee1 383         return settings.saveSettings(updatedSettings);
b75734 384     }
JM 385
386     public ServerStatus getStatus() {
387         // update heap memory status
388         serverStatus.heapAllocated = Runtime.getRuntime().totalMemory();
389         serverStatus.heapFree = Runtime.getRuntime().freeMemory();
390         return serverStatus;
87cc1e 391     }
JM 392
892570 393     /**
JM 394      * Returns the list of non-Gitblit clone urls. This allows Gitblit to
395      * advertise alternative urls for Git client repository access.
396      * 
397      * @param repositoryName
398      * @return list of non-gitblit clone urls
399      */
8a2e9c 400     public List<String> getOtherCloneUrls(String repositoryName) {
JM 401         List<String> cloneUrls = new ArrayList<String>();
892570 402         for (String url : settings.getStrings(Keys.web.otherUrls)) {
8a2e9c 403             cloneUrls.add(MessageFormat.format(url, repositoryName));
JM 404         }
405         return cloneUrls;
fc948c 406     }
JM 407
892570 408     /**
JM 409      * Set the user service. The user service authenticates all users and is
410      * responsible for managing user permissions.
411      * 
412      * @param userService
413      */
85c2e6 414     public void setUserService(IUserService userService) {
JM 415         logger.info("Setting up user service " + userService.toString());
416         this.userService = userService;
63ee41 417         this.userService.setup(settings);
fc948c 418     }
6cca86 419     
JM 420     /**
421      * 
422      * @return true if the user service supports credential changes
423      */
424     public boolean supportsCredentialChanges() {
425         return userService.supportsCredentialChanges();
426     }
427
428     /**
429      * 
0aa8cf 430      * @return true if the user service supports display name changes
JM 431      */
432     public boolean supportsDisplayNameChanges() {
433         return userService.supportsDisplayNameChanges();
434     }
435
436     /**
437      * 
438      * @return true if the user service supports email address changes
439      */
440     public boolean supportsEmailAddressChanges() {
441         return userService.supportsEmailAddressChanges();
442     }
443
444     /**
445      * 
6cca86 446      * @return true if the user service supports team membership changes
JM 447      */
448     public boolean supportsTeamMembershipChanges() {
449         return userService.supportsTeamMembershipChanges();
450     }
fc948c 451
892570 452     /**
JM 453      * Authenticate a user based on a username and password.
454      * 
455      * @see IUserService.authenticate(String, char[])
456      * @param username
457      * @param password
458      * @return a user object or null
459      */
511554 460     public UserModel authenticate(String username, char[] password) {
831469 461         if (StringUtils.isEmpty(username)) {
JM 462             // can not authenticate empty username
463             return null;
464         }
465         String pw = new String(password);
466         if (StringUtils.isEmpty(pw)) {
467             // can not authenticate empty password
468             return null;
469         }
470
471         // check to see if this is the federation user
472         if (canFederate()) {
473             if (username.equalsIgnoreCase(Constants.FEDERATION_USER)) {
474                 List<String> tokens = getFederationTokens();
475                 if (tokens.contains(pw)) {
476                     // the federation user is an administrator
477                     UserModel federationUser = new UserModel(Constants.FEDERATION_USER);
478                     federationUser.canAdmin = true;
479                     return federationUser;
480                 }
481             }
482         }
483
484         // delegate authentication to the user service
85c2e6 485         if (userService == null) {
fc948c 486             return null;
JM 487         }
85c2e6 488         return userService.authenticate(username, password);
JM 489     }
490
892570 491     /**
JM 492      * Authenticate a user based on their cookie.
493      * 
494      * @param cookies
495      * @return a user object or null
496      */
85c2e6 497     public UserModel authenticate(Cookie[] cookies) {
JM 498         if (userService == null) {
499             return null;
500         }
501         if (userService.supportsCookies()) {
502             if (cookies != null && cookies.length > 0) {
503                 for (Cookie cookie : cookies) {
504                     if (cookie.getName().equals(Constants.NAME)) {
505                         String value = cookie.getValue();
506                         return userService.authenticate(value.toCharArray());
507                     }
508                 }
509             }
510         }
511         return null;
512     }
513
892570 514     /**
JM 515      * Sets a cookie for the specified user.
516      * 
517      * @param response
518      * @param user
519      */
85c2e6 520     public void setCookie(WebResponse response, UserModel user) {
JM 521         if (userService == null) {
522             return;
523         }
524         if (userService.supportsCookies()) {
525             Cookie userCookie;
526             if (user == null) {
527                 // clear cookie for logout
528                 userCookie = new Cookie(Constants.NAME, "");
529             } else {
530                 // set cookie for login
62aeb9 531                 String cookie = userService.getCookie(user);
JM 532                 if (StringUtils.isEmpty(cookie)) {
533                     // create empty cookie
534                     userCookie = new Cookie(Constants.NAME, "");
535                 } else {
536                     // create real cookie
537                     userCookie = new Cookie(Constants.NAME, cookie);
538                     userCookie.setMaxAge(Integer.MAX_VALUE);
539                 }
85c2e6 540             }
JM 541             userCookie.setPath("/");
542             response.addCookie(userCookie);
543         }
fc948c 544     }
ea094a 545     
JM 546     /**
547      * Logout a user.
548      * 
549      * @param user
550      */
551     public void logout(UserModel user) {
552         if (userService == null) {
553             return;
554         }
555         userService.logout(user);
556     }
fc948c 557
892570 558     /**
JM 559      * Returns the list of all users available to the login service.
560      * 
561      * @see IUserService.getAllUsernames()
562      * @return list of all usernames
563      */
f98825 564     public List<String> getAllUsernames() {
85c2e6 565         List<String> names = new ArrayList<String>(userService.getAllUsernames());
00afd7 566         return names;
abeaaf 567     }
e36d4d 568
abeaaf 569     /**
JM 570      * Returns the list of all users available to the login service.
571      * 
572      * @see IUserService.getAllUsernames()
573      * @return list of all usernames
574      */
575     public List<UserModel> getAllUsers() {
576         List<UserModel> users = userService.getAllUsers();
577         return users;
8a2e9c 578     }
JM 579
892570 580     /**
JM 581      * Delete the user object with the specified username
582      * 
583      * @see IUserService.deleteUser(String)
584      * @param username
585      * @return true if successful
586      */
8a2e9c 587     public boolean deleteUser(String username) {
85c2e6 588         return userService.deleteUser(username);
f98825 589     }
dfb889 590
892570 591     /**
JM 592      * Retrieve the user object for the specified username.
593      * 
594      * @see IUserService.getUserModel(String)
595      * @param username
596      * @return a user object or null
597      */
f98825 598     public UserModel getUserModel(String username) {
85c2e6 599         UserModel user = userService.getUserModel(username);
dfb889 600         return user;
f98825 601     }
8a2e9c 602
892570 603     /**
JM 604      * Returns the list of all users who are allowed to bypass the access
605      * restriction placed on the specified repository.
606      * 
607      * @see IUserService.getUsernamesForRepositoryRole(String)
608      * @param repository
609      * @return list of all usernames that can bypass the access restriction
610      */
f98825 611     public List<String> getRepositoryUsers(RepositoryModel repository) {
892570 612         return userService.getUsernamesForRepositoryRole(repository.name);
f98825 613     }
8a2e9c 614
892570 615     /**
JM 616      * Sets the list of all uses who are allowed to bypass the access
617      * restriction placed on the specified repository.
618      * 
619      * @see IUserService.setUsernamesForRepositoryRole(String, List<String>)
620      * @param repository
621      * @param usernames
622      * @return true if successful
623      */
f98825 624     public boolean setRepositoryUsers(RepositoryModel repository, List<String> repositoryUsers) {
892570 625         return userService.setUsernamesForRepositoryRole(repository.name, repositoryUsers);
dfb889 626     }
JM 627
892570 628     /**
JM 629      * Adds/updates a complete user object keyed by username. This method allows
630      * for renaming a user.
631      * 
632      * @see IUserService.updateUserModel(String, UserModel)
633      * @param username
634      * @param user
635      * @param isCreate
636      * @throws GitBlitException
637      */
638     public void updateUserModel(String username, UserModel user, boolean isCreate)
2a7306 639             throws GitBlitException {
16038c 640         if (!username.equalsIgnoreCase(user.username)) {
JM 641             if (userService.getUserModel(user.username) != null) {
d03aff 642                 throw new GitBlitException(MessageFormat.format(
JM 643                         "Failed to rename ''{0}'' because ''{1}'' already exists.", username,
644                         user.username));
16038c 645             }
JM 646         }
85c2e6 647         if (!userService.updateUserModel(username, user)) {
dfb889 648             throw new GitBlitException(isCreate ? "Failed to add user!" : "Failed to update user!");
JM 649         }
fe24a0 650     }
JM 651
652     /**
653      * Returns the list of available teams that a user or repository may be
654      * assigned to.
655      * 
656      * @return the list of teams
657      */
658     public List<String> getAllTeamnames() {
659         List<String> teams = new ArrayList<String>(userService.getAllTeamNames());
abeaaf 660         return teams;
JM 661     }
e36d4d 662
abeaaf 663     /**
JM 664      * Returns the list of available teams that a user or repository may be
665      * assigned to.
666      * 
667      * @return the list of teams
668      */
669     public List<TeamModel> getAllTeams() {
670         List<TeamModel> teams = userService.getAllTeams();
fe24a0 671         return teams;
JM 672     }
673
674     /**
675      * Returns the TeamModel object for the specified name.
676      * 
677      * @param teamname
678      * @return a TeamModel object or null
679      */
680     public TeamModel getTeamModel(String teamname) {
681         return userService.getTeamModel(teamname);
682     }
683
684     /**
685      * Returns the list of all teams who are allowed to bypass the access
686      * restriction placed on the specified repository.
687      * 
688      * @see IUserService.getTeamnamesForRepositoryRole(String)
689      * @param repository
690      * @return list of all teamnames that can bypass the access restriction
691      */
692     public List<String> getRepositoryTeams(RepositoryModel repository) {
693         return userService.getTeamnamesForRepositoryRole(repository.name);
694     }
695
696     /**
697      * Sets the list of all uses who are allowed to bypass the access
698      * restriction placed on the specified repository.
699      * 
700      * @see IUserService.setTeamnamesForRepositoryRole(String, List<String>)
701      * @param repository
702      * @param teamnames
703      * @return true if successful
704      */
705     public boolean setRepositoryTeams(RepositoryModel repository, List<String> repositoryTeams) {
706         return userService.setTeamnamesForRepositoryRole(repository.name, repositoryTeams);
707     }
fa54be 708
fe24a0 709     /**
JM 710      * Updates the TeamModel object for the specified name.
711      * 
712      * @param teamname
713      * @param team
714      * @param isCreate
715      */
fa54be 716     public void updateTeamModel(String teamname, TeamModel team, boolean isCreate)
JM 717             throws GitBlitException {
fe24a0 718         if (!teamname.equalsIgnoreCase(team.name)) {
JM 719             if (userService.getTeamModel(team.name) != null) {
720                 throw new GitBlitException(MessageFormat.format(
721                         "Failed to rename ''{0}'' because ''{1}'' already exists.", teamname,
722                         team.name));
723             }
724         }
725         if (!userService.updateTeamModel(teamname, team)) {
726             throw new GitBlitException(isCreate ? "Failed to add team!" : "Failed to update team!");
727         }
728     }
fa54be 729
fe24a0 730     /**
JM 731      * Delete the team object with the specified teamname
732      * 
733      * @see IUserService.deleteTeam(String)
734      * @param teamname
735      * @return true if successful
736      */
737     public boolean deleteTeam(String teamname) {
738         return userService.deleteTeam(teamname);
dfb889 739     }
fee060 740     
JM 741     /**
742      * Adds the repository to the list of cached repositories if Gitblit is
743      * configured to cache the repository list.
744      * 
745      * @param name
746      */
cdf77b 747     private void addToCachedRepositoryList(String name, RepositoryModel model) {
fee060 748         if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
cdf77b 749             repositoryListCache.put(name, model);
fee060 750         }
cdf77b 751     }
JM 752     
753     /**
754      * Removes the repository from the list of cached repositories.
755      * 
756      * @param name
757      */
758     private void removeFromCachedRepositoryList(String name) {
759         if (StringUtils.isEmpty(name)) {
760             return;
761         }
762         repositoryListCache.remove(name);
fee060 763     }
dfb889 764
892570 765     /**
cdf77b 766      * Clears all the cached metadata for the specified repository.
4d44cf 767      * 
JM 768      * @param repositoryName
769      */
cdf77b 770     private void clearRepositoryMetadataCache(String repositoryName) {
4d44cf 771         repositorySizeCache.remove(repositoryName);
JM 772         repositoryMetricsCache.remove(repositoryName);
fee060 773     }
JM 774     
775     /**
776      * Resets the repository list cache.
777      * 
778      */
779     public void resetRepositoryListCache() {
780         logger.info("Repository cache manually reset");
781         repositoryListCache.clear();
782     }
783     
784     /**
785      * Calculate the checksum of settings that affect the repository list cache.
786      * @return a checksum
787      */
788     private String getRepositoryListSettingsChecksum() {
789         StringBuilder ns = new StringBuilder();
790         ns.append(settings.getString(Keys.git.cacheRepositoryList, "")).append('\n');
791         ns.append(settings.getString(Keys.git.onlyAccessBareRepositories, "")).append('\n');
792         ns.append(settings.getString(Keys.git.searchRepositoriesSubfolders, "")).append('\n');
793         ns.append(settings.getString(Keys.git.searchRecursionDepth, "")).append('\n');
794         ns.append(settings.getString(Keys.git.searchExclusions, "")).append('\n');
795         String checksum = StringUtils.getSHA1(ns.toString());
796         return checksum;
797     }
798     
799     /**
800      * Compare the last repository list setting checksum to the current checksum.
801      * If different then clear the cache so that it may be rebuilt.
802      * 
803      * @return true if the cached repository list is valid since the last check
804      */
805     private boolean isValidRepositoryList() {
806         String newChecksum = getRepositoryListSettingsChecksum();
807         boolean valid = newChecksum.equals(repositoryListSettingsChecksum.get());
808         repositoryListSettingsChecksum.set(newChecksum);
809         if (!valid && settings.getBoolean(Keys.git.cacheRepositoryList,  true)) {
810             logger.info("Repository list settings have changed. Clearing repository list cache.");
811             repositoryListCache.clear();
812         }
813         return valid;
4d44cf 814     }
JM 815
816     /**
892570 817      * Returns the list of all repositories available to Gitblit. This method
JM 818      * does not consider user access permissions.
819      * 
820      * @return list of all repositories
821      */
166e6a 822     public List<String> getRepositoryList() {
fee060 823         if (repositoryListCache.size() == 0 || !isValidRepositoryList()) {
JM 824             // we are not caching OR we have not yet cached OR the cached list is invalid
825             long startTime = System.currentTimeMillis();
826             List<String> repositories = JGitUtils.getRepositoryList(repositoriesFolder, 
827                     settings.getBoolean(Keys.git.onlyAccessBareRepositories, false),
828                     settings.getBoolean(Keys.git.searchRepositoriesSubfolders, true),
829                     settings.getInteger(Keys.git.searchRecursionDepth, -1),
830                     settings.getStrings(Keys.git.searchExclusions));
831
832             if (!settings.getBoolean(Keys.git.cacheRepositoryList,  true)) {
833                 // we are not caching
834                 StringUtils.sortRepositorynames(repositories);
835                 return repositories;
836             } else {
837                 // we are caching this list
838                 String msg = "{0} repositories identified in {1} msecs";
839
840                 // optionally (re)calculate repository sizes
841                 if (getBoolean(Keys.web.showRepositorySizes, true)) {
842                     msg = "{0} repositories identified with calculated folder sizes in {1} msecs";
843                     for (String repository : repositories) {
844                         RepositoryModel model = getRepositoryModel(repository);
845                         if (!model.skipSizeCalculation) {
846                             calculateSize(model);
847                         }
848                     }
cdf77b 849                 } else {
JM 850                     // update cache
851                     for (String repository : repositories) {
852                         getRepositoryModel(repository);
853                     }
fee060 854                 }
JM 855                 
856                 long duration = System.currentTimeMillis() - startTime;
857                 logger.info(MessageFormat.format(msg, repositoryListCache.size(), duration));
858             }
859         }
860         
861         // return sorted copy of cached list
cdf77b 862         List<String> list = new ArrayList<String>(repositoryListCache.keySet());        
fee060 863         StringUtils.sortRepositorynames(list);
JM 864         return list;
166e6a 865     }
155bf7 866
892570 867     /**
JM 868      * Returns the JGit repository for the specified name.
869      * 
870      * @param repositoryName
871      * @return repository or null
872      */
166e6a 873     public Repository getRepository(String repositoryName) {
11924d 874         return getRepository(repositoryName, true);
JM 875     }
876
877     /**
878      * Returns the JGit repository for the specified name.
879      * 
880      * @param repositoryName
881      * @param logError
882      * @return repository or null
883      */
884     public Repository getRepository(String repositoryName, boolean logError) {
166e6a 885         Repository r = null;
JM 886         try {
887             r = repositoryResolver.open(null, repositoryName);
888         } catch (RepositoryNotFoundException e) {
889             r = null;
11924d 890             if (logError) {
JM 891                 logger.error("GitBlit.getRepository(String) failed to find "
892                         + new File(repositoriesFolder, repositoryName).getAbsolutePath());
893             }
892570 894         } catch (ServiceNotAuthorizedException e) {
JM 895             r = null;
11924d 896             if (logError) {
JM 897                 logger.error("GitBlit.getRepository(String) failed to find "
898                         + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
899             }
166e6a 900         } catch (ServiceNotEnabledException e) {
JM 901             r = null;
11924d 902             if (logError) {
JM 903                 logger.error("GitBlit.getRepository(String) failed to find "
904                         + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
905             }
5d9bd7 906         } catch (ServiceMayNotContinueException e) {
JM 907             r = null;
908             if (logError) {
909                 logger.error("GitBlit.getRepository(String) failed to find "
910                         + new File(repositoriesFolder, repositoryName).getAbsolutePath(), e);
911             }
166e6a 912         }
JM 913         return r;
914     }
dfb889 915
892570 916     /**
JM 917      * Returns the list of repository models that are accessible to the user.
918      * 
919      * @param user
920      * @return list of repository models accessible to user
921      */
511554 922     public List<RepositoryModel> getRepositoryModels(UserModel user) {
fee060 923         long methodStart = System.currentTimeMillis();
166e6a 924         List<String> list = getRepositoryList();
JM 925         List<RepositoryModel> repositories = new ArrayList<RepositoryModel>();
926         for (String repo : list) {
dfb889 927             RepositoryModel model = getRepositoryModel(user, repo);
JM 928             if (model != null) {
929                 repositories.add(model);
930             }
166e6a 931         }
3d293a 932         if (getBoolean(Keys.web.showRepositorySizes, true)) {
JM 933             int repoCount = 0;
934             long startTime = System.currentTimeMillis();
935             ByteFormat byteFormat = new ByteFormat();
936             for (RepositoryModel model : repositories) {
937                 if (!model.skipSizeCalculation) {
938                     repoCount++;
939                     model.size = byteFormat.format(calculateSize(model));
940                 }
941             }
942             long duration = System.currentTimeMillis() - startTime;
fee060 943             if (duration > 250) {
JM 944                 // only log calcualtion time if > 250 msecs
945                 logger.info(MessageFormat.format("{0} repository sizes calculated in {1} msecs",
3d293a 946                     repoCount, duration));
fee060 947             }
3d293a 948         }
fee060 949         long duration = System.currentTimeMillis() - methodStart;
JM 950         logger.info(MessageFormat.format("{0} repository models loaded for {1} in {2} msecs",
4bcaea 951                 repositories.size(), user == null ? "anonymous" : user.username, duration));
166e6a 952         return repositories;
JM 953     }
8a2e9c 954
892570 955     /**
JM 956      * Returns a repository model if the repository exists and the user may
957      * access the repository.
958      * 
959      * @param user
960      * @param repositoryName
961      * @return repository model or null
962      */
511554 963     public RepositoryModel getRepositoryModel(UserModel user, String repositoryName) {
dfb889 964         RepositoryModel model = getRepositoryModel(repositoryName);
85c2e6 965         if (model == null) {
JM 966             return null;
967         }
dfb889 968         if (model.accessRestriction.atLeast(AccessRestrictionType.VIEW)) {
efe8ec 969             if (user != null && user.canAccessRepository(model)) {
dfb889 970                 return model;
JM 971             }
972             return null;
973         } else {
974             return model;
975         }
976     }
977
892570 978     /**
JM 979      * Returns the repository model for the specified repository. This method
980      * does not consider user access permissions.
981      * 
982      * @param repositoryName
983      * @return repository model or null
984      */
166e6a 985     public RepositoryModel getRepositoryModel(String repositoryName) {
cdf77b 986         if (!repositoryListCache.containsKey(repositoryName)) {
JM 987             RepositoryModel model = loadRepositoryModel(repositoryName);
988             if (model == null) {
989                 return null;
990             }
991             addToCachedRepositoryList(repositoryName, model);            
992             return model;
993         }
994         
995         // cached model
996         RepositoryModel model = repositoryListCache.get(repositoryName);
997         
998         // check for updates
999         Repository r = getRepository(repositoryName);
1000         if (r == null) {
1001             // repository is missing
1002             removeFromCachedRepositoryList(repositoryName);
1003             logger.error(MessageFormat.format("Repository \"{0}\" is missing! Removing from cache.", repositoryName));
1004             return null;
1005         }
1006         
1007         FileBasedConfig config = (FileBasedConfig) getRepositoryConfig(r);
1008         if (config.isOutdated()) {
1009             // reload model
1010             logger.info(MessageFormat.format("Config for \"{0}\" has changed. Reloading model and updating cache.", repositoryName));
1011             model = loadRepositoryModel(repositoryName);
1012             removeFromCachedRepositoryList(repositoryName);
1013             addToCachedRepositoryList(repositoryName, model);
1014         } else {
1015             // update a few repository parameters 
1016             if (!model.hasCommits) {
1017                 // update hasCommits, assume a repository only gains commits :)
1018                 model.hasCommits = JGitUtils.hasCommits(r);
1019             }
1020
1021             model.lastChange = JGitUtils.getLastChange(r);
1022         }
1023         r.close();
1024         
1025         // return a copy of the cached model
1026         return DeepCopier.copy(model);
13a3f5 1027     }
JM 1028     
1029     
1030     /**
1031      * Returns the map of project config.  This map is cached and reloaded if
1032      * the underlying projects.conf file changes.
1033      * 
1034      * @return project config map
1035      */
1036     private Map<String, ProjectModel> getProjectConfigs() {
1037         if (projectConfigs.isOutdated()) {
1038             
1039             try {
1040                 projectConfigs.load();
1041             } catch (Exception e) {
1042             }
1043
1044             // project configs
1045             String rootName = GitBlit.getString(Keys.web.repositoryRootGroupName, "main");
1046             ProjectModel rootProject = new ProjectModel(rootName, true);
1047
1048             Map<String, ProjectModel> configs = new HashMap<String, ProjectModel>();
1049             // cache the root project under its alias and an empty path
1050             configs.put("", rootProject);
1051             configs.put(rootProject.name.toLowerCase(), rootProject);
1052
1053             for (String name : projectConfigs.getSubsections("project")) {
1054                 ProjectModel project;
1055                 if (name.equalsIgnoreCase(rootName)) {
1056                     project = rootProject;
1057                 } else {
1058                     project = new ProjectModel(name);
1059                 }
1060                 project.title = projectConfigs.getString("project", name, "title");
1061                 project.description = projectConfigs.getString("project", name, "description");
1062                 // TODO add more interesting metadata
1063                 // project manager?
1064                 // commit message regex?
1065                 // RW+
1066                 // RW
1067                 // R
1068                 configs.put(name.toLowerCase(), project);                
1069             }
1070             projectCache.clear();
1071             projectCache.putAll(configs);
1072         }
1073         return projectCache;
1074     }
1075     
1076     /**
1077      * Returns a list of project models for the user.
1078      * 
1079      * @param user
1080      * @return list of projects that are accessible to the user
1081      */
1082     public List<ProjectModel> getProjectModels(UserModel user) {
1083         Map<String, ProjectModel> configs = getProjectConfigs();
1084
1085         // per-user project lists, this accounts for security and visibility
1086         Map<String, ProjectModel> map = new TreeMap<String, ProjectModel>();
1087         // root project
1088         map.put("", configs.get(""));
1089         
1090         for (RepositoryModel model : getRepositoryModels(user)) {
1091             String rootPath = StringUtils.getRootPath(model.name).toLowerCase();            
1092             if (!map.containsKey(rootPath)) {
1093                 ProjectModel project;
1094                 if (configs.containsKey(rootPath)) {
1095                     // clone the project model because it's repository list will
1096                     // be tailored for the requesting user
1097                     project = DeepCopier.copy(configs.get(rootPath));
1098                 } else {
1099                     project = new ProjectModel(rootPath);
1100                 }
1101                 map.put(rootPath, project);
1102             }
1103             map.get(rootPath).addRepository(model);
1104         }
1105         
1106         // sort projects, root project first
1107         List<ProjectModel> projects = new ArrayList<ProjectModel>(map.values());
1108         Collections.sort(projects);
1109         projects.remove(map.get(""));
1110         projects.add(0, map.get(""));
1111         return projects;
1112     }
1113     
1114     /**
1115      * Returns the project model for the specified user.
1116      * 
1117      * @param name
1118      * @param user
1119      * @return a project model, or null if it does not exist
1120      */
1121     public ProjectModel getProjectModel(String name, UserModel user) {
1122         for (ProjectModel project : getProjectModels(user)) {
1123             if (project.name.equalsIgnoreCase(name)) {
1124                 return project;
1125             }
1126         }
1127         return null;
1128     }
1129     
1130     /**
1131      * Returns a project model for the Gitblit/system user.
1132      * 
1133      * @param name a project name
1134      * @return a project model or null if the project does not exist
1135      */
1136     public ProjectModel getProjectModel(String name) {
1137         Map<String, ProjectModel> configs = getProjectConfigs();
1138         ProjectModel project = configs.get(name.toLowerCase());
1139         if (project == null) {
1140             return null;
1141         }
1142         // clone the object
1143         project = DeepCopier.copy(project);
1144         String folder = name.toLowerCase() + "/";
1145         for (String repository : getRepositoryList()) {
1146             if (repository.toLowerCase().startsWith(folder)) {
1147                 project.addRepository(repository);
1148             }
1149         }
1150         return project;
cdf77b 1151     }
JM 1152     
1153     /**
1154      * Workaround JGit.  I need to access the raw config object directly in order
1155      * to see if the config is dirty so that I can reload a repository model.
1156      * If I use the stock JGit method to get the config it already reloads the
1157      * config.  If the config changes are made within Gitblit this is fine as
1158      * the returned config will still be flagged as dirty.  BUT... if the config
1159      * is manipulated outside Gitblit then it fails to recognize this as dirty.
1160      *  
1161      * @param r
1162      * @return a config
1163      */
1164     private StoredConfig getRepositoryConfig(Repository r) {
1165         try {
1166             Field f = r.getClass().getDeclaredField("repoConfig");
1167             f.setAccessible(true);
1168             StoredConfig config = (StoredConfig) f.get(r);
1169             return config;
1170         } catch (Exception e) {
1171             logger.error("Failed to retrieve \"repoConfig\" via reflection", e);
1172         }
1173         return r.getConfig();
1174     }
1175     
1176     /**
1177      * Create a repository model from the configuration and repository data.
1178      * 
1179      * @param repositoryName
1180      * @return a repositoryModel or null if the repository does not exist
1181      */
1182     private RepositoryModel loadRepositoryModel(String repositoryName) {
166e6a 1183         Repository r = getRepository(repositoryName);
1f9dae 1184         if (r == null) {
JM 1185             return null;
1186         }
166e6a 1187         RepositoryModel model = new RepositoryModel();
JM 1188         model.name = repositoryName;
bc9d4a 1189         model.hasCommits = JGitUtils.hasCommits(r);
4fea45 1190         model.lastChange = JGitUtils.getLastChange(r);
b74031 1191         model.isBare = r.isBare();
fee060 1192         
JM 1193         StoredConfig config = r.getConfig();
166e6a 1194         if (config != null) {
00afd7 1195             model.description = getConfig(config, "description", "");
JM 1196             model.owner = getConfig(config, "owner", "");
1197             model.useTickets = getConfig(config, "useTickets", false);
1198             model.useDocs = getConfig(config, "useDocs", false);
2a7306 1199             model.accessRestriction = AccessRestrictionType.fromName(getConfig(config,
94dcbd 1200                     "accessRestriction", settings.getString(Keys.git.defaultAccessRestriction, null)));
6adf56 1201             model.authorizationControl = AuthorizationControl.fromName(getConfig(config,
JM 1202                     "authorizationControl", settings.getString(Keys.git.defaultAuthorizationControl, null)));
00afd7 1203             model.showRemoteBranches = getConfig(config, "showRemoteBranches", false);
JM 1204             model.isFrozen = getConfig(config, "isFrozen", false);
a1ea87 1205             model.showReadme = getConfig(config, "showReadme", false);
3d293a 1206             model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
fe3262 1207             model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
831469 1208             model.federationStrategy = FederationStrategy.fromName(getConfig(config,
JM 1209                     "federationStrategy", null));
8f73a7 1210             model.federationSets = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 1211                     Constants.CONFIG_GITBLIT, null, "federationSets")));
831469 1212             model.isFederated = getConfig(config, "isFederated", false);
JM 1213             model.origin = config.getString("remote", "origin", "url");
fa54be 1214             model.preReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 1215                     Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
fa54be 1216             model.postReceiveScripts = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 1217                     Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
eb96ea 1218             model.mailingLists = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 1219                     Constants.CONFIG_GITBLIT, null, "mailingList")));
40ca5c 1220             model.indexedBranches = new ArrayList<String>(Arrays.asList(config.getStringList(
380afa 1221                     Constants.CONFIG_GITBLIT, null, "indexBranch")));
4a5a55 1222             
JC 1223             // Custom defined properties
7c1cdc 1224             model.customFields = new LinkedHashMap<String, String>();
380afa 1225             for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
JM 1226                 model.customFields.put(aProperty, config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
4a5a55 1227             }
166e6a 1228         }
90b8d7 1229         model.HEAD = JGitUtils.getHEADRef(r);
JM 1230         model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
166e6a 1231         r.close();
JM 1232         return model;
00afd7 1233     }
eb870f 1234     
JM 1235     /**
1236      * Determines if this server has the requested repository.
1237      * 
1238      * @param name
1239      * @return true if the repository exists
1240      */
1241     public boolean hasRepository(String repositoryName) {
cdf77b 1242         if (settings.getBoolean(Keys.git.cacheRepositoryList, true)) {
JM 1243             // if we are caching use the cache to determine availability
1244             // otherwise we end up adding a phantom repository to the cache
1245             return repositoryListCache.containsKey(repositoryName);
1246         }        
eb870f 1247         Repository r = getRepository(repositoryName, false);
JM 1248         if (r == null) {
1249             return false;
1250         }
1251         r.close();
1252         return true;
1253     }
8a2e9c 1254
892570 1255     /**
4d44cf 1256      * Returns the size in bytes of the repository. Gitblit caches the
JM 1257      * repository sizes to reduce the performance penalty of recursive
1258      * calculation. The cache is updated if the repository has been changed
1259      * since the last calculation.
5c2841 1260      * 
JM 1261      * @param model
1262      * @return size in bytes
1263      */
1264     public long calculateSize(RepositoryModel model) {
4d44cf 1265         if (repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
JM 1266             return repositorySizeCache.getObject(model.name);
1267         }
5c2841 1268         File gitDir = FileKey.resolve(new File(repositoriesFolder, model.name), FS.DETECTED);
4d44cf 1269         long size = com.gitblit.utils.FileUtils.folderSize(gitDir);
JM 1270         repositorySizeCache.updateObject(model.name, model.lastChange, size);
1271         return size;
5c2841 1272     }
JM 1273
1274     /**
dd6f08 1275      * Ensure that a cached repository is completely closed and its resources
JM 1276      * are properly released.
1277      * 
1278      * @param repositoryName
1279      */
1280     private void closeRepository(String repositoryName) {
1281         Repository repository = getRepository(repositoryName);
1282         // assume 2 uses in case reflection fails
1283         int uses = 2;
1284         try {
1285             // The FileResolver caches repositories which is very useful
1286             // for performance until you want to delete a repository.
1287             // I have to use reflection to call close() the correct
1288             // number of times to ensure that the object and ref databases
1289             // are properly closed before I can delete the repository from
1290             // the filesystem.
1291             Field useCnt = Repository.class.getDeclaredField("useCnt");
1292             useCnt.setAccessible(true);
1293             uses = ((AtomicInteger) useCnt.get(repository)).get();
1294         } catch (Exception e) {
1295             logger.warn(MessageFormat
1296                     .format("Failed to reflectively determine use count for repository {0}",
1297                             repositoryName), e);
1298         }
1299         if (uses > 0) {
1300             logger.info(MessageFormat
1301                     .format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases",
1302                             repositoryName, uses, uses));
1303             for (int i = 0; i < uses; i++) {
1304                 repository.close();
1305             }
1306         }
e6637c 1307         
JM 1308         // close any open index writer/searcher in the Lucene executor
1309         luceneExecutor.close(repositoryName);
dd6f08 1310     }
JM 1311
1312     /**
4d44cf 1313      * Returns the metrics for the default branch of the specified repository.
JM 1314      * This method builds a metrics cache. The cache is updated if the
1315      * repository is updated. A new copy of the metrics list is returned on each
1316      * call so that modifications to the list are non-destructive.
1317      * 
1318      * @param model
1319      * @param repository
1320      * @return a new array list of metrics
1321      */
1322     public List<Metric> getRepositoryDefaultMetrics(RepositoryModel model, Repository repository) {
1323         if (repositoryMetricsCache.hasCurrent(model.name, model.lastChange)) {
1324             return new ArrayList<Metric>(repositoryMetricsCache.getObject(model.name));
1325         }
40538c 1326         List<Metric> metrics = MetricUtils.getDateMetrics(repository, null, true, null, getTimezone());
4d44cf 1327         repositoryMetricsCache.updateObject(model.name, model.lastChange, metrics);
JM 1328         return new ArrayList<Metric>(metrics);
1329     }
1330
1331     /**
1332      * Returns the gitblit string value for the specified key. If key is not
892570 1333      * set, returns defaultValue.
JM 1334      * 
1335      * @param config
1336      * @param field
1337      * @param defaultValue
1338      * @return field value or defaultValue
1339      */
00afd7 1340     private String getConfig(StoredConfig config, String field, String defaultValue) {
380afa 1341         String value = config.getString(Constants.CONFIG_GITBLIT, null, field);
00afd7 1342         if (StringUtils.isEmpty(value)) {
JM 1343             return defaultValue;
1344         }
1345         return value;
1346     }
8a2e9c 1347
892570 1348     /**
380afa 1349      * Returns the gitblit boolean value for the specified key. If key is not
892570 1350      * set, returns defaultValue.
JM 1351      * 
1352      * @param config
1353      * @param field
1354      * @param defaultValue
1355      * @return field value or defaultValue
1356      */
00afd7 1357     private boolean getConfig(StoredConfig config, String field, boolean defaultValue) {
380afa 1358         return config.getBoolean(Constants.CONFIG_GITBLIT, field, defaultValue);
166e6a 1359     }
JM 1360
892570 1361     /**
JM 1362      * Creates/updates the repository model keyed by reopsitoryName. Saves all
1363      * repository settings in .git/config. This method allows for renaming
1364      * repositories and will update user access permissions accordingly.
1365      * 
1366      * All repositories created by this method are bare and automatically have
1367      * .git appended to their names, which is the standard convention for bare
1368      * repositories.
1369      * 
1370      * @param repositoryName
1371      * @param repository
1372      * @param isCreate
1373      * @throws GitBlitException
1374      */
1375     public void updateRepositoryModel(String repositoryName, RepositoryModel repository,
2a7306 1376             boolean isCreate) throws GitBlitException {
f5d0ad 1377         Repository r = null;
JM 1378         if (isCreate) {
a3bde6 1379             // ensure created repository name ends with .git
168566 1380             if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
a3bde6 1381                 repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
JM 1382             }
166e6a 1383             if (new File(repositoriesFolder, repository.name).exists()) {
2a7306 1384                 throw new GitBlitException(MessageFormat.format(
JM 1385                         "Can not create repository ''{0}'' because it already exists.",
1386                         repository.name));
166e6a 1387             }
dfb889 1388             // create repository
f5d0ad 1389             logger.info("create repository " + repository.name);
168566 1390             r = JGitUtils.createRepository(repositoriesFolder, repository.name);
f5d0ad 1391         } else {
8a2e9c 1392             // rename repository
JM 1393             if (!repositoryName.equalsIgnoreCase(repository.name)) {
16038c 1394                 if (!repository.name.toLowerCase().endsWith(
JM 1395                         org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
1396                     repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
1397                 }
1398                 if (new File(repositoriesFolder, repository.name).exists()) {
d03aff 1399                     throw new GitBlitException(MessageFormat.format(
JM 1400                             "Failed to rename ''{0}'' because ''{1}'' already exists.",
1401                             repositoryName, repository.name));
16038c 1402                 }
dd6f08 1403                 closeRepository(repositoryName);
8a2e9c 1404                 File folder = new File(repositoriesFolder, repositoryName);
JM 1405                 File destFolder = new File(repositoriesFolder, repository.name);
1406                 if (destFolder.exists()) {
2a7306 1407                     throw new GitBlitException(
JM 1408                             MessageFormat
1409                                     .format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.",
1410                                             repositoryName, repository.name));
8a2e9c 1411                 }
c1a4cc 1412                 File parentFile = destFolder.getParentFile();
JM 1413                 if (!parentFile.exists() && !parentFile.mkdirs()) {
1414                     throw new GitBlitException(MessageFormat.format(
1415                             "Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
1416                 }
8a2e9c 1417                 if (!folder.renameTo(destFolder)) {
2a7306 1418                     throw new GitBlitException(MessageFormat.format(
JM 1419                             "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName,
1420                             repository.name));
8a2e9c 1421                 }
JM 1422                 // rename the roles
85c2e6 1423                 if (!userService.renameRepositoryRole(repositoryName, repository.name)) {
2a7306 1424                     throw new GitBlitException(MessageFormat.format(
JM 1425                             "Failed to rename repository permissions ''{0}'' to ''{1}''.",
1426                             repositoryName, repository.name));
8a2e9c 1427                 }
4d44cf 1428
JM 1429                 // clear the cache
cdf77b 1430                 clearRepositoryMetadataCache(repositoryName);
8a2e9c 1431             }
JM 1432
f5d0ad 1433             // load repository
JM 1434             logger.info("edit repository " + repository.name);
1435             try {
1436                 r = repositoryResolver.open(null, repository.name);
1437             } catch (RepositoryNotFoundException e) {
1438                 logger.error("Repository not found", e);
892570 1439             } catch (ServiceNotAuthorizedException e) {
JM 1440                 logger.error("Service not authorized", e);
f5d0ad 1441             } catch (ServiceNotEnabledException e) {
JM 1442                 logger.error("Service not enabled", e);
5d9bd7 1443             } catch (ServiceMayNotContinueException e) {
JM 1444                 logger.error("Service may not continue", e);
f5d0ad 1445             }
f97bf0 1446         }
JM 1447
f5d0ad 1448         // update settings
2a7306 1449         if (r != null) {
831469 1450             updateConfiguration(r, repository);
2cdb73 1451             // only update symbolic head if it changes
90b8d7 1452             String currentRef = JGitUtils.getHEADRef(r);
JM 1453             if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
d394d9 1454                 logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", 
90b8d7 1455                         repository.name, currentRef, repository.HEAD));
JM 1456                 if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
1457                     // clear the cache
cdf77b 1458                     clearRepositoryMetadataCache(repository.name);
90b8d7 1459                 }
912938 1460             }
d394d9 1461
JM 1462             // close the repository object
2a7306 1463             r.close();
831469 1464         }
cdf77b 1465         
JM 1466         // update repository cache
1467         removeFromCachedRepositoryList(repositoryName);
1468         // model will actually be replaced on next load because config is stale
1469         addToCachedRepositoryList(repository.name, repository);
831469 1470     }
fee060 1471     
831469 1472     /**
JM 1473      * Updates the Gitblit configuration for the specified repository.
1474      * 
1475      * @param r
1476      *            the Git repository
1477      * @param repository
1478      *            the Gitblit repository model
1479      */
1480     public void updateConfiguration(Repository r, RepositoryModel repository) {
fee060 1481         StoredConfig config = r.getConfig();
380afa 1482         config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description);
JM 1483         config.setString(Constants.CONFIG_GITBLIT, null, "owner", repository.owner);
1484         config.setBoolean(Constants.CONFIG_GITBLIT, null, "useTickets", repository.useTickets);
1485         config.setBoolean(Constants.CONFIG_GITBLIT, null, "useDocs", repository.useDocs);
1486         config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name());
6adf56 1487         config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl", repository.authorizationControl.name());
380afa 1488         config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches);
JM 1489         config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen);
1490         config.setBoolean(Constants.CONFIG_GITBLIT, null, "showReadme", repository.showReadme);
1491         config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation);
1492         config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics);
1493         config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy",
831469 1494                 repository.federationStrategy.name());
380afa 1495         config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated);
a21fc5 1496
5efafa 1497         updateList(config, "federationSets", repository.federationSets);
JM 1498         updateList(config, "preReceiveScript", repository.preReceiveScripts);
1499         updateList(config, "postReceiveScript", repository.postReceiveScripts);
1500         updateList(config, "mailingList", repository.mailingLists);
1501         updateList(config, "indexBranch", repository.indexedBranches);
4a5a55 1502         
JC 1503         // User Defined Properties
380afa 1504         if (repository.customFields != null) {
JM 1505             if (repository.customFields.size() == 0) {
1506                 // clear section
1507                 config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS);
1508             } else {
1509                 for (Entry<String, String> property : repository.customFields.entrySet()) {
1510                     // set field
1511                     String key = property.getKey();
1512                     String value = property.getValue();
1513                     config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value);
1514                 }
1515             }
4a5a55 1516         }
a21fc5 1517
831469 1518         try {
JM 1519             config.save();
1520         } catch (IOException e) {
1521             logger.error("Failed to save repository config!", e);
f97bf0 1522         }
f5d0ad 1523     }
5efafa 1524     
JM 1525     private void updateList(StoredConfig config, String field, List<String> list) {
1526         // a null list is skipped, not cleared
1527         // this is for RPC administration where an older manager might be used
1528         if (list == null) {
1529             return;
1530         }
1531         if (ArrayUtils.isEmpty(list)) {
380afa 1532             config.unset(Constants.CONFIG_GITBLIT, null, field);
5efafa 1533         } else {
380afa 1534             config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
5efafa 1535         }
JM 1536     }
f5d0ad 1537
892570 1538     /**
JM 1539      * Deletes the repository from the file system and removes the repository
1540      * permission from all repository users.
1541      * 
1542      * @param model
1543      * @return true if successful
1544      */
8a2e9c 1545     public boolean deleteRepositoryModel(RepositoryModel model) {
JM 1546         return deleteRepository(model.name);
1547     }
1548
892570 1549     /**
JM 1550      * Deletes the repository from the file system and removes the repository
1551      * permission from all repository users.
1552      * 
1553      * @param repositoryName
1554      * @return true if successful
1555      */
8a2e9c 1556     public boolean deleteRepository(String repositoryName) {
JM 1557         try {
dd6f08 1558             closeRepository(repositoryName);
fee060 1559             // clear the repository cache
cdf77b 1560             clearRepositoryMetadataCache(repositoryName);
JM 1561             removeFromCachedRepositoryList(repositoryName);
fee060 1562
8a2e9c 1563             File folder = new File(repositoriesFolder, repositoryName);
JM 1564             if (folder.exists() && folder.isDirectory()) {
892570 1565                 FileUtils.delete(folder, FileUtils.RECURSIVE | FileUtils.RETRY);
85c2e6 1566                 if (userService.deleteRepositoryRole(repositoryName)) {
cdf77b 1567                     logger.info(MessageFormat.format("Repository \"{0}\" deleted", repositoryName));
8a2e9c 1568                     return true;
JM 1569                 }
1570             }
1571         } catch (Throwable t) {
1572             logger.error(MessageFormat.format("Failed to delete repository {0}", repositoryName), t);
1573         }
1574         return false;
1575     }
1576
892570 1577     /**
JM 1578      * Returns an html version of the commit message with any global or
1579      * repository-specific regular expression substitution applied.
1580      * 
1581      * @param repositoryName
1582      * @param text
1583      * @return html version of the commit message
1584      */
8c9a20 1585     public String processCommitMessage(String repositoryName, String text) {
JM 1586         String html = StringUtils.breakLinesForHtml(text);
1587         Map<String, String> map = new HashMap<String, String>();
1588         // global regex keys
892570 1589         if (settings.getBoolean(Keys.regex.global, false)) {
JM 1590             for (String key : settings.getAllKeys(Keys.regex.global)) {
8c9a20 1591                 if (!key.equals(Keys.regex.global)) {
JM 1592                     String subKey = key.substring(key.lastIndexOf('.') + 1);
892570 1593                     map.put(subKey, settings.getString(key, ""));
8c9a20 1594                 }
JM 1595             }
1596         }
1597
1598         // repository-specific regex keys
892570 1599         List<String> keys = settings.getAllKeys(Keys.regex._ROOT + "."
8c9a20 1600                 + repositoryName.toLowerCase());
JM 1601         for (String key : keys) {
1602             String subKey = key.substring(key.lastIndexOf('.') + 1);
892570 1603             map.put(subKey, settings.getString(key, ""));
8c9a20 1604         }
JM 1605
1606         for (Entry<String, String> entry : map.entrySet()) {
1607             String definition = entry.getValue().trim();
1608             String[] chunks = definition.split("!!!");
1609             if (chunks.length == 2) {
1610                 html = html.replaceAll(chunks[0], chunks[1]);
1611             } else {
1612                 logger.warn(entry.getKey()
1613                         + " improperly formatted.  Use !!! to separate match from replacement: "
1614                         + definition);
1615             }
1616         }
1617         return html;
1618     }
1619
892570 1620     /**
831469 1621      * Returns Gitblit's scheduled executor service for scheduling tasks.
JM 1622      * 
1623      * @return scheduledExecutor
1624      */
1625     public ScheduledExecutorService executor() {
1626         return scheduledExecutor;
1627     }
1628
1629     public static boolean canFederate() {
2c32fd 1630         String passphrase = getString(Keys.federation.passphrase, "");
JM 1631         return !StringUtils.isEmpty(passphrase);
831469 1632     }
JM 1633
1634     /**
1635      * Configures this Gitblit instance to pull any registered federated gitblit
1636      * instances.
1637      */
1638     private void configureFederation() {
2c32fd 1639         boolean validPassphrase = true;
JM 1640         String passphrase = settings.getString(Keys.federation.passphrase, "");
1641         if (StringUtils.isEmpty(passphrase)) {
1642             logger.warn("Federation passphrase is blank! This server can not be PULLED from.");
1643             validPassphrase = false;
831469 1644         }
2c32fd 1645         if (validPassphrase) {
8f73a7 1646             // standard tokens
831469 1647             for (FederationToken tokenType : FederationToken.values()) {
JM 1648                 logger.info(MessageFormat.format("Federation {0} token = {1}", tokenType.name(),
1649                         getFederationToken(tokenType)));
8f73a7 1650             }
JM 1651
1652             // federation set tokens
1653             for (String set : settings.getStrings(Keys.federation.sets)) {
1654                 logger.info(MessageFormat.format("Federation Set {0} token = {1}", set,
1655                         getFederationToken(set)));
831469 1656             }
JM 1657         }
1658
1659         // Schedule the federation executor
1660         List<FederationModel> registrations = getFederationRegistrations();
1661         if (registrations.size() > 0) {
f6740d 1662             FederationPullExecutor executor = new FederationPullExecutor(registrations, true);
JM 1663             scheduledExecutor.schedule(executor, 1, TimeUnit.MINUTES);
831469 1664         }
JM 1665     }
1666
1667     /**
1668      * Returns the list of federated gitblit instances that this instance will
1669      * try to pull.
1670      * 
1671      * @return list of registered gitblit instances
1672      */
1673     public List<FederationModel> getFederationRegistrations() {
1674         if (federationRegistrations.isEmpty()) {
f6740d 1675             federationRegistrations.addAll(FederationUtils.getFederationRegistrations(settings));
831469 1676         }
JM 1677         return federationRegistrations;
1678     }
1679
1680     /**
1681      * Retrieve the specified federation registration.
1682      * 
1683      * @param name
1684      *            the name of the registration
1685      * @return a federation registration
1686      */
1687     public FederationModel getFederationRegistration(String url, String name) {
1688         // check registrations
1689         for (FederationModel r : getFederationRegistrations()) {
1690             if (r.name.equals(name) && r.url.equals(url)) {
1691                 return r;
1692             }
1693         }
1694
1695         // check the results
1696         for (FederationModel r : getFederationResultRegistrations()) {
1697             if (r.name.equals(name) && r.url.equals(url)) {
1698                 return r;
1699             }
1700         }
1701         return null;
1702     }
1703
1704     /**
31abc2 1705      * Returns the list of federation sets.
JM 1706      * 
1707      * @return list of federation sets
1708      */
1709     public List<FederationSet> getFederationSets(String gitblitUrl) {
1710         List<FederationSet> list = new ArrayList<FederationSet>();
1711         // generate standard tokens
1712         for (FederationToken type : FederationToken.values()) {
1713             FederationSet fset = new FederationSet(type.toString(), type, getFederationToken(type));
1714             fset.repositories = getRepositories(gitblitUrl, fset.token);
1715             list.add(fset);
1716         }
1717         // generate tokens for federation sets
1718         for (String set : settings.getStrings(Keys.federation.sets)) {
1719             FederationSet fset = new FederationSet(set, FederationToken.REPOSITORIES,
1720                     getFederationToken(set));
1721             fset.repositories = getRepositories(gitblitUrl, fset.token);
1722             list.add(fset);
1723         }
1724         return list;
1725     }
1726
1727     /**
831469 1728      * Returns the list of possible federation tokens for this Gitblit instance.
JM 1729      * 
1730      * @return list of federation tokens
1731      */
1732     public List<String> getFederationTokens() {
1733         List<String> tokens = new ArrayList<String>();
8f73a7 1734         // generate standard tokens
831469 1735         for (FederationToken type : FederationToken.values()) {
JM 1736             tokens.add(getFederationToken(type));
8f73a7 1737         }
JM 1738         // generate tokens for federation sets
1739         for (String set : settings.getStrings(Keys.federation.sets)) {
1740             tokens.add(getFederationToken(set));
831469 1741         }
JM 1742         return tokens;
1743     }
1744
1745     /**
1746      * Returns the specified federation token for this Gitblit instance.
1747      * 
1748      * @param type
1749      * @return a federation token
1750      */
1751     public String getFederationToken(FederationToken type) {
8f73a7 1752         return getFederationToken(type.name());
JM 1753     }
1754
1755     /**
1756      * Returns the specified federation token for this Gitblit instance.
1757      * 
1758      * @param value
1759      * @return a federation token
1760      */
1761     public String getFederationToken(String value) {
2c32fd 1762         String passphrase = settings.getString(Keys.federation.passphrase, "");
8f73a7 1763         return StringUtils.getSHA1(passphrase + "-" + value);
831469 1764     }
JM 1765
1766     /**
1767      * Compares the provided token with this Gitblit instance's tokens and
1768      * determines if the requested permission may be granted to the token.
1769      * 
1770      * @param req
1771      * @param token
1772      * @return true if the request can be executed
1773      */
1774     public boolean validateFederationRequest(FederationRequest req, String token) {
1775         String all = getFederationToken(FederationToken.ALL);
1776         String unr = getFederationToken(FederationToken.USERS_AND_REPOSITORIES);
1777         String jur = getFederationToken(FederationToken.REPOSITORIES);
1778         switch (req) {
1779         case PULL_REPOSITORIES:
1780             return token.equals(all) || token.equals(unr) || token.equals(jur);
1781         case PULL_USERS:
fe24a0 1782         case PULL_TEAMS:
831469 1783             return token.equals(all) || token.equals(unr);
JM 1784         case PULL_SETTINGS:
df162c 1785         case PULL_SCRIPTS:
831469 1786             return token.equals(all);
JM 1787         }
1788         return false;
1789     }
1790
1791     /**
1792      * Acknowledge and cache the status of a remote Gitblit instance.
1793      * 
1794      * @param identification
1795      *            the identification of the pulling Gitblit instance
1796      * @param registration
1797      *            the registration from the pulling Gitblit instance
1798      * @return true if acknowledged
1799      */
1800     public boolean acknowledgeFederationStatus(String identification, FederationModel registration) {
1801         // reset the url to the identification of the pulling Gitblit instance
1802         registration.url = identification;
1803         String id = identification;
1804         if (!StringUtils.isEmpty(registration.folder)) {
1805             id += "-" + registration.folder;
1806         }
1807         federationPullResults.put(id, registration);
1808         return true;
1809     }
1810
1811     /**
1812      * Returns the list of registration results.
1813      * 
1814      * @return the list of registration results
1815      */
1816     public List<FederationModel> getFederationResultRegistrations() {
1817         return new ArrayList<FederationModel>(federationPullResults.values());
1818     }
1819
1820     /**
1821      * Submit a federation proposal. The proposal is cached locally and the
1822      * Gitblit administrator(s) are notified via email.
1823      * 
1824      * @param proposal
1825      *            the proposal
1826      * @param gitblitUrl
4aafd4 1827      *            the url of your gitblit instance to send an email to
JM 1828      *            administrators
831469 1829      * @return true if the proposal was submitted
JM 1830      */
1831     public boolean submitFederationProposal(FederationProposal proposal, String gitblitUrl) {
1832         // convert proposal to json
93f0b1 1833         String json = JsonUtils.toJsonString(proposal);
831469 1834
JM 1835         try {
1836             // make the proposals folder
b774de 1837             File proposalsFolder = getProposalsFolder();
831469 1838             proposalsFolder.mkdirs();
JM 1839
1840             // cache json to a file
1841             File file = new File(proposalsFolder, proposal.token + Constants.PROPOSAL_EXT);
1842             com.gitblit.utils.FileUtils.writeContent(file, json);
1843         } catch (Exception e) {
1844             logger.error(MessageFormat.format("Failed to cache proposal from {0}", proposal.url), e);
1845         }
1846
1847         // send an email, if possible
1848         try {
1849             Message message = mailExecutor.createMessageForAdministrators();
1850             if (message != null) {
1851                 message.setSubject("Federation proposal from " + proposal.url);
1852                 message.setText("Please review the proposal @ " + gitblitUrl + "/proposal/"
1853                         + proposal.token);
1854                 mailExecutor.queue(message);
1855             }
1856         } catch (Throwable t) {
1857             logger.error("Failed to notify administrators of proposal", t);
1858         }
1859         return true;
1860     }
1861
1862     /**
1863      * Returns the list of pending federation proposals
1864      * 
1865      * @return list of federation proposals
1866      */
1867     public List<FederationProposal> getPendingFederationProposals() {
1868         List<FederationProposal> list = new ArrayList<FederationProposal>();
b774de 1869         File folder = getProposalsFolder();
831469 1870         if (folder.exists()) {
JM 1871             File[] files = folder.listFiles(new FileFilter() {
1872                 @Override
1873                 public boolean accept(File file) {
1874                     return file.isFile()
1875                             && file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
1876                 }
1877             });
1878             for (File file : files) {
1879                 String json = com.gitblit.utils.FileUtils.readContent(file, null);
31abc2 1880                 FederationProposal proposal = JsonUtils.fromJsonString(json,
JM 1881                         FederationProposal.class);
831469 1882                 list.add(proposal);
JM 1883             }
1884         }
1885         return list;
1886     }
1887
1888     /**
dd9ae7 1889      * Get repositories for the specified token.
JM 1890      * 
1891      * @param gitblitUrl
1892      *            the base url of this gitblit instance
1893      * @param token
1894      *            the federation token
1895      * @return a map of <cloneurl, RepositoryModel>
1896      */
1897     public Map<String, RepositoryModel> getRepositories(String gitblitUrl, String token) {
1898         Map<String, String> federationSets = new HashMap<String, String>();
1899         for (String set : getStrings(Keys.federation.sets)) {
1900             federationSets.put(getFederationToken(set), set);
1901         }
1902
1903         // Determine the Gitblit clone url
1904         StringBuilder sb = new StringBuilder();
1905         sb.append(gitblitUrl);
1906         sb.append(Constants.GIT_PATH);
1907         sb.append("{0}");
1908         String cloneUrl = sb.toString();
1909
1910         // Retrieve all available repositories
1911         UserModel user = new UserModel(Constants.FEDERATION_USER);
1912         user.canAdmin = true;
1913         List<RepositoryModel> list = getRepositoryModels(user);
1914
1915         // create the [cloneurl, repositoryModel] map
1916         Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
1917         for (RepositoryModel model : list) {
1918             // by default, setup the url for THIS repository
1919             String url = MessageFormat.format(cloneUrl, model.name);
1920             switch (model.federationStrategy) {
1921             case EXCLUDE:
1922                 // skip this repository
1923                 continue;
1924             case FEDERATE_ORIGIN:
1925                 // federate the origin, if it is defined
1926                 if (!StringUtils.isEmpty(model.origin)) {
1927                     url = model.origin;
1928                 }
1929                 break;
1930             }
1931
1932             if (federationSets.containsKey(token)) {
1933                 // include repositories only for federation set
1934                 String set = federationSets.get(token);
1935                 if (model.federationSets.contains(set)) {
1936                     repositories.put(url, model);
1937                 }
1938             } else {
1939                 // standard federation token for ALL
1940                 repositories.put(url, model);
1941             }
1942         }
1943         return repositories;
1944     }
1945
1946     /**
1947      * Creates a proposal from the token.
1948      * 
1949      * @param gitblitUrl
1950      *            the url of this Gitblit instance
1951      * @param token
1952      * @return a potential proposal
1953      */
1954     public FederationProposal createFederationProposal(String gitblitUrl, String token) {
1955         FederationToken tokenType = FederationToken.REPOSITORIES;
1956         for (FederationToken type : FederationToken.values()) {
1957             if (token.equals(getFederationToken(type))) {
1958                 tokenType = type;
1959                 break;
1960             }
1961         }
1962         Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
1963         FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token,
1964                 repositories);
1965         return proposal;
1966     }
1967
1968     /**
831469 1969      * Returns the proposal identified by the supplied token.
JM 1970      * 
1971      * @param token
1972      * @return the specified proposal or null
1973      */
1974     public FederationProposal getPendingFederationProposal(String token) {
1975         List<FederationProposal> list = getPendingFederationProposals();
1976         for (FederationProposal proposal : list) {
1977             if (proposal.token.equals(token)) {
1978                 return proposal;
1979             }
1980         }
1981         return null;
1982     }
1983
1984     /**
1985      * Deletes a pending federation proposal.
1986      * 
1987      * @param a
1988      *            proposal
1989      * @return true if the proposal was deleted
1990      */
1991     public boolean deletePendingFederationProposal(FederationProposal proposal) {
b774de 1992         File folder = getProposalsFolder();
831469 1993         File file = new File(folder, proposal.token + Constants.PROPOSAL_EXT);
JM 1994         return file.delete();
1995     }
1996
1997     /**
d7905a 1998      * Returns the list of all Groovy push hook scripts. Script files must have
6cc1d4 1999      * .groovy extension
JM 2000      * 
2001      * @return list of available hook scripts
2002      */
d7905a 2003     public List<String> getAllScripts() {
6cc1d4 2004         File groovyFolder = getGroovyScriptsFolder();
JM 2005         File[] files = groovyFolder.listFiles(new FileFilter() {
2006             @Override
2007             public boolean accept(File pathname) {
2008                 return pathname.isFile() && pathname.getName().endsWith(".groovy");
2009             }
2010         });
2011         List<String> scripts = new ArrayList<String>();
2012         if (files != null) {
2013             for (File file : files) {
2014                 String script = file.getName().substring(0, file.getName().lastIndexOf('.'));
d7905a 2015                 scripts.add(script);
6cc1d4 2016             }
JM 2017         }
2018         return scripts;
2019     }
d7905a 2020
JM 2021     /**
2022      * Returns the list of pre-receive scripts the repository inherited from the
2023      * global settings and team affiliations.
2024      * 
2025      * @param repository
2026      *            if null only the globally specified scripts are returned
2027      * @return a list of scripts
2028      */
2029     public List<String> getPreReceiveScriptsInherited(RepositoryModel repository) {
2030         Set<String> scripts = new LinkedHashSet<String>();
2031         // Globals
0d013a 2032         for (String script : getStrings(Keys.groovy.preReceiveScripts)) {
JM 2033             if (script.endsWith(".groovy")) {
d7905a 2034                 scripts.add(script.substring(0, script.lastIndexOf('.')));
0d013a 2035             } else {
d7905a 2036                 scripts.add(script);
0d013a 2037             }
JM 2038         }
d7905a 2039
JM 2040         // Team Scripts
2041         if (repository != null) {
2042             for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
2043                 TeamModel team = userService.getTeamModel(teamname);
2044                 scripts.addAll(team.preReceiveScripts);
2045             }
2046         }
2047         return new ArrayList<String>(scripts);
0d013a 2048     }
d7905a 2049
JM 2050     /**
2051      * Returns the list of all available Groovy pre-receive push hook scripts
2052      * that are not already inherited by the repository. Script files must have
2053      * .groovy extension
2054      * 
2055      * @param repository
2056      *            optional parameter
2057      * @return list of available hook scripts
2058      */
2059     public List<String> getPreReceiveScriptsUnused(RepositoryModel repository) {
2060         Set<String> inherited = new TreeSet<String>(getPreReceiveScriptsInherited(repository));
2061
2062         // create list of available scripts by excluding inherited scripts
2063         List<String> scripts = new ArrayList<String>();
2064         for (String script : getAllScripts()) {
2065             if (!inherited.contains(script)) {
2066                 scripts.add(script);
2067             }
2068         }
2069         return scripts;
2070     }
2071
2072     /**
2073      * Returns the list of post-receive scripts the repository inherited from
2074      * the global settings and team affiliations.
2075      * 
2076      * @param repository
2077      *            if null only the globally specified scripts are returned
2078      * @return a list of scripts
2079      */
2080     public List<String> getPostReceiveScriptsInherited(RepositoryModel repository) {
2081         Set<String> scripts = new LinkedHashSet<String>();
2082         // Global Scripts
0d013a 2083         for (String script : getStrings(Keys.groovy.postReceiveScripts)) {
JM 2084             if (script.endsWith(".groovy")) {
d7905a 2085                 scripts.add(script.substring(0, script.lastIndexOf('.')));
0d013a 2086             } else {
d7905a 2087                 scripts.add(script);
0d013a 2088             }
JM 2089         }
d7905a 2090         // Team Scripts
JM 2091         if (repository != null) {
2092             for (String teamname : userService.getTeamnamesForRepositoryRole(repository.name)) {
2093                 TeamModel team = userService.getTeamModel(teamname);
2094                 scripts.addAll(team.postReceiveScripts);
2095             }
2096         }
2097         return new ArrayList<String>(scripts);
2098     }
2099
2100     /**
2101      * Returns the list of unused Groovy post-receive push hook scripts that are
2102      * not already inherited by the repository. Script files must have .groovy
2103      * extension
2104      * 
2105      * @param repository
2106      *            optional parameter
2107      * @return list of available hook scripts
2108      */
2109     public List<String> getPostReceiveScriptsUnused(RepositoryModel repository) {
2110         Set<String> inherited = new TreeSet<String>(getPostReceiveScriptsInherited(repository));
2111
2112         // create list of available scripts by excluding inherited scripts
2113         List<String> scripts = new ArrayList<String>();
2114         for (String script : getAllScripts()) {
2115             if (!inherited.contains(script)) {
2116                 scripts.add(script);
2117             }
2118         }
2119         return scripts;
0d013a 2120     }
d896e6 2121     
JM 2122     /**
2123      * Search the specified repositories using the Lucene query.
2124      * 
2125      * @param query
d04009 2126      * @param page
JM 2127      * @param pageSize
d896e6 2128      * @param repositories
JM 2129      * @return
2130      */
d04009 2131     public List<SearchResult> search(String query, int page, int pageSize, List<String> repositories) {        
JM 2132         List<SearchResult> srs = luceneExecutor.search(query, page, pageSize, repositories);
d896e6 2133         return srs;
JM 2134     }
0d013a 2135
6cc1d4 2136     /**
831469 2137      * Notify the administrators by email.
JM 2138      * 
2139      * @param subject
2140      * @param message
2141      */
eb96ea 2142     public void sendMailToAdministrators(String subject, String message) {
831469 2143         try {
JM 2144             Message mail = mailExecutor.createMessageForAdministrators();
2145             if (mail != null) {
2146                 mail.setSubject(subject);
2147                 mail.setText(message);
2148                 mailExecutor.queue(mail);
2149             }
2150         } catch (MessagingException e) {
2151             logger.error("Messaging error", e);
2152         }
2153     }
2154
2155     /**
fa54be 2156      * Notify users by email of something.
JM 2157      * 
2158      * @param subject
2159      * @param message
2160      * @param toAddresses
2161      */
0b9119 2162     public void sendMail(String subject, String message, Collection<String> toAddresses) {
eb96ea 2163         this.sendMail(subject, message, toAddresses.toArray(new String[0]));
fa54be 2164     }
JM 2165
2166     /**
2167      * Notify users by email of something.
2168      * 
2169      * @param subject
2170      * @param message
2171      * @param toAddresses
2172      */
eb96ea 2173     public void sendMail(String subject, String message, String... toAddresses) {
fa54be 2174         try {
JM 2175             Message mail = mailExecutor.createMessage(toAddresses);
2176             if (mail != null) {
2177                 mail.setSubject(subject);
2178                 mail.setText(message);
2179                 mailExecutor.queue(mail);
2180             }
2181         } catch (MessagingException e) {
2182             logger.error("Messaging error", e);
2183         }
b938ae 2184     }
JM 2185
2186     /**
b75734 2187      * Returns the descriptions/comments of the Gitblit config settings.
JM 2188      * 
84c1d5 2189      * @return SettingsModel
b75734 2190      */
84c1d5 2191     public ServerSettings getSettingsModel() {
b75734 2192         // ensure that the current values are updated in the setting models
773bb6 2193         for (String key : settings.getAllKeys(null)) {
JM 2194             SettingModel setting = settingsModel.get(key);
e09d4b 2195             if (setting == null) {
JM 2196                 // unreferenced setting, create a setting model
2197                 setting = new SettingModel();
2198                 setting.name = key;
2199                 settingsModel.add(setting);
773bb6 2200             }
e09d4b 2201             setting.currentValue = settings.getString(key, "");            
773bb6 2202         }
d7905a 2203         settingsModel.pushScripts = getAllScripts();
84c1d5 2204         return settingsModel;
b75734 2205     }
JM 2206
2207     /**
2208      * Parse the properties file and aggregate all the comments by the setting
2209      * key. A setting model tracks the current value, the default value, the
2210      * description of the setting and and directives about the setting.
2211      * 
2212      * @return Map<String, SettingModel>
2213      */
84c1d5 2214     private ServerSettings loadSettingModels() {
JM 2215         ServerSettings settingsModel = new ServerSettings();
0aa8cf 2216         settingsModel.supportsCredentialChanges = userService.supportsCredentialChanges();
JM 2217         settingsModel.supportsDisplayNameChanges = userService.supportsDisplayNameChanges();
2218         settingsModel.supportsEmailAddressChanges = userService.supportsEmailAddressChanges();
2219         settingsModel.supportsTeamMembershipChanges = userService.supportsTeamMembershipChanges();
b75734 2220         try {
JM 2221             // Read bundled Gitblit properties to extract setting descriptions.
2222             // This copy is pristine and only used for populating the setting
2223             // models map.
97a20e 2224             InputStream is = servletContext.getResourceAsStream("/WEB-INF/reference.properties");
b75734 2225             BufferedReader propertiesReader = new BufferedReader(new InputStreamReader(is));
JM 2226             StringBuilder description = new StringBuilder();
2227             SettingModel setting = new SettingModel();
2228             String line = null;
2229             while ((line = propertiesReader.readLine()) != null) {
2230                 if (line.length() == 0) {
2231                     description.setLength(0);
2232                     setting = new SettingModel();
2233                 } else {
2234                     if (line.charAt(0) == '#') {
2235                         if (line.length() > 1) {
2236                             String text = line.substring(1).trim();
2237                             if (SettingModel.CASE_SENSITIVE.equals(text)) {
2238                                 setting.caseSensitive = true;
2239                             } else if (SettingModel.RESTART_REQUIRED.equals(text)) {
2240                                 setting.restartRequired = true;
2241                             } else if (SettingModel.SPACE_DELIMITED.equals(text)) {
2242                                 setting.spaceDelimited = true;
2243                             } else if (text.startsWith(SettingModel.SINCE)) {
2244                                 try {
2245                                     setting.since = text.split(" ")[1];
2246                                 } catch (Exception e) {
2247                                     setting.since = text;
2248                                 }
2249                             } else {
2250                                 description.append(text);
2251                                 description.append('\n');
2252                             }
2253                         }
2254                     } else {
2255                         String[] kvp = line.split("=", 2);
2256                         String key = kvp[0].trim();
2257                         setting.name = key;
2258                         setting.defaultValue = kvp[1].trim();
2259                         setting.currentValue = setting.defaultValue;
2260                         setting.description = description.toString().trim();
84c1d5 2261                         settingsModel.add(setting);
b75734 2262                         description.setLength(0);
JM 2263                         setting = new SettingModel();
2264                     }
2265                 }
2266             }
2267             propertiesReader.close();
2268         } catch (NullPointerException e) {
2269             logger.error("Failed to find resource copy of gitblit.properties");
2270         } catch (IOException e) {
2271             logger.error("Failed to load resource copy of gitblit.properties");
2272         }
84c1d5 2273         return settingsModel;
b75734 2274     }
JM 2275
2276     /**
892570 2277      * Configure the Gitblit singleton with the specified settings source. This
JM 2278      * source may be file settings (Gitblit GO) or may be web.xml settings
2279      * (Gitblit WAR).
2280      * 
2281      * @param settings
2282      */
f6740d 2283     public void configureContext(IStoredSettings settings, boolean startFederation) {
1f9dae 2284         logger.info("Reading configuration from " + settings.toString());
892570 2285         this.settings = settings;
b774de 2286         repositoriesFolder = getRepositoriesFolder();
5450d0 2287         logger.info("Git repositories folder " + repositoriesFolder.getAbsolutePath());
b86562 2288         repositoryResolver = new FileResolver<Void>(repositoriesFolder, true);
fee060 2289
JM 2290         // calculate repository list settings checksum for future config changes
2291         repositoryListSettingsChecksum.set(getRepositoryListSettingsChecksum());
2292
2293         // build initial repository list
2294         if (settings.getBoolean(Keys.git.cacheRepositoryList,  true)) {
2295             logger.info("Identifying available repositories...");
2296             getRepositoryList();
2297         }
6c6e7d 2298         
JM 2299         logTimezone("JVM", TimeZone.getDefault());
2300         logTimezone(Constants.NAME, getTimezone());
2301
486ee1 2302         serverStatus = new ServerStatus(isGO());
85c2e6 2303         String realm = settings.getString(Keys.realm.userService, "users.properties");
JM 2304         IUserService loginService = null;
5450d0 2305         try {
892570 2306             // check to see if this "file" is a login service class
5450d0 2307             Class<?> realmClass = Class.forName(realm);
d25c59 2308             loginService = (IUserService) realmClass.newInstance();
5450d0 2309         } catch (Throwable t) {
eb96ea 2310             loginService = new GitblitUserService();
5450d0 2311         }
85c2e6 2312         setUserService(loginService);
13a3f5 2313         
JM 2314         // load and cache the project metadata
2315         projectConfigs = new FileBasedConfig(getFileOrFolder(Keys.web.projectsFile, "projects.conf"), FS.detect());
2316         getProjectConfigs();
2317         
831469 2318         mailExecutor = new MailExecutor(settings);
JM 2319         if (mailExecutor.isReady()) {
e31da0 2320             logger.info("Mail executor is scheduled to process the message queue every 2 minutes.");
831469 2321             scheduledExecutor.scheduleAtFixedRate(mailExecutor, 1, 2, TimeUnit.MINUTES);
JM 2322         } else {
2323             logger.warn("Mail server is not properly configured.  Mail services disabled.");
f6740d 2324         }
d896e6 2325         luceneExecutor = new LuceneExecutor(settings, repositoriesFolder);
273cb9 2326         logger.info("Lucene executor is scheduled to process indexed branches every 2 minutes.");
JM 2327         scheduledExecutor.scheduleAtFixedRate(luceneExecutor, 1, 2, TimeUnit.MINUTES);
f6740d 2328         if (startFederation) {
JM 2329             configureFederation();
478678 2330         }
JM 2331         
2332         // Configure JGit
2333         WindowCacheConfig cfg = new WindowCacheConfig();
2334         
2335         cfg.setPackedGitWindowSize(settings.getFilesize(Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
2336         cfg.setPackedGitLimit(settings.getFilesize(Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
2337         cfg.setDeltaBaseCacheLimit(settings.getFilesize(Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
2338         cfg.setPackedGitOpenFiles(settings.getFilesize(Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
2339         cfg.setStreamFileThreshold(settings.getFilesize(Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
2340         cfg.setPackedGitMMAP(settings.getBoolean(Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
2341         
2342         try {
2343             WindowCache.reconfigure(cfg);
2344             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitWindowSize, cfg.getPackedGitWindowSize()));
2345             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitLimit, cfg.getPackedGitLimit()));
2346             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.deltaBaseCacheLimit, cfg.getDeltaBaseCacheLimit()));
2347             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.packedGitOpenFiles, cfg.getPackedGitOpenFiles()));
2348             logger.debug(MessageFormat.format("{0} = {1,number,0}", Keys.git.streamFileThreshold, cfg.getStreamFileThreshold()));
2349             logger.debug(MessageFormat.format("{0} = {1}", Keys.git.packedGitMmap, cfg.isPackedGitMMAP()));
2350         } catch (IllegalArgumentException e) {
2351             logger.error("Failed to configure JGit parameters!", e);
2352         }
165254 2353
JP 2354         ContainerUtils.CVE_2007_0450.test();
6c6e7d 2355     }
JM 2356     
2357     private void logTimezone(String type, TimeZone zone) {
2358         SimpleDateFormat df = new SimpleDateFormat("z Z");
2359         df.setTimeZone(zone);
2360         String offset = df.format(new Date());
2361         logger.info(type + " timezone is " + zone.getID() + " (" + offset + ")");
87cc1e 2362     }
JM 2363
892570 2364     /**
JM 2365      * Configure Gitblit from the web.xml, if no configuration has already been
2366      * specified.
2367      * 
2368      * @see ServletContextListener.contextInitialize(ServletContextEvent)
2369      */
87cc1e 2370     @Override
JM 2371     public void contextInitialized(ServletContextEvent contextEvent) {
b75734 2372         servletContext = contextEvent.getServletContext();
892570 2373         if (settings == null) {
JM 2374             // Gitblit WAR is running in a servlet container
b774de 2375             ServletContext context = contextEvent.getServletContext();
JM 2376             WebXmlSettings webxmlSettings = new WebXmlSettings(context);
2377
2378             // 0.7.0 web.properties in the deployed war folder
7a1889 2379             String webProps = context.getRealPath("/WEB-INF/web.properties");
JM 2380             if (!StringUtils.isEmpty(webProps)) {
2381                 File overrideFile = new File(webProps);
2382                 if (overrideFile.exists()) {
2383                     webxmlSettings.applyOverrides(overrideFile);
2384                 }
b774de 2385             }
7a1889 2386             
b774de 2387
JM 2388             // 0.8.0 gitblit.properties file located outside the deployed war
2389             // folder lie, for example, on RedHat OpenShift.
7a1889 2390             File overrideFile = getFileOrFolder("gitblit.properties");
b774de 2391             if (!overrideFile.getPath().equals("gitblit.properties")) {
JM 2392                 webxmlSettings.applyOverrides(overrideFile);
2393             }
f6740d 2394             configureContext(webxmlSettings, true);
e36d4d 2395
JM 2396             // Copy the included scripts to the configured groovy folder
2397             File localScripts = getFileOrFolder(Keys.groovy.scriptsFolder, "groovy");
2398             if (!localScripts.exists()) {
2399                 File includedScripts = new File(context.getRealPath("/WEB-INF/groovy"));
2400                 if (!includedScripts.equals(localScripts)) {
2401                     try {
2402                         com.gitblit.utils.FileUtils.copy(localScripts, includedScripts.listFiles());
2403                     } catch (IOException e) {
2404                         logger.error(MessageFormat.format(
2405                                 "Failed to copy included Groovy scripts from {0} to {1}",
2406                                 includedScripts, localScripts));
2407                     }
2408                 }
2409             }
87cc1e 2410         }
b6db0d 2411         
JM 2412         settingsModel = loadSettingModels();
486ee1 2413         serverStatus.servletContainer = servletContext.getServerInfo();
87cc1e 2414     }
JM 2415
892570 2416     /**
JM 2417      * Gitblit is being shutdown either because the servlet container is
2418      * shutting down or because the servlet container is re-deploying Gitblit.
2419      */
87cc1e 2420     @Override
JM 2421     public void contextDestroyed(ServletContextEvent contextEvent) {
f339f5 2422         logger.info("Gitblit context destroyed by servlet container.");
831469 2423         scheduledExecutor.shutdownNow();
b938ae 2424         luceneExecutor.close();
87cc1e 2425     }
fc948c 2426 }