Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

GitBlitServer.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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.BufferedWriter;
  19. import java.io.File;
  20. import java.io.FileWriter;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.InputStreamReader;
  24. import java.io.OutputStream;
  25. import java.net.InetAddress;
  26. import java.net.ServerSocket;
  27. import java.net.Socket;
  28. import java.net.URI;
  29. import java.net.URL;
  30. import java.net.UnknownHostException;
  31. import java.security.ProtectionDomain;
  32. import java.text.MessageFormat;
  33. import java.util.ArrayList;
  34. import java.util.Date;
  35. import java.util.List;
  36. import java.util.Properties;
  37. import java.util.Scanner;
  38. import org.apache.log4j.PropertyConfigurator;
  39. import org.eclipse.jetty.ajp.Ajp13SocketConnector;
  40. import org.eclipse.jetty.security.ConstraintMapping;
  41. import org.eclipse.jetty.security.ConstraintSecurityHandler;
  42. import org.eclipse.jetty.server.Connector;
  43. import org.eclipse.jetty.server.Server;
  44. import org.eclipse.jetty.server.bio.SocketConnector;
  45. import org.eclipse.jetty.server.nio.SelectChannelConnector;
  46. import org.eclipse.jetty.server.session.HashSessionManager;
  47. import org.eclipse.jetty.server.ssl.SslConnector;
  48. import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
  49. import org.eclipse.jetty.server.ssl.SslSocketConnector;
  50. import org.eclipse.jetty.util.security.Constraint;
  51. import org.eclipse.jetty.util.thread.QueuedThreadPool;
  52. import org.eclipse.jetty.webapp.WebAppContext;
  53. import org.eclipse.jgit.storage.file.FileBasedConfig;
  54. import org.eclipse.jgit.util.FS;
  55. import org.eclipse.jgit.util.FileUtils;
  56. import org.kohsuke.args4j.CmdLineException;
  57. import org.kohsuke.args4j.CmdLineParser;
  58. import org.kohsuke.args4j.Option;
  59. import org.slf4j.Logger;
  60. import org.slf4j.LoggerFactory;
  61. import com.gitblit.authority.GitblitAuthority;
  62. import com.gitblit.authority.NewCertificateConfig;
  63. import com.gitblit.servlet.GitblitContext;
  64. import com.gitblit.utils.StringUtils;
  65. import com.gitblit.utils.TimeUtils;
  66. import com.gitblit.utils.X509Utils;
  67. import com.gitblit.utils.X509Utils.X509Log;
  68. import com.gitblit.utils.X509Utils.X509Metadata;
  69. import com.unboundid.ldap.listener.InMemoryDirectoryServer;
  70. import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
  71. import com.unboundid.ldap.listener.InMemoryListenerConfig;
  72. import com.unboundid.ldif.LDIFReader;
  73. /**
  74. * GitBlitServer is the embedded Jetty server for Gitblit GO. This class starts
  75. * and stops an instance of Jetty that is configured from a combination of the
  76. * gitblit.properties file and command line parameters. JCommander is used to
  77. * simplify command line parameter processing. This class also automatically
  78. * generates a self-signed certificate for localhost, if the keystore does not
  79. * already exist.
  80. *
  81. * @author James Moger
  82. *
  83. */
  84. public class GitBlitServer {
  85. private static Logger logger;
  86. public static void main(String... args) {
  87. GitBlitServer server = new GitBlitServer();
  88. // filter out the baseFolder parameter
  89. List<String> filtered = new ArrayList<String>();
  90. String folder = "data";
  91. for (int i = 0; i < args.length; i++) {
  92. String arg = args[i];
  93. if (arg.equals("--baseFolder")) {
  94. if (i + 1 == args.length) {
  95. System.out.println("Invalid --baseFolder parameter!");
  96. System.exit(-1);
  97. } else if (!".".equals(args[i + 1])) {
  98. folder = args[i + 1];
  99. }
  100. i = i + 1;
  101. } else {
  102. filtered.add(arg);
  103. }
  104. }
  105. Params.baseFolder = folder;
  106. Params params = new Params();
  107. CmdLineParser parser = new CmdLineParser(params);
  108. try {
  109. parser.parseArgument(filtered);
  110. if (params.help) {
  111. server.usage(parser, null);
  112. }
  113. } catch (CmdLineException t) {
  114. server.usage(parser, t);
  115. }
  116. if (params.stop) {
  117. server.stop(params);
  118. } else {
  119. server.start(params);
  120. }
  121. }
  122. /**
  123. * Display the command line usage of Gitblit GO.
  124. *
  125. * @param parser
  126. * @param t
  127. */
  128. protected final void usage(CmdLineParser parser, CmdLineException t) {
  129. System.out.println(Constants.BORDER);
  130. System.out.println(Constants.getGitBlitVersion());
  131. System.out.println(Constants.BORDER);
  132. System.out.println();
  133. if (t != null) {
  134. System.out.println(t.getMessage());
  135. System.out.println();
  136. }
  137. if (parser != null) {
  138. parser.printUsage(System.out);
  139. System.out
  140. .println("\nExample:\n java -server -Xmx1024M -jar gitblit.jar --repositoriesFolder c:\\git --httpPort 80 --httpsPort 443");
  141. }
  142. System.exit(0);
  143. }
  144. /**
  145. * Stop Gitblt GO.
  146. */
  147. public void stop(Params params) {
  148. try {
  149. Socket s = new Socket(InetAddress.getByName("127.0.0.1"), params.shutdownPort);
  150. OutputStream out = s.getOutputStream();
  151. System.out.println("Sending Shutdown Request to " + Constants.NAME);
  152. out.write("\r\n".getBytes());
  153. out.flush();
  154. s.close();
  155. } catch (UnknownHostException e) {
  156. e.printStackTrace();
  157. } catch (IOException e) {
  158. e.printStackTrace();
  159. }
  160. }
  161. /**
  162. * Start Gitblit GO.
  163. */
  164. protected final void start(Params params) {
  165. final File baseFolder = new File(Params.baseFolder).getAbsoluteFile();
  166. FileSettings settings = params.FILESETTINGS;
  167. if (!StringUtils.isEmpty(params.settingsfile)) {
  168. if (new File(params.settingsfile).exists()) {
  169. settings = new FileSettings(params.settingsfile);
  170. }
  171. }
  172. if (params.dailyLogFile) {
  173. // Configure log4j for daily log file generation
  174. InputStream is = null;
  175. try {
  176. is = getClass().getResourceAsStream("/log4j.properties");
  177. Properties loggingProperties = new Properties();
  178. loggingProperties.load(is);
  179. loggingProperties.put("log4j.appender.R.File", new File(baseFolder, "logs/gitblit.log").getAbsolutePath());
  180. loggingProperties.put("log4j.rootCategory", "INFO, R");
  181. if (settings.getBoolean(Keys.web.debugMode, false)) {
  182. loggingProperties.put("log4j.logger.com.gitblit", "DEBUG");
  183. }
  184. PropertyConfigurator.configure(loggingProperties);
  185. } catch (Exception e) {
  186. e.printStackTrace();
  187. } finally {
  188. try {
  189. is.close();
  190. } catch (IOException e) {
  191. e.printStackTrace();
  192. }
  193. }
  194. }
  195. logger = LoggerFactory.getLogger(GitBlitServer.class);
  196. logger.info(Constants.BORDER);
  197. logger.info(" _____ _ _ _ _ _ _");
  198. logger.info(" | __ \\(_)| | | | | |(_)| |");
  199. logger.info(" | | \\/ _ | |_ | |__ | | _ | |_");
  200. logger.info(" | | __ | || __|| '_ \\ | || || __|");
  201. logger.info(" | |_\\ \\| || |_ | |_) || || || |_");
  202. logger.info(" \\____/|_| \\__||_.__/ |_||_| \\__|");
  203. int spacing = (Constants.BORDER.length() - Constants.getGitBlitVersion().length()) / 2;
  204. StringBuilder sb = new StringBuilder();
  205. while (spacing > 0) {
  206. spacing--;
  207. sb.append(' ');
  208. }
  209. logger.info(sb.toString() + Constants.getGitBlitVersion());
  210. logger.info("");
  211. logger.info(Constants.BORDER);
  212. System.setProperty("java.awt.headless", "true");
  213. String osname = System.getProperty("os.name");
  214. String osversion = System.getProperty("os.version");
  215. logger.info("Running on " + osname + " (" + osversion + ")");
  216. List<Connector> connectors = new ArrayList<Connector>();
  217. // conditionally configure the http connector
  218. if (params.port > 0) {
  219. Connector httpConnector = createConnector(params.useNIO, params.port, settings.getInteger(Keys.server.threadPoolSize, 50));
  220. String bindInterface = settings.getString(Keys.server.httpBindInterface, null);
  221. if (!StringUtils.isEmpty(bindInterface)) {
  222. logger.warn(MessageFormat.format("Binding connector on port {0,number,0} to {1}",
  223. params.port, bindInterface));
  224. httpConnector.setHost(bindInterface);
  225. }
  226. if (params.port < 1024 && !isWindows()) {
  227. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  228. }
  229. if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
  230. // redirect HTTP requests to HTTPS
  231. if (httpConnector instanceof SelectChannelConnector) {
  232. ((SelectChannelConnector) httpConnector).setConfidentialPort(params.securePort);
  233. } else {
  234. ((SocketConnector) httpConnector).setConfidentialPort(params.securePort);
  235. }
  236. }
  237. connectors.add(httpConnector);
  238. }
  239. // conditionally configure the https connector
  240. if (params.securePort > 0) {
  241. File certificatesConf = new File(baseFolder, X509Utils.CA_CONFIG);
  242. File serverKeyStore = new File(baseFolder, X509Utils.SERVER_KEY_STORE);
  243. File serverTrustStore = new File(baseFolder, X509Utils.SERVER_TRUST_STORE);
  244. File caRevocationList = new File(baseFolder, X509Utils.CA_REVOCATION_LIST);
  245. // generate CA & web certificates, create certificate stores
  246. X509Metadata metadata = new X509Metadata("localhost", params.storePassword);
  247. // set default certificate values from config file
  248. if (certificatesConf.exists()) {
  249. FileBasedConfig config = new FileBasedConfig(certificatesConf, FS.detect());
  250. try {
  251. config.load();
  252. } catch (Exception e) {
  253. logger.error("Error parsing " + certificatesConf, e);
  254. }
  255. NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
  256. certificateConfig.update(metadata);
  257. }
  258. metadata.notAfter = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
  259. X509Utils.prepareX509Infrastructure(metadata, baseFolder, new X509Log() {
  260. @Override
  261. public void log(String message) {
  262. BufferedWriter writer = null;
  263. try {
  264. writer = new BufferedWriter(new FileWriter(new File(baseFolder, X509Utils.CERTS + File.separator + "log.txt"), true));
  265. writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
  266. writer.newLine();
  267. writer.flush();
  268. } catch (Exception e) {
  269. LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
  270. } finally {
  271. if (writer != null) {
  272. try {
  273. writer.close();
  274. } catch (IOException e) {
  275. }
  276. }
  277. }
  278. }
  279. });
  280. if (serverKeyStore.exists()) {
  281. Connector secureConnector = createSSLConnector(params.alias, serverKeyStore, serverTrustStore, params.storePassword,
  282. caRevocationList, params.useNIO, params.securePort, settings.getInteger(Keys.server.threadPoolSize, 50), params.requireClientCertificates);
  283. String bindInterface = settings.getString(Keys.server.httpsBindInterface, null);
  284. if (!StringUtils.isEmpty(bindInterface)) {
  285. logger.warn(MessageFormat.format(
  286. "Binding ssl connector on port {0,number,0} to {1}", params.securePort,
  287. bindInterface));
  288. secureConnector.setHost(bindInterface);
  289. }
  290. if (params.securePort < 1024 && !isWindows()) {
  291. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  292. }
  293. connectors.add(secureConnector);
  294. } else {
  295. logger.warn("Failed to find or load Keystore?");
  296. logger.warn("SSL connector DISABLED.");
  297. }
  298. }
  299. // conditionally configure the ajp connector
  300. if (params.ajpPort > 0) {
  301. Connector ajpConnector = createAJPConnector(params.ajpPort);
  302. String bindInterface = settings.getString(Keys.server.ajpBindInterface, null);
  303. if (!StringUtils.isEmpty(bindInterface)) {
  304. logger.warn(MessageFormat.format("Binding connector on port {0,number,0} to {1}",
  305. params.ajpPort, bindInterface));
  306. ajpConnector.setHost(bindInterface);
  307. }
  308. if (params.ajpPort < 1024 && !isWindows()) {
  309. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  310. }
  311. connectors.add(ajpConnector);
  312. }
  313. // tempDir is where the embedded Gitblit web application is expanded and
  314. // where Jetty creates any necessary temporary files
  315. File tempDir = com.gitblit.utils.FileUtils.resolveParameter(Constants.baseFolder$, baseFolder, params.temp);
  316. if (tempDir.exists()) {
  317. try {
  318. FileUtils.delete(tempDir, FileUtils.RECURSIVE | FileUtils.RETRY);
  319. } catch (IOException x) {
  320. logger.warn("Failed to delete temp dir " + tempDir.getAbsolutePath(), x);
  321. }
  322. }
  323. if (!tempDir.mkdirs()) {
  324. logger.warn("Failed to create temp dir " + tempDir.getAbsolutePath());
  325. }
  326. Server server = new Server();
  327. server.setStopAtShutdown(true);
  328. server.setConnectors(connectors.toArray(new Connector[connectors.size()]));
  329. // Get the execution path of this class
  330. // We use this to set the WAR path.
  331. ProtectionDomain protectionDomain = GitBlitServer.class.getProtectionDomain();
  332. URL location = protectionDomain.getCodeSource().getLocation();
  333. // Root WebApp Context
  334. WebAppContext rootContext = new WebAppContext();
  335. rootContext.setContextPath(settings.getString(Keys.server.contextPath, "/"));
  336. rootContext.setServer(server);
  337. rootContext.setWar(location.toExternalForm());
  338. rootContext.setTempDirectory(tempDir);
  339. // Set cookies HttpOnly so they are not accessible to JavaScript engines
  340. HashSessionManager sessionManager = new HashSessionManager();
  341. sessionManager.setHttpOnly(true);
  342. // Use secure cookies if only serving https
  343. sessionManager.setSecureRequestOnly(params.port <= 0 && params.securePort > 0);
  344. rootContext.getSessionHandler().setSessionManager(sessionManager);
  345. // Ensure there is a defined User Service
  346. String realmUsers = params.userService;
  347. if (StringUtils.isEmpty(realmUsers)) {
  348. logger.error(MessageFormat.format("PLEASE SPECIFY {0}!!", Keys.realm.userService));
  349. return;
  350. }
  351. // Override settings from the command-line
  352. settings.overrideSetting(Keys.realm.userService, params.userService);
  353. settings.overrideSetting(Keys.git.repositoriesFolder, params.repositoriesFolder);
  354. settings.overrideSetting(Keys.git.daemonPort, params.gitPort);
  355. // Start up an in-memory LDAP server, if configured
  356. try {
  357. if (!StringUtils.isEmpty(params.ldapLdifFile)) {
  358. File ldifFile = new File(params.ldapLdifFile);
  359. if (ldifFile != null && ldifFile.exists()) {
  360. URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server));
  361. String firstLine = new Scanner(ldifFile).nextLine();
  362. String rootDN = firstLine.substring(4);
  363. String bindUserName = settings.getString(Keys.realm.ldap.username, "");
  364. String bindPassword = settings.getString(Keys.realm.ldap.password, "");
  365. // Get the port
  366. int port = ldapUrl.getPort();
  367. if (port == -1)
  368. port = 389;
  369. InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(rootDN);
  370. config.addAdditionalBindCredentials(bindUserName, bindPassword);
  371. config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", port));
  372. config.setSchema(null);
  373. InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
  374. ds.importFromLDIF(true, new LDIFReader(ldifFile));
  375. ds.startListening();
  376. logger.info("LDAP Server started at ldap://localhost:" + port);
  377. }
  378. }
  379. } catch (Exception e) {
  380. // Completely optional, just show a warning
  381. logger.warn("Unable to start LDAP server", e);
  382. }
  383. // Set the server's contexts
  384. server.setHandler(rootContext);
  385. // redirect HTTP requests to HTTPS
  386. if (params.port > 0 && params.securePort > 0 && settings.getBoolean(Keys.server.redirectToHttpsPort, true)) {
  387. logger.info(String.format("Configuring automatic http(%1$s) -> https(%2$s) redirects", params.port, params.securePort));
  388. // Create the internal mechanisms to handle secure connections and redirects
  389. Constraint constraint = new Constraint();
  390. constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);
  391. ConstraintMapping cm = new ConstraintMapping();
  392. cm.setConstraint(constraint);
  393. cm.setPathSpec("/*");
  394. ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
  395. sh.setConstraintMappings(new ConstraintMapping[] { cm });
  396. // Configure this context to use the Security Handler defined before
  397. rootContext.setHandler(sh);
  398. }
  399. // Setup the Gitblit context
  400. GitblitContext gitblit = newGitblit(settings, baseFolder);
  401. rootContext.addEventListener(gitblit);
  402. try {
  403. // start the shutdown monitor
  404. if (params.shutdownPort > 0) {
  405. Thread shutdownMonitor = new ShutdownMonitorThread(server, params);
  406. shutdownMonitor.start();
  407. }
  408. // start Jetty
  409. server.start();
  410. server.join();
  411. } catch (Exception e) {
  412. e.printStackTrace();
  413. System.exit(100);
  414. }
  415. }
  416. protected GitblitContext newGitblit(IStoredSettings settings, File baseFolder) {
  417. return new GitblitContext(settings, baseFolder);
  418. }
  419. /**
  420. * Creates an http connector.
  421. *
  422. * @param useNIO
  423. * @param port
  424. * @param threadPoolSize
  425. * @return an http connector
  426. */
  427. private Connector createConnector(boolean useNIO, int port, int threadPoolSize) {
  428. Connector connector;
  429. if (useNIO) {
  430. logger.info("Setting up NIO SelectChannelConnector on port " + port);
  431. SelectChannelConnector nioconn = new SelectChannelConnector();
  432. nioconn.setSoLingerTime(-1);
  433. if (threadPoolSize > 0) {
  434. nioconn.setThreadPool(new QueuedThreadPool(threadPoolSize));
  435. }
  436. connector = nioconn;
  437. } else {
  438. logger.info("Setting up SocketConnector on port " + port);
  439. SocketConnector sockconn = new SocketConnector();
  440. if (threadPoolSize > 0) {
  441. sockconn.setThreadPool(new QueuedThreadPool(threadPoolSize));
  442. }
  443. connector = sockconn;
  444. }
  445. connector.setPort(port);
  446. connector.setMaxIdleTime(30000);
  447. return connector;
  448. }
  449. /**
  450. * Creates an https connector.
  451. *
  452. * SSL renegotiation will be enabled if the JVM is 1.6.0_22 or later.
  453. * oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html
  454. *
  455. * @param certAlias
  456. * @param keyStore
  457. * @param clientTrustStore
  458. * @param storePassword
  459. * @param caRevocationList
  460. * @param useNIO
  461. * @param port
  462. * @param threadPoolSize
  463. * @param requireClientCertificates
  464. * @return an https connector
  465. */
  466. private Connector createSSLConnector(String certAlias, File keyStore, File clientTrustStore,
  467. String storePassword, File caRevocationList, boolean useNIO, int port, int threadPoolSize,
  468. boolean requireClientCertificates) {
  469. GitblitSslContextFactory factory = new GitblitSslContextFactory(certAlias,
  470. keyStore, clientTrustStore, storePassword, caRevocationList);
  471. SslConnector connector;
  472. if (useNIO) {
  473. logger.info("Setting up NIO SslSelectChannelConnector on port " + port);
  474. SslSelectChannelConnector ssl = new SslSelectChannelConnector(factory);
  475. ssl.setSoLingerTime(-1);
  476. if (requireClientCertificates) {
  477. factory.setNeedClientAuth(true);
  478. } else {
  479. factory.setWantClientAuth(true);
  480. }
  481. if (threadPoolSize > 0) {
  482. ssl.setThreadPool(new QueuedThreadPool(threadPoolSize));
  483. }
  484. connector = ssl;
  485. } else {
  486. logger.info("Setting up NIO SslSocketConnector on port " + port);
  487. SslSocketConnector ssl = new SslSocketConnector(factory);
  488. if (threadPoolSize > 0) {
  489. ssl.setThreadPool(new QueuedThreadPool(threadPoolSize));
  490. }
  491. connector = ssl;
  492. }
  493. connector.setPort(port);
  494. connector.setMaxIdleTime(30000);
  495. return connector;
  496. }
  497. /**
  498. * Creates an ajp connector.
  499. *
  500. * @param port
  501. * @return an ajp connector
  502. */
  503. private Connector createAJPConnector(int port) {
  504. logger.info("Setting up AJP Connector on port " + port);
  505. Ajp13SocketConnector ajp = new Ajp13SocketConnector();
  506. ajp.setPort(port);
  507. if (port < 1024 && !isWindows()) {
  508. logger.warn("Gitblit needs to run with ROOT permissions for ports < 1024!");
  509. }
  510. return ajp;
  511. }
  512. /**
  513. * Tests to see if the operating system is Windows.
  514. *
  515. * @return true if this is a windows machine
  516. */
  517. private boolean isWindows() {
  518. return System.getProperty("os.name").toLowerCase().indexOf("windows") > -1;
  519. }
  520. /**
  521. * The ShutdownMonitorThread opens a socket on a specified port and waits
  522. * for an incoming connection. When that connection is accepted a shutdown
  523. * message is issued to the running Jetty server.
  524. *
  525. * @author James Moger
  526. *
  527. */
  528. private static class ShutdownMonitorThread extends Thread {
  529. private final ServerSocket socket;
  530. private final Server server;
  531. private final Logger logger = LoggerFactory.getLogger(ShutdownMonitorThread.class);
  532. public ShutdownMonitorThread(Server server, Params params) {
  533. this.server = server;
  534. setDaemon(true);
  535. setName(Constants.NAME + " Shutdown Monitor");
  536. ServerSocket skt = null;
  537. try {
  538. skt = new ServerSocket(params.shutdownPort, 1, InetAddress.getByName("127.0.0.1"));
  539. } catch (Exception e) {
  540. logger.warn("Could not open shutdown monitor on port " + params.shutdownPort, e);
  541. }
  542. socket = skt;
  543. }
  544. @Override
  545. public void run() {
  546. logger.info("Shutdown Monitor listening on port " + socket.getLocalPort());
  547. Socket accept;
  548. try {
  549. accept = socket.accept();
  550. BufferedReader reader = new BufferedReader(new InputStreamReader(
  551. accept.getInputStream()));
  552. reader.readLine();
  553. logger.info(Constants.BORDER);
  554. logger.info("Stopping " + Constants.NAME);
  555. logger.info(Constants.BORDER);
  556. server.stop();
  557. server.setStopAtShutdown(false);
  558. accept.close();
  559. socket.close();
  560. } catch (Exception e) {
  561. logger.warn("Failed to shutdown Jetty", e);
  562. }
  563. }
  564. }
  565. /**
  566. * Parameters class for GitBlitServer.
  567. */
  568. public static class Params {
  569. public static String baseFolder;
  570. private final FileSettings FILESETTINGS = new FileSettings(new File(baseFolder, Constants.PROPERTIES_FILE).getAbsolutePath());
  571. /*
  572. * Server parameters
  573. */
  574. @Option(name = "--help", aliases = { "-h"}, usage = "Show this help")
  575. public Boolean help = false;
  576. @Option(name = "--stop", usage = "Stop Server")
  577. public Boolean stop = false;
  578. @Option(name = "--tempFolder", usage = "Folder for server to extract built-in webapp", metaVar="PATH")
  579. public String temp = FILESETTINGS.getString(Keys.server.tempFolder, "temp");
  580. @Option(name = "--dailyLogFile", usage = "Log to a rolling daily log file INSTEAD of stdout.")
  581. public Boolean dailyLogFile = false;
  582. /*
  583. * GIT Servlet Parameters
  584. */
  585. @Option(name = "--repositoriesFolder", usage = "Git Repositories Folder", metaVar="PATH")
  586. public String repositoriesFolder = FILESETTINGS.getString(Keys.git.repositoriesFolder,
  587. "git");
  588. /*
  589. * Authentication Parameters
  590. */
  591. @Option(name = "--userService", usage = "Authentication and Authorization Service (filename or fully qualified classname)")
  592. public String userService = FILESETTINGS.getString(Keys.realm.userService,
  593. "users.conf");
  594. /*
  595. * JETTY Parameters
  596. */
  597. @Option(name = "--useNio", usage = "Use NIO Connector else use Socket Connector.")
  598. public Boolean useNIO = FILESETTINGS.getBoolean(Keys.server.useNio, true);
  599. @Option(name = "--httpPort", usage = "HTTP port for to serve. (port <= 0 will disable this connector)", metaVar="PORT")
  600. public Integer port = FILESETTINGS.getInteger(Keys.server.httpPort, 0);
  601. @Option(name = "--httpsPort", usage = "HTTPS port to serve. (port <= 0 will disable this connector)", metaVar="PORT")
  602. public Integer securePort = FILESETTINGS.getInteger(Keys.server.httpsPort, 8443);
  603. @Option(name = "--ajpPort", usage = "AJP port to serve. (port <= 0 will disable this connector)", metaVar="PORT")
  604. public Integer ajpPort = FILESETTINGS.getInteger(Keys.server.ajpPort, 0);
  605. @Option(name = "--gitPort", usage = "Git Daemon port to serve. (port <= 0 will disable this connector)", metaVar="PORT")
  606. public Integer gitPort = FILESETTINGS.getInteger(Keys.git.daemonPort, 9418);
  607. @Option(name = "--alias", usage = "Alias of SSL certificate in keystore for serving https.", metaVar="ALIAS")
  608. public String alias = FILESETTINGS.getString(Keys.server.certificateAlias, "");
  609. @Option(name = "--storePassword", usage = "Password for SSL (https) keystore.", metaVar="PASSWORD")
  610. public String storePassword = FILESETTINGS.getString(Keys.server.storePassword, "");
  611. @Option(name = "--shutdownPort", usage = "Port for Shutdown Monitor to listen on. (port <= 0 will disable this monitor)", metaVar="PORT")
  612. public Integer shutdownPort = FILESETTINGS.getInteger(Keys.server.shutdownPort, 8081);
  613. @Option(name = "--requireClientCertificates", usage = "Require client X509 certificates for https connections.")
  614. public Boolean requireClientCertificates = FILESETTINGS.getBoolean(Keys.server.requireClientCertificates, false);
  615. /*
  616. * Setting overrides
  617. */
  618. @Option(name = "--settings", usage = "Path to alternative settings", metaVar="FILE")
  619. public String settingsfile;
  620. @Option(name = "--ldapLdifFile", usage = "Path to LDIF file. This will cause an in-memory LDAP server to be started according to gitblit settings", metaVar="FILE")
  621. public String ldapLdifFile;
  622. }
  623. }