PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/tomcat-7.0.2/java/org/apache/tomcat/util/net/AbstractEndpoint.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 587 lines | 372 code | 83 blank | 132 comment | 51 complexity | 8854125cd8dfa7a3f8b94f81fb7741e5 MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package org.apache.tomcat.util.net;
  18. import java.io.File;
  19. import java.net.InetAddress;
  20. import java.net.InetSocketAddress;
  21. import java.util.StringTokenizer;
  22. import java.util.concurrent.Executor;
  23. import java.util.concurrent.TimeUnit;
  24. import javax.net.ssl.KeyManagerFactory;
  25. import org.apache.juli.logging.Log;
  26. import org.apache.juli.logging.LogFactory;
  27. import org.apache.tomcat.util.IntrospectionUtils;
  28. import org.apache.tomcat.util.net.jsse.JSSESocketFactory;
  29. import org.apache.tomcat.util.res.StringManager;
  30. import org.apache.tomcat.util.threads.ResizableExecutor;
  31. import org.apache.tomcat.util.threads.TaskQueue;
  32. import org.apache.tomcat.util.threads.TaskThreadFactory;
  33. import org.apache.tomcat.util.threads.ThreadPoolExecutor;
  34. /**
  35. *
  36. * @author fhanik
  37. * @author Mladen Turk
  38. * @author Remy Maucherat
  39. */
  40. public abstract class AbstractEndpoint {
  41. private static final Log log = LogFactory.getLog(AbstractEndpoint.class);
  42. // -------------------------------------------------------------- Constants
  43. protected static final StringManager sm = StringManager.getManager("org.apache.tomcat.util.net.res");
  44. /**
  45. * The Request attribute key for the cipher suite.
  46. */
  47. public static final String CIPHER_SUITE_KEY = "javax.servlet.request.cipher_suite";
  48. /**
  49. * The Request attribute key for the key size.
  50. */
  51. public static final String KEY_SIZE_KEY = "javax.servlet.request.key_size";
  52. /**
  53. * The Request attribute key for the client certificate chain.
  54. */
  55. public static final String CERTIFICATE_KEY = "javax.servlet.request.X509Certificate";
  56. /**
  57. * The Request attribute key for the session id.
  58. * This one is a Tomcat extension to the Servlet spec.
  59. */
  60. public static final String SESSION_ID_KEY = "javax.servlet.request.ssl_session";
  61. /**
  62. * The request attribute key for the session manager.
  63. * This one is a Tomcat extension to the Servlet spec.
  64. */
  65. public static final String SESSION_MGR = "javax.servlet.request.ssl_session_mgr";
  66. /**
  67. * Different types of socket states to react upon
  68. */
  69. public static interface Handler {
  70. public enum SocketState {
  71. OPEN, CLOSED, LONG
  72. }
  73. }
  74. // Standard SSL Configuration attributes
  75. // JSSE
  76. // Standard configuration attribute names
  77. public static final String SSL_ATTR_ALGORITHM = "algorithm";
  78. public static final String SSL_ATTR_CLIENT_AUTH = "clientAuth";
  79. public static final String SSL_ATTR_KEYSTORE_FILE = "keystoreFile";
  80. public static final String SSL_ATTR_KEYSTORE_PASS = "keystorePass";
  81. public static final String SSL_ATTR_KEYSTORE_TYPE = "keystoreType";
  82. public static final String SSL_ATTR_KEYSTORE_PROVIDER = "keystoreProvider";
  83. public static final String SSL_ATTR_SSL_PROTOCOL = "sslProtocol";
  84. public static final String SSL_ATTR_CIPHERS = "ciphers";
  85. public static final String SSL_ATTR_CIPHERS_ARRAY = "ciphersArray";
  86. public static final String SSL_ATTR_KEY_ALIAS = "keyAlias";
  87. public static final String SSL_ATTR_KEY_PASS = "keyPass";
  88. public static final String SSL_ATTR_TRUSTSTORE_FILE = "truststoreFile";
  89. public static final String SSL_ATTR_TRUSTSTORE_PASS = "truststorePass";
  90. public static final String SSL_ATTR_TRUSTSTORE_TYPE = "truststoreType";
  91. public static final String SSL_ATTR_TRUSTSTORE_PROVIDER =
  92. "truststoreProvider";
  93. public static final String SSL_ATTR_TRUSTSTORE_ALGORITHM =
  94. "truststoreAlgorithm";
  95. public static final String SSL_ATTR_CRL_FILE =
  96. "crlFile";
  97. public static final String SSL_ATTR_TRUST_MAX_CERT_LENGTH =
  98. "trustMaxCertLength";
  99. public static final String SSL_ATTR_SESSION_CACHE_SIZE =
  100. "sessionCacheSize";
  101. public static final String SSL_ATTR_SESSION_TIMEOUT =
  102. "sessionTimeout";
  103. public static final String SSL_ATTR_ALLOW_UNSAFE_RENEG =
  104. "allowUnsafeLegacyRenegotiation";
  105. // ----------------------------------------------------------------- Fields
  106. /**
  107. * Running state of the endpoint.
  108. */
  109. protected volatile boolean running = false;
  110. /**
  111. * Will be set to true whenever the endpoint is paused.
  112. */
  113. protected volatile boolean paused = false;
  114. /**
  115. * Track the initialization state of the endpoint.
  116. */
  117. protected boolean initialized = false;
  118. /**
  119. * Are we using an internal executor
  120. */
  121. protected volatile boolean internalExecutor = false;
  122. /**
  123. * Socket properties
  124. */
  125. protected SocketProperties socketProperties = new SocketProperties();
  126. public SocketProperties getSocketProperties() {
  127. return socketProperties;
  128. }
  129. // ----------------------------------------------------------------- Properties
  130. private int maxConnections = 10000;
  131. public void setMaxConnections(int maxCon) { this.maxConnections = maxCon; }
  132. public int getMaxConnections() { return this.maxConnections; }
  133. /**
  134. * External Executor based thread pool.
  135. */
  136. private Executor executor = null;
  137. public void setExecutor(Executor executor) {
  138. this.executor = executor;
  139. this.internalExecutor = (executor==null);
  140. }
  141. public Executor getExecutor() { return executor; }
  142. /**
  143. * Server socket port.
  144. */
  145. private int port;
  146. public int getPort() { return port; }
  147. public void setPort(int port ) { this.port=port; }
  148. /**
  149. * Address for the server socket.
  150. */
  151. private InetAddress address;
  152. public InetAddress getAddress() { return address; }
  153. public void setAddress(InetAddress address) { this.address = address; }
  154. /**
  155. * Allows the server developer to specify the backlog that
  156. * should be used for server sockets. By default, this value
  157. * is 100.
  158. */
  159. private int backlog = 100;
  160. public void setBacklog(int backlog) { if (backlog > 0) this.backlog = backlog; }
  161. public int getBacklog() { return backlog; }
  162. /**
  163. * Keepalive timeout, if lesser or equal to 0 then soTimeout will be used.
  164. */
  165. private int keepAliveTimeout = 0;
  166. public void setKeepAliveTimeout(int keepAliveTimeout) { this.keepAliveTimeout = keepAliveTimeout; }
  167. public int getKeepAliveTimeout() { return keepAliveTimeout;}
  168. /**
  169. * Socket TCP no delay.
  170. */
  171. public boolean getTcpNoDelay() { return socketProperties.getTcpNoDelay();}
  172. public void setTcpNoDelay(boolean tcpNoDelay) { socketProperties.setTcpNoDelay(tcpNoDelay); }
  173. /**
  174. * Socket linger.
  175. */
  176. public int getSoLinger() { return socketProperties.getSoLingerTime(); }
  177. public void setSoLinger(int soLinger) {
  178. socketProperties.setSoLingerTime(soLinger);
  179. socketProperties.setSoLingerOn(soLinger>=0);
  180. }
  181. /**
  182. * Socket timeout.
  183. */
  184. public int getSoTimeout() { return socketProperties.getSoTimeout(); }
  185. public void setSoTimeout(int soTimeout) { socketProperties.setSoTimeout(soTimeout); }
  186. /**
  187. * SSL engine.
  188. */
  189. private boolean SSLEnabled = false;
  190. public boolean isSSLEnabled() { return SSLEnabled; }
  191. public void setSSLEnabled(boolean SSLEnabled) { this.SSLEnabled = SSLEnabled; }
  192. private int minSpareThreads = 10;
  193. public int getMinSpareThreads() {
  194. return Math.min(minSpareThreads,getMaxThreads());
  195. }
  196. public void setMinSpareThreads(int minSpareThreads) {
  197. this.minSpareThreads = minSpareThreads;
  198. if (running && executor!=null) {
  199. if (executor instanceof java.util.concurrent.ThreadPoolExecutor) {
  200. ((java.util.concurrent.ThreadPoolExecutor)executor).setCorePoolSize(maxThreads);
  201. } else if (executor instanceof ResizableExecutor) {
  202. ((ResizableExecutor)executor).resizePool(minSpareThreads, maxThreads);
  203. }
  204. }
  205. }
  206. /**
  207. * Maximum amount of worker threads.
  208. */
  209. private int maxThreads = 200;
  210. public void setMaxThreads(int maxThreads) {
  211. this.maxThreads = maxThreads;
  212. if (running && executor!=null) {
  213. if (executor instanceof java.util.concurrent.ThreadPoolExecutor) {
  214. ((java.util.concurrent.ThreadPoolExecutor)executor).setMaximumPoolSize(maxThreads);
  215. } else if (executor instanceof ResizableExecutor) {
  216. ((ResizableExecutor)executor).resizePool(minSpareThreads, maxThreads);
  217. }
  218. }
  219. }
  220. public int getMaxThreads() {
  221. if (running && executor!=null) {
  222. if (executor instanceof java.util.concurrent.ThreadPoolExecutor) {
  223. return ((java.util.concurrent.ThreadPoolExecutor)executor).getMaximumPoolSize();
  224. } else if (executor instanceof ResizableExecutor) {
  225. return ((ResizableExecutor)executor).getMaxThreads();
  226. } else {
  227. return -1;
  228. }
  229. } else {
  230. return maxThreads;
  231. }
  232. }
  233. /**
  234. * Max keep alive requests
  235. */
  236. private int maxKeepAliveRequests=100; // as in Apache HTTPD server
  237. public int getMaxKeepAliveRequests() {
  238. return maxKeepAliveRequests;
  239. }
  240. public void setMaxKeepAliveRequests(int maxKeepAliveRequests) {
  241. this.maxKeepAliveRequests = maxKeepAliveRequests;
  242. }
  243. /**
  244. * Name of the thread pool, which will be used for naming child threads.
  245. */
  246. private String name = "TP";
  247. public void setName(String name) { this.name = name; }
  248. public String getName() { return name; }
  249. /**
  250. * The default is true - the created threads will be
  251. * in daemon mode. If set to false, the control thread
  252. * will not be daemon - and will keep the process alive.
  253. */
  254. private boolean daemon = true;
  255. public void setDaemon(boolean b) { daemon = b; }
  256. public boolean getDaemon() { return daemon; }
  257. /**
  258. * Priority of the worker threads.
  259. */
  260. protected int threadPriority = Thread.NORM_PRIORITY;
  261. public void setThreadPriority(int threadPriority) { this.threadPriority = threadPriority; }
  262. public int getThreadPriority() { return threadPriority; }
  263. /**
  264. * Generic properties, introspected
  265. */
  266. public boolean setProperty(String name, String value) {
  267. final String socketName = "socket.";
  268. try {
  269. if (name.startsWith(socketName)) {
  270. return IntrospectionUtils.setProperty(socketProperties, name.substring(socketName.length()), value);
  271. } else {
  272. return IntrospectionUtils.setProperty(this,name,value,false);
  273. }
  274. }catch ( Exception x ) {
  275. log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x);
  276. return false;
  277. }
  278. }
  279. /**
  280. * Return the amount of threads that are managed by the pool.
  281. *
  282. * @return the amount of threads that are managed by the pool
  283. */
  284. public int getCurrentThreadCount() {
  285. if (executor!=null) {
  286. if (executor instanceof ThreadPoolExecutor) {
  287. return ((ThreadPoolExecutor)executor).getPoolSize();
  288. } else if (executor instanceof ResizableExecutor) {
  289. return ((ResizableExecutor)executor).getPoolSize();
  290. } else {
  291. return -1;
  292. }
  293. } else {
  294. return -2;
  295. }
  296. }
  297. /**
  298. * Return the amount of threads that are in use
  299. *
  300. * @return the amount of threads that are in use
  301. */
  302. public int getCurrentThreadsBusy() {
  303. if (executor!=null) {
  304. if (executor instanceof ThreadPoolExecutor) {
  305. return ((ThreadPoolExecutor)executor).getActiveCount();
  306. } else if (executor instanceof ResizableExecutor) {
  307. return ((ResizableExecutor)executor).getActiveCount();
  308. } else {
  309. return -1;
  310. }
  311. } else {
  312. return -2;
  313. }
  314. }
  315. public boolean isRunning() {
  316. return running;
  317. }
  318. public boolean isPaused() {
  319. return paused;
  320. }
  321. public void createExecutor() {
  322. internalExecutor = true;
  323. TaskQueue taskqueue = new TaskQueue();
  324. TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority());
  325. executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf);
  326. taskqueue.setParent( (ThreadPoolExecutor) executor);
  327. }
  328. public void shutdownExecutor() {
  329. if ( executor!=null && internalExecutor ) {
  330. if ( executor instanceof ThreadPoolExecutor ) {
  331. //this is our internal one, so we need to shut it down
  332. ThreadPoolExecutor tpe = (ThreadPoolExecutor) executor;
  333. tpe.shutdownNow();
  334. TaskQueue queue = (TaskQueue) tpe.getQueue();
  335. queue.setParent(null);
  336. }
  337. executor = null;
  338. }
  339. }
  340. /**
  341. * Unlock the server socket accept using a bogus connection.
  342. */
  343. protected void unlockAccept() {
  344. java.net.Socket s = null;
  345. InetSocketAddress saddr = null;
  346. try {
  347. // Need to create a connection to unlock the accept();
  348. if (address == null) {
  349. saddr = new InetSocketAddress("localhost", getPort());
  350. } else {
  351. saddr = new InetSocketAddress(address,getPort());
  352. }
  353. s = new java.net.Socket();
  354. s.setSoTimeout(getSocketProperties().getSoTimeout());
  355. // TODO Consider hard-coding to s.setSoLinger(true,0)
  356. s.setSoLinger(getSocketProperties().getSoLingerOn(),getSocketProperties().getSoLingerTime());
  357. if (log.isDebugEnabled()) {
  358. log.debug("About to unlock socket for:"+saddr);
  359. }
  360. s.connect(saddr,getSocketProperties().getUnlockTimeout());
  361. if (log.isDebugEnabled()) {
  362. log.debug("Socket unlock completed for:"+saddr);
  363. }
  364. } catch(Exception e) {
  365. if (log.isDebugEnabled()) {
  366. log.debug(sm.getString("endpoint.debug.unlock", "" + getPort()), e);
  367. }
  368. } finally {
  369. if (s != null) {
  370. try {
  371. s.close();
  372. } catch (Exception e) {
  373. // Ignore
  374. }
  375. }
  376. }
  377. }
  378. public abstract void pause();
  379. public abstract void resume();
  380. public abstract void start() throws Exception;
  381. public abstract void destroy() throws Exception;
  382. public abstract void init() throws Exception;
  383. public String adjustRelativePath(String path, String relativeTo) {
  384. File f = new File(path);
  385. if ( !f.isAbsolute()) {
  386. path = relativeTo + File.separator + path;
  387. f = new File(path);
  388. }
  389. if (!f.exists()) {
  390. log.warn("configured file:["+path+"] does not exist.");
  391. }
  392. return path;
  393. }
  394. public String defaultIfNull(String val, String defaultValue) {
  395. if (val==null) return defaultValue;
  396. return val;
  397. }
  398. // -------------------- SSL related properties --------------------
  399. private String algorithm = KeyManagerFactory.getDefaultAlgorithm();
  400. public String getAlgorithm() { return algorithm;}
  401. public void setAlgorithm(String s ) { this.algorithm = s;}
  402. private String clientAuth = "false";
  403. public String getClientAuth() { return clientAuth;}
  404. public void setClientAuth(String s ) { this.clientAuth = s;}
  405. private String keystoreFile = System.getProperty("user.home")+"/.keystore";
  406. public String getKeystoreFile() { return keystoreFile;}
  407. public void setKeystoreFile(String s ) {
  408. String file = adjustRelativePath(s,System.getProperty("catalina.base"));
  409. this.keystoreFile = file;
  410. }
  411. private String keystorePass = null;
  412. public String getKeystorePass() { return keystorePass;}
  413. public void setKeystorePass(String s ) { this.keystorePass = s;}
  414. private String keystoreType = "JKS";
  415. public String getKeystoreType() { return keystoreType;}
  416. public void setKeystoreType(String s ) { this.keystoreType = s;}
  417. private String keystoreProvider = null;
  418. public String getKeystoreProvider() { return keystoreProvider;}
  419. public void setKeystoreProvider(String s ) { this.keystoreProvider = s;}
  420. private String sslProtocol = "TLS";
  421. public String getSslProtocol() { return sslProtocol;}
  422. public void setSslProtocol(String s) { sslProtocol = s;}
  423. // Note: Some implementations use the comma separated string, some use
  424. // the array
  425. private String ciphers = null;
  426. private String[] ciphersarr = new String[0];
  427. public String[] getCiphersArray() { return this.ciphersarr;}
  428. public String getCiphers() { return ciphers;}
  429. public void setCiphers(String s) {
  430. ciphers = s;
  431. if ( s == null ) ciphersarr = new String[0];
  432. else {
  433. StringTokenizer t = new StringTokenizer(s,",");
  434. ciphersarr = new String[t.countTokens()];
  435. for (int i=0; i<ciphersarr.length; i++ ) ciphersarr[i] = t.nextToken();
  436. }
  437. }
  438. private String keyAlias = null;
  439. public String getKeyAlias() { return keyAlias;}
  440. public void setKeyAlias(String s ) { keyAlias = s;}
  441. private String keyPass = JSSESocketFactory.DEFAULT_KEY_PASS;
  442. public String getKeyPass() { return keyPass;}
  443. public void setKeyPass(String s ) { this.keyPass = s;}
  444. private String truststoreFile = System.getProperty("javax.net.ssl.trustStore");
  445. public String getTruststoreFile() {return truststoreFile;}
  446. public void setTruststoreFile(String s) {
  447. String file = adjustRelativePath(s,System.getProperty("catalina.base"));
  448. this.truststoreFile = file;
  449. }
  450. private String truststorePass =
  451. System.getProperty("javax.net.ssl.trustStorePassword");
  452. public String getTruststorePass() {return truststorePass;}
  453. public void setTruststorePass(String truststorePass) {
  454. this.truststorePass = truststorePass;
  455. }
  456. private String truststoreType =
  457. System.getProperty("javax.net.ssl.trustStoreType");
  458. public String getTruststoreType() {return truststoreType;}
  459. public void setTruststoreType(String truststoreType) {
  460. this.truststoreType = truststoreType;
  461. }
  462. private String truststoreProvider = null;
  463. public String getTruststoreProvider() {return truststoreProvider;}
  464. public void setTruststoreProvider(String truststoreProvider) {
  465. this.truststoreProvider = truststoreProvider;
  466. }
  467. private String truststoreAlgorithm = null;
  468. public String getTruststoreAlgorithm() {return truststoreAlgorithm;}
  469. public void setTruststoreAlgorithm(String truststoreAlgorithm) {
  470. this.truststoreAlgorithm = truststoreAlgorithm;
  471. }
  472. private String crlFile = null;
  473. public String getCrlFile() {return crlFile;}
  474. public void setCrlFile(String crlFile) {
  475. this.crlFile = crlFile;
  476. }
  477. private String trustMaxCertLength = null;
  478. public String getTrustMaxCertLength() {return trustMaxCertLength;}
  479. public void setTrustMaxCertLength(String trustMaxCertLength) {
  480. this.trustMaxCertLength = trustMaxCertLength;
  481. }
  482. private String sessionCacheSize = null;
  483. public String getSessionCacheSize() { return sessionCacheSize;}
  484. public void setSessionCacheSize(String s) { sessionCacheSize = s;}
  485. private String sessionTimeout = "86400";
  486. public String getSessionTimeout() { return sessionTimeout;}
  487. public void setSessionTimeout(String s) { sessionTimeout = s;}
  488. private String allowUnsafeLegacyRenegotiation = null;
  489. public String getAllowUnsafeLegacyRenegotiation() {
  490. return allowUnsafeLegacyRenegotiation;
  491. }
  492. public void setAllowUnsafeLegacyRenegotiation(String s) {
  493. allowUnsafeLegacyRenegotiation = s;
  494. }
  495. private String sslEnabledProtocols=null; //"TLSv1,SSLv3,SSLv2Hello"
  496. private String[] sslEnabledProtocolsarr = new String[0];
  497. public String[] getSslEnabledProtocolsArray() { return this.sslEnabledProtocolsarr;}
  498. public void setSslEnabledProtocols(String s) {
  499. this.sslEnabledProtocols = s;
  500. StringTokenizer t = new StringTokenizer(s,",");
  501. sslEnabledProtocolsarr = new String[t.countTokens()];
  502. for (int i=0; i<sslEnabledProtocolsarr.length; i++ ) sslEnabledProtocolsarr[i] = t.nextToken();
  503. }
  504. }