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 17KB

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