Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

GitBlitServer.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStreamReader;
  21. import java.io.OutputStream;
  22. import java.net.InetAddress;
  23. import java.net.ServerSocket;
  24. import java.net.Socket;
  25. import java.net.URL;
  26. import java.net.UnknownHostException;
  27. import java.security.ProtectionDomain;
  28. import java.text.MessageFormat;
  29. import java.util.ArrayList;
  30. import java.util.List;
  31. import java.util.Scanner;
  32. import org.eclipse.jetty.ajp.Ajp13SocketConnector;
  33. import org.eclipse.jetty.server.Connector;
  34. import org.eclipse.jetty.server.Server;
  35. import org.eclipse.jetty.server.bio.SocketConnector;
  36. import org.eclipse.jetty.server.nio.SelectChannelConnector;
  37. import org.eclipse.jetty.server.session.HashSessionManager;
  38. import org.eclipse.jetty.server.ssl.SslConnector;
  39. import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
  40. import org.eclipse.jetty.server.ssl.SslSocketConnector;
  41. import org.eclipse.jetty.util.thread.QueuedThreadPool;
  42. import org.eclipse.jetty.webapp.WebAppContext;
  43. import org.eclipse.jgit.util.FileUtils;
  44. import org.slf4j.Logger;
  45. import org.slf4j.LoggerFactory;
  46. import com.beust.jcommander.JCommander;
  47. import com.beust.jcommander.Parameter;
  48. import com.beust.jcommander.ParameterException;
  49. import com.beust.jcommander.Parameters;
  50. import com.gitblit.utils.StringUtils;
  51. import com.unboundid.ldap.listener.InMemoryDirectoryServer;
  52. import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
  53. import com.unboundid.ldap.listener.InMemoryListenerConfig;
  54. import com.unboundid.ldif.LDIFReader;
  55. /**
  56. * GitBlitServer is the embedded Jetty server for Gitblit GO. This class starts
  57. * and stops an instance of Jetty that is configured from a combination of the
  58. * gitblit.properties file and command line parameters. JCommander is used to
  59. * simplify command line parameter processing. This class also automatically
  60. * generates a self-signed certificate for localhost, if the keystore does not
  61. * already exist.
  62. *
  63. * @author James Moger
  64. *
  65. */
  66. public class GitBlitServer {
  67. private static Logger logger;
  68. public static void main(String... args) {
  69. Params params = new Params();
  70. JCommander jc = new JCommander(params);
  71. try {
  72. jc.parse(args);
  73. if (params.help) {
  74. usage(jc, null);
  75. }
  76. } catch (ParameterException t) {
  77. usage(jc, t);
  78. }
  79. if (params.stop) {
  80. stop(params);
  81. } else {
  82. start(params);
  83. }
  84. }
  85. /**
  86. * Display the command line usage of Gitblit GO.
  87. *
  88. * @param jc
  89. * @param t
  90. */
  91. private static void usage(JCommander jc, ParameterException t) {
  92. System.out.println(Constants.BORDER);
  93. System.out.println(Constants.getGitBlitVersion());
  94. System.out.println(Constants.BORDER);
  95. System.out.println();
  96. if (t != null) {
  97. System.out.println(t.getMessage());
  98. System.out.println();
  99. }
  100. if (jc != null) {
  101. jc.usage();
  102. System.out
  103. .println("\nExample:\n java -server -Xmx1024M -jar gitblit.jar --repositoriesFolder c:\\git --httpPort 80 --httpsPort 443");
  104. }
  105. System.exit(0);
  106. }
  107. /**
  108. * Stop Gitblt GO.
  109. */
  110. public static void stop(Params params) {
  111. try {
  112. Socket s = new Socket(InetAddress.getByName("127.0.0.1"), params.shutdownPort);
  113. OutputStream out = s.getOutputStream();
  114. System.out.println("Sending Shutdown Request to " + Constants.NAME);
  115. out.write("\r\n".getBytes());
  116. out.flush();
  117. s.close();
  118. } catch (UnknownHostException e) {
  119. e.printStackTrace();
  120. } catch (IOException e) {
  121. e.printStackTrace();
  122. }
  123. }
  124. /**
  125. * Start Gitblit GO.
  126. */
  127. private static void start(Params params) {
  128. FileSettings settings = Params.FILESETTINGS;
  129. if (!StringUtils.isEmpty(params.settingsfile)) {
  130. if (new File(params.settingsfile).exists()) {
  131. settings = new FileSettings(params.settingsfile);
  132. }
  133. }
  134. logger = LoggerFactory.getLogger(GitBlitServer.class);
  135. logger.info(Constants.BORDER);
  136. logger.info(" _____ _ _ _ _ _ _");
  137. logger.info(" | __ \\(_)| | | | | |(_)| |");
  138. logger.info(" | | \\/ _ | |_ | |__ | | _ | |_");
  139. logger.info(" | | __ | || __|| '_ \\ | || || __|");
  140. logger.info(" | |_\\ \\| || |_ | |_) || || || |_");
  141. logger.info(" \\____/|_| \\__||_.__/ |_||_| \\__|");
  142. int spacing = (Constants.BORDER.length() - Constants.getGitBlitVersion().length()) / 2;
  143. StringBuilder sb = new StringBuilder();
  144. while (spacing > 0) {
  145. spacing--;
  146. sb.append(' ');
  147. }
  148. logger.info(sb.toString() + Constants.getGitBlitVersion());
  149. logger.info("");
  150. logger.info(Constants.BORDER);
  151. String osname = System.getProperty("os.name");
  152. String osversion = System.getProperty("os.version");
  153. logger.info("Running on " + osname + " (" + osversion + ")");
  154. List<Connector> connectors = new ArrayList<Connector>();
  155. // conditionally configure the http connector
  156. if (params.port > 0) {
  157. Connector httpConnector = createConnector(params.useNIO, params.port);
  158. String bindInterface = settings.getString(Keys.server.httpBindInterface, null);
  159. if (!StringUtils.isEmpty(bindInterface)) {
  160. logger.warn(MessageFormat.format("Binding connector on port {0,number,0} to {1}",
  161. params.port, bindInterface));
  162. httpConnector.setHost(bindInterface);
  163. }
  164. if (params.port < 1024 && !isWindows()) {
  165. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  166. }
  167. connectors.add(httpConnector);
  168. }
  169. // conditionally configure the https connector
  170. if (params.securePort > 0) {
  171. File keystore = new File("keystore");
  172. if (!keystore.exists()) {
  173. logger.info("Generating self-signed SSL certificate for localhost");
  174. MakeCertificate.generateSelfSignedCertificate("localhost", keystore,
  175. params.storePassword);
  176. }
  177. if (keystore.exists()) {
  178. Connector secureConnector = createSSLConnector(keystore, params.storePassword,
  179. params.useNIO, params.securePort);
  180. String bindInterface = settings.getString(Keys.server.httpsBindInterface, null);
  181. if (!StringUtils.isEmpty(bindInterface)) {
  182. logger.warn(MessageFormat.format(
  183. "Binding ssl connector on port {0,number,0} to {1}", params.securePort,
  184. bindInterface));
  185. secureConnector.setHost(bindInterface);
  186. }
  187. if (params.securePort < 1024 && !isWindows()) {
  188. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  189. }
  190. connectors.add(secureConnector);
  191. } else {
  192. logger.warn("Failed to find or load Keystore?");
  193. logger.warn("SSL connector DISABLED.");
  194. }
  195. }
  196. // conditionally configure the ajp connector
  197. if (params.ajpPort > 0) {
  198. Connector ajpConnector = createAJPConnector(params.ajpPort);
  199. String bindInterface = settings.getString(Keys.server.ajpBindInterface, null);
  200. if (!StringUtils.isEmpty(bindInterface)) {
  201. logger.warn(MessageFormat.format("Binding connector on port {0,number,0} to {1}",
  202. params.ajpPort, bindInterface));
  203. ajpConnector.setHost(bindInterface);
  204. }
  205. if (params.ajpPort < 1024 && !isWindows()) {
  206. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  207. }
  208. connectors.add(ajpConnector);
  209. }
  210. // tempDir is where the embedded Gitblit web application is expanded and
  211. // where Jetty creates any necessary temporary files
  212. File tempDir = new File(params.temp);
  213. if (tempDir.exists()) {
  214. try {
  215. FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY);
  216. } catch (IOException x) {
  217. logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x);
  218. }
  219. }
  220. if (!tempDir.mkdirs()) {
  221. logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath());
  222. }
  223. Server server = new Server();
  224. server.setStopAtShutdown(true);
  225. server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
  226. // Get the execution path of this class
  227. // We use this to set the WAR path.
  228. ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain();
  229. URL location = protectionDomain.getCodeSource().getLocation();
  230. // Root WebApp Context
  231. WebAppContext rootContext = new WebAppContext();
  232. rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/"));
  233. rootContext.setServer(server);
  234. rootContext.setWar(location.toExternalForm());
  235. rootContext.setTempDirectory(tempDir);
  236. // Set cookies HttpOnly so they are not accessible to JavaScript engines
  237. HashSessionManager sessionManager = new HashSessionManager();
  238. sessionManager.setHttpOnly(true);
  239. // Use secure cookies if only serving https
  240. sessionManager.setSecureCookies(params.port <= 0 && params.securePort > 0);
  241. rootContext.getSessionHandler().setSessionManager(sessionManager);
  242. // Ensure there is a defined User Service
  243. String realmUsers = params.userService;
  244. if (StringUtils.isEmpty(realmUsers)) {
  245. logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService));
  246. return;
  247. }
  248. // Override settings from the command-line
  249. settings.overrideSetting(Keys.realm.userService, params.userService);
  250. settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder);
  251. // Start up an in-memory LDAP server, if configured
  252. try {
  253. if (StringUtils.isEmpty(params.ldapLdifFile) == false) {
  254. File ldifFile = new File(params.ldapLdifFile);
  255. if (ldifFile != null && ldifFile.exists()) {
  256. String firstLine = new Scanner(ldifFile).nextLine();
  257. String rootDN = firstLine.substring(4);
  258. String bindUserName = settings.getString(Keys.realm.ldap_username, "");
  259. String bindPassword = settings.getString(Keys.realm.ldap_password, "");
  260. InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN);
  261. config.addAdditionalBindCredentials(bindUserName, bindPassword);
  262. config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 389));
  263. config.setSchema(null);
  264. InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
  265. ds.importFromLDIF(true, new LDIFReader(ldifFile));
  266. ds.startListening();
  267. logger.info("LDAP Server started at ldap://localhost:389");
  268. }
  269. }
  270. } catch (Exception e) {
  271. // Completely optional, just show a warning
  272. logger.warn("Unable to start LDAP server", e);
  273. }
  274. // Set the server's contexts
  275. server.setHandler(rootContext);
  276. // Setup the GitBlit context
  277. GitBlit gitblit = GitBlit.self();
  278. gitblit.configureContext(settings, true);
  279. rootContext.addEventListener(gitblit);
  280. try {
  281. // start the shutdown monitor
  282. if (params.shutdownPort > 0) {
  283. Thread shutdownMonitor = new ShutdownMonitorThread(server, params);
  284. shutdownMonitor.start();
  285. }
  286. // start Jetty
  287. server.start();
  288. server.join();
  289. } catch (Exception e) {
  290. e.printStackTrace();
  291. System.exit(100);
  292. }
  293. }
  294. /**
  295. * Creates an http connector.
  296. *
  297. * @param useNIO
  298. * @param port
  299. * @return an http connector
  300. */
  301. private static Connector createConnector(boolean useNIO, int port) {
  302. Connector connector;
  303. if (useNIO) {
  304. logger.info("Setting up NIO SelectChannelConnector on port " + port);
  305. SelectChannelConnector nioconn = new SelectChannelConnector();
  306. nioconn.setSoLingerTime(-1);
  307. nioconn.setThreadPool(new QueuedThreadPool(20));
  308. connector = nioconn;
  309. } else {
  310. logger.info("Setting up SocketConnector on port " + port);
  311. SocketConnector sockconn = new SocketConnector();
  312. connector = sockconn;
  313. }
  314. connector.setPort(port);
  315. connector.setMaxIdleTime(30000);
  316. return connector;
  317. }
  318. /**
  319. * Creates an https connector.
  320. *
  321. * SSL renegotiation will be enabled if the JVM is 1.6.0_22 or later.
  322. * oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html
  323. *
  324. * @param keystore
  325. * @param password
  326. * @param useNIO
  327. * @param port
  328. * @return an https connector
  329. */
  330. private static Connector createSSLConnector(File keystore, String password, boolean useNIO,
  331. int port) {
  332. SslConnector connector;
  333. if (useNIO) {
  334. logger.info("Setting up NIO SslSelectChannelConnector on port " + port);
  335. SslSelectChannelConnector ssl = new SslSelectChannelConnector();
  336. ssl.setSoLingerTime(-1);
  337. ssl.setThreadPool(new QueuedThreadPool(20));
  338. connector = ssl;
  339. } else {
  340. logger.info("Setting up NIO SslSocketConnector on port " + port);
  341. SslSocketConnector ssl = new SslSocketConnector();
  342. connector = ssl;
  343. }
  344. // disable renegotiation unless this is a patched JVM
  345. boolean allowRenegotiation = false;
  346. String v = System.getProperty("java.version");
  347. if (v.startsWith("1.7")) {
  348. allowRenegotiation = true;
  349. } else if (v.startsWith("1.6")) {
  350. // 1.6.0_22 was first release with RFC-5746 implemented fix.
  351. if (v.indexOf('_') > -1) {
  352. String b = v.substring(v.indexOf('_') + 1);
  353. if (Integer.parseInt(b) >= 22) {
  354. allowRenegotiation = true;
  355. }
  356. }
  357. }
  358. if (allowRenegotiation) {
  359. logger.info(" allowing SSL renegotiation on Java " + v);
  360. connector.setAllowRenegotiate(allowRenegotiation);
  361. }
  362. connector.setKeystore(keystore.getAbsolutePath());
  363. connector.setPassword(password);
  364. connector.setPort(port);
  365. connector.setMaxIdleTime(30000);
  366. return connector;
  367. }
  368. /**
  369. * Creates an ajp connector.
  370. *
  371. * @param port
  372. * @return an ajp connector
  373. */
  374. private static Connector createAJPConnector(int port) {
  375. logger.info("Setting up AJP Connector on port " + port);
  376. Ajp13SocketConnector ajp = new Ajp13SocketConnector();
  377. ajp.setPort(port);
  378. if (port < 1024 && !isWindows()) {
  379. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  380. }
  381. return ajp;
  382. }
  383. /**
  384. * Tests to see if the operating system is Windows.
  385. *
  386. * @return true if this is a windows machine
  387. */
  388. private static boolean isWindows() {
  389. return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
  390. }
  391. /**
  392. * The ShutdownMonitorThread opens a socket on a specified port and waits
  393. * for an incoming connection. When that connection is accepted a shutdown
  394. * message is issued to the running Jetty server.
  395. *
  396. * @author James Moger
  397. *
  398. */
  399. private static class ShutdownMonitorThread extends Thread {
  400. private final ServerSocket socket;
  401. private final Server server;
  402. private final Logger logger = LoggerFactory.getLogger(ShutdownMonitorThread.class);
  403. public ShutdownMonitorThread(Server server, Params params) {
  404. this.server = server;
  405. setDaemon(true);
  406. setName(Constants.NAME + " Shutdown Monitor");
  407. ServerSocket skt = null;
  408. try {
  409. skt = new ServerSocket(params.shutdownPort, 1, InetAddress.getByName("127.0.0.1"));
  410. } catch (Exception e) {
  411. logger.warn("Could not open shutdown monitor on port " + params.shutdownPort, e);
  412. }
  413. socket = skt;
  414. }
  415. @Override
  416. public void run() {
  417. logger.info("Shutdown Monitor listening on port " + socket.getLocalPort());
  418. Socket accept;
  419. try {
  420. accept = socket.accept();
  421. BufferedReader reader = new BufferedReader(new InputStreamReader(
  422. accept.getInputStream()));
  423. reader.readLine();
  424. logger.info(Constants.BORDER);
  425. logger.info("Stopping " + Constants.NAME);
  426. logger.info(Constants.BORDER);
  427. server.stop();
  428. server.setStopAtShutdown(false);
  429. accept.close();
  430. socket.close();
  431. } catch (Exception e) {
  432. logger.warn("Failed to shutdown Jetty", e);
  433. }
  434. }
  435. }
  436. /**
  437. * JCommander Parameters class for GitBlitServer.
  438. */
  439. @Parameters(separators = " ")
  440. private static class Params {
  441. private static final FileSettings FILESETTINGS = new FileSettings(Constants.PROPERTIES_FILE);
  442. /*
  443. * Server parameters
  444. */
  445. @Parameter(names = { "-h", "--help" }, description = "Show this help")
  446. public Boolean help = false;
  447. @Parameter(names = { "--stop" }, description = "Stop Server")
  448. public Boolean stop = false;
  449. @Parameter(names = { "--tempFolder" }, description = "Folder for server to extract built-in webapp")
  450. public String temp = FILESETTINGS.getString(Keys.server.tempFolder, "temp");
  451. /*
  452. * GIT Servlet Parameters
  453. */
  454. @Parameter(names = { "--repositoriesFolder" }, description = "Git Repositories Folder")
  455. public String repositoriesFolder = FILESETTINGS.getString(Keys.git.repositoriesFolder,
  456. "repos");
  457. /*
  458. * Authentication Parameters
  459. */
  460. @Parameter(names = { "--userService" }, description = "Authentication and Authorization Service (filename or fully qualified classname)")
  461. public String userService = FILESETTINGS.getString(Keys.realm.userService,
  462. "users.properties");
  463. /*
  464. * JETTY Parameters
  465. */
  466. @Parameter(names = { "--useNio" }, description = "Use NIO Connector else use Socket Connector.")
  467. public Boolean useNIO = FILESETTINGS.getBoolean(Keys.server.useNio, true);
  468. @Parameter(names = "--httpPort", description = "HTTP port for to serve. (port <= 0 will disable this connector)")
  469. public Integer port = FILESETTINGS.getInteger(Keys.server.httpPort, 80);
  470. @Parameter(names = "--httpsPort", description = "HTTPS port to serve. (port <= 0 will disable this connector)")
  471. public Integer securePort = FILESETTINGS.getInteger(Keys.server.httpsPort, 443);
  472. @Parameter(names = "--ajpPort", description = "AJP port to serve. (port <= 0 will disable this connector)")
  473. public Integer ajpPort = FILESETTINGS.getInteger(Keys.server.ajpPort, 0);
  474. @Parameter(names = "--storePassword", description = "Password for SSL (https) keystore.")
  475. public String storePassword = FILESETTINGS.getString(Keys.server.storePassword, "");
  476. @Parameter(names = "--shutdownPort", description = "Port for Shutdown Monitor to listen on. (port <= 0 will disable this monitor)")
  477. public Integer shutdownPort = FILESETTINGS.getInteger(Keys.server.shutdownPort, 8081);
  478. /*
  479. * Setting overrides
  480. */
  481. @Parameter(names = { "--settings" }, description = "Path to alternative settings")
  482. public String settingsfile;
  483. @Parameter(names = { "--ldapLdifFile" }, description = "Path to LDIF file. This will cause an in-memory LDAP server to be started according to gitblit settings")
  484. public String ldapLdifFile;
  485. }
  486. }