PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/tomcat-7.0.2/java/org/apache/coyote/http11/Http11NioProcessor.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 1258 lines | 838 code | 185 blank | 235 comment | 349 complexity | 537f5242d7a013020ab601c19203e11f 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.coyote.http11;
  18. import java.io.IOException;
  19. import java.io.InterruptedIOException;
  20. import java.net.InetAddress;
  21. import java.nio.channels.SelectionKey;
  22. import java.util.Locale;
  23. import java.util.concurrent.atomic.AtomicBoolean;
  24. import org.apache.coyote.ActionCode;
  25. import org.apache.coyote.ActionHook;
  26. import org.apache.coyote.Request;
  27. import org.apache.coyote.RequestInfo;
  28. import org.apache.coyote.Response;
  29. import org.apache.coyote.http11.filters.BufferedInputFilter;
  30. import org.apache.coyote.http11.filters.SavedRequestInputFilter;
  31. import org.apache.juli.logging.Log;
  32. import org.apache.juli.logging.LogFactory;
  33. import org.apache.tomcat.util.buf.Ascii;
  34. import org.apache.tomcat.util.buf.ByteChunk;
  35. import org.apache.tomcat.util.buf.HexUtils;
  36. import org.apache.tomcat.util.buf.MessageBytes;
  37. import org.apache.tomcat.util.http.FastHttpDateFormat;
  38. import org.apache.tomcat.util.http.MimeHeaders;
  39. import org.apache.tomcat.util.net.NioChannel;
  40. import org.apache.tomcat.util.net.NioEndpoint;
  41. import org.apache.tomcat.util.net.SSLSupport;
  42. import org.apache.tomcat.util.net.SocketStatus;
  43. import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
  44. import org.apache.tomcat.util.net.NioEndpoint.KeyAttachment;
  45. /**
  46. * Processes HTTP requests.
  47. *
  48. * @author Remy Maucherat
  49. * @author Filip Hanik
  50. */
  51. public class Http11NioProcessor extends AbstractHttp11Processor implements ActionHook {
  52. /**
  53. * Logger.
  54. */
  55. private static final Log log = LogFactory.getLog(Http11NioProcessor.class);
  56. /**
  57. * SSL information.
  58. */
  59. protected SSLSupport sslSupport;
  60. // ----------------------------------------------------------- Constructors
  61. public Http11NioProcessor(int maxHttpHeaderSize, NioEndpoint endpoint) {
  62. this.endpoint = endpoint;
  63. request = new Request();
  64. inputBuffer = new InternalNioInputBuffer(request, maxHttpHeaderSize);
  65. request.setInputBuffer(inputBuffer);
  66. response = new Response();
  67. response.setHook(this);
  68. outputBuffer = new InternalNioOutputBuffer(response, maxHttpHeaderSize);
  69. response.setOutputBuffer(outputBuffer);
  70. request.setResponse(response);
  71. ssl = endpoint.isSSLEnabled();
  72. initializeFilters();
  73. // Cause loading of HexUtils
  74. HexUtils.load();
  75. }
  76. // ----------------------------------------------------- Instance Variables
  77. /**
  78. * Input.
  79. */
  80. protected InternalNioInputBuffer inputBuffer = null;
  81. /**
  82. * Output.
  83. */
  84. protected InternalNioOutputBuffer outputBuffer = null;
  85. /**
  86. * Sendfile data.
  87. */
  88. protected NioEndpoint.SendfileData sendfileData = null;
  89. /**
  90. * Comet used.
  91. */
  92. protected boolean comet = false;
  93. /**
  94. * Closed flag, a Comet async thread can
  95. * signal for this Nio processor to be closed and recycled instead
  96. * of waiting for a timeout.
  97. * Closed by HttpServletResponse.getWriter().close()
  98. */
  99. protected boolean cometClose = false;
  100. /**
  101. * Async used
  102. */
  103. protected boolean async = false;
  104. /**
  105. * SSL enabled ?
  106. */
  107. protected boolean ssl = false;
  108. /**
  109. * Socket associated with the current connection.
  110. */
  111. protected NioChannel socket = null;
  112. /**
  113. * Associated endpoint.
  114. */
  115. protected NioEndpoint endpoint;
  116. // ------------------------------------------------------------- Properties
  117. // --------------------------------------------------------- Public Methods
  118. /**
  119. * Process pipelined HTTP requests using the specified input and output
  120. * streams.
  121. *
  122. * @throws IOException error during an I/O operation
  123. */
  124. public SocketState event(SocketStatus status)
  125. throws IOException {
  126. long soTimeout = endpoint.getSoTimeout();
  127. int keepAliveTimeout = endpoint.getKeepAliveTimeout();
  128. RequestInfo rp = request.getRequestProcessor();
  129. final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
  130. try {
  131. rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
  132. error = !adapter.event(request, response, status);
  133. if ( !error ) {
  134. if (attach != null) {
  135. attach.setComet(comet);
  136. if (comet) {
  137. Integer comettimeout = (Integer) request.getAttribute("org.apache.tomcat.comet.timeout");
  138. if (comettimeout != null) attach.setTimeout(comettimeout.longValue());
  139. } else {
  140. //reset the timeout
  141. if (keepAlive && keepAliveTimeout>0) {
  142. attach.setTimeout(keepAliveTimeout);
  143. } else {
  144. attach.setTimeout(soTimeout);
  145. }
  146. }
  147. }
  148. }
  149. } catch (InterruptedIOException e) {
  150. error = true;
  151. } catch (Throwable t) {
  152. log.error(sm.getString("http11processor.request.process"), t);
  153. // 500 - Internal Server Error
  154. response.setStatus(500);
  155. adapter.log(request, response, 0);
  156. error = true;
  157. }
  158. rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
  159. if (error) {
  160. recycle();
  161. return SocketState.CLOSED;
  162. } else if (!comet) {
  163. recycle();
  164. return (keepAlive)?SocketState.OPEN:SocketState.CLOSED;
  165. } else {
  166. return SocketState.LONG;
  167. }
  168. }
  169. /**
  170. * Process pipelined HTTP requests using the specified input and output
  171. * streams.
  172. *
  173. * @throws IOException error during an I/O operation
  174. */
  175. public SocketState asyncDispatch(SocketStatus status)
  176. throws IOException {
  177. long soTimeout = endpoint.getSoTimeout();
  178. int keepAliveTimeout = endpoint.getKeepAliveTimeout();
  179. RequestInfo rp = request.getRequestProcessor();
  180. final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
  181. try {
  182. rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
  183. error = !adapter.asyncDispatch(request, response, status);
  184. if ( !error ) {
  185. if (attach != null) {
  186. attach.setComet(comet);
  187. if (comet) {
  188. Integer comettimeout = (Integer) request.getAttribute("org.apache.tomcat.comet.timeout");
  189. if (comettimeout != null) attach.setTimeout(comettimeout.longValue());
  190. } else {
  191. //reset the timeout
  192. if (keepAlive && keepAliveTimeout>0) {
  193. attach.setTimeout(keepAliveTimeout);
  194. } else {
  195. attach.setTimeout(soTimeout);
  196. }
  197. }
  198. }
  199. }
  200. } catch (InterruptedIOException e) {
  201. error = true;
  202. } catch (Throwable t) {
  203. log.error(sm.getString("http11processor.request.process"), t);
  204. // 500 - Internal Server Error
  205. response.setStatus(500);
  206. adapter.log(request, response, 0);
  207. error = true;
  208. }
  209. rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
  210. if (error) {
  211. recycle();
  212. return SocketState.CLOSED;
  213. } else if (!comet) {
  214. recycle();
  215. return (keepAlive)?SocketState.OPEN:SocketState.CLOSED;
  216. } else {
  217. return SocketState.LONG;
  218. }
  219. }
  220. /**
  221. * Process pipelined HTTP requests using the specified input and output
  222. * streams.
  223. *
  224. * @throws IOException error during an I/O operation
  225. */
  226. public SocketState process(NioChannel socket)
  227. throws IOException {
  228. RequestInfo rp = request.getRequestProcessor();
  229. rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);
  230. // Setting up the socket
  231. this.socket = socket;
  232. inputBuffer.setSocket(socket);
  233. outputBuffer.setSocket(socket);
  234. inputBuffer.setSelectorPool(endpoint.getSelectorPool());
  235. outputBuffer.setSelectorPool(endpoint.getSelectorPool());
  236. // Error flag
  237. error = false;
  238. keepAlive = true;
  239. comet = false;
  240. async = false;
  241. long soTimeout = endpoint.getSoTimeout();
  242. int keepAliveTimeout = endpoint.getKeepAliveTimeout();
  243. boolean keptAlive = false;
  244. boolean openSocket = false;
  245. boolean recycle = true;
  246. final KeyAttachment ka = (KeyAttachment)socket.getAttachment(false);
  247. while (!error && keepAlive && !comet && !async) {
  248. //always default to our soTimeout
  249. ka.setTimeout(soTimeout);
  250. // Parsing the request header
  251. try {
  252. if( !disableUploadTimeout && keptAlive && soTimeout > 0 ) {
  253. socket.getIOChannel().socket().setSoTimeout((int)soTimeout);
  254. }
  255. if (!inputBuffer.parseRequestLine(keptAlive)) {
  256. //no data available yet, since we might have read part
  257. //of the request line, we can't recycle the processor
  258. openSocket = true;
  259. recycle = false;
  260. if (inputBuffer.getParsingRequestLinePhase()<2) {
  261. //keep alive timeout here
  262. if (keepAliveTimeout>0) ka.setTimeout(keepAliveTimeout);
  263. }
  264. break;
  265. }
  266. keptAlive = true;
  267. if ( !inputBuffer.parseHeaders() ) {
  268. //we've read part of the request, don't recycle it
  269. //instead associate it with the socket
  270. openSocket = true;
  271. recycle = false;
  272. break;
  273. }
  274. request.setStartTime(System.currentTimeMillis());
  275. if (!disableUploadTimeout) { //only for body, not for request headers
  276. socket.getIOChannel().socket().setSoTimeout(timeout);
  277. }
  278. } catch (IOException e) {
  279. if (log.isDebugEnabled()) {
  280. log.debug(sm.getString("http11processor.header.parse"), e);
  281. }
  282. error = true;
  283. break;
  284. } catch (Throwable t) {
  285. if (log.isDebugEnabled()) {
  286. log.debug(sm.getString("http11processor.header.parse"), t);
  287. }
  288. // 400 - Bad Request
  289. response.setStatus(400);
  290. adapter.log(request, response, 0);
  291. error = true;
  292. }
  293. if (!error) {
  294. // Setting up filters, and parse some request headers
  295. rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE);
  296. try {
  297. prepareRequest();
  298. } catch (Throwable t) {
  299. if (log.isDebugEnabled()) {
  300. log.debug(sm.getString("http11processor.request.prepare"), t);
  301. }
  302. // 400 - Internal Server Error
  303. response.setStatus(400);
  304. adapter.log(request, response, 0);
  305. error = true;
  306. }
  307. }
  308. if (maxKeepAliveRequests == 1 )
  309. keepAlive = false;
  310. if (maxKeepAliveRequests > 0 && ka.decrementKeepAlive() <= 0)
  311. keepAlive = false;
  312. // Process the request in the adapter
  313. if (!error) {
  314. try {
  315. rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE);
  316. adapter.service(request, response);
  317. // Handle when the response was committed before a serious
  318. // error occurred. Throwing a ServletException should both
  319. // set the status to 500 and set the errorException.
  320. // If we fail here, then the response is likely already
  321. // committed, so we can't try and set headers.
  322. if(keepAlive && !error) { // Avoid checking twice.
  323. error = response.getErrorException() != null ||
  324. statusDropsConnection(response.getStatus());
  325. }
  326. // Comet support
  327. SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
  328. if (key != null) {
  329. NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment();
  330. if (attach != null) {
  331. attach.setComet(comet);
  332. if (comet) {
  333. Integer comettimeout = (Integer) request.getAttribute("org.apache.tomcat.comet.timeout");
  334. if (comettimeout != null) attach.setTimeout(comettimeout.longValue());
  335. }
  336. }
  337. }
  338. } catch (InterruptedIOException e) {
  339. error = true;
  340. } catch (Throwable t) {
  341. log.error(sm.getString("http11processor.request.process"), t);
  342. // 500 - Internal Server Error
  343. response.setStatus(500);
  344. adapter.log(request, response, 0);
  345. error = true;
  346. }
  347. }
  348. // Finish the handling of the request
  349. if (!comet && !async) {
  350. // If we know we are closing the connection, don't drain input.
  351. // This way uploading a 100GB file doesn't tie up the thread
  352. // if the servlet has rejected it.
  353. if(error)
  354. inputBuffer.setSwallowInput(false);
  355. endRequest();
  356. }
  357. // If there was an error, make sure the request is counted as
  358. // and error, and update the statistics counter
  359. if (error) {
  360. response.setStatus(500);
  361. }
  362. request.updateCounters();
  363. if (!comet && !async) {
  364. // Next request
  365. inputBuffer.nextRequest();
  366. outputBuffer.nextRequest();
  367. }
  368. // Do sendfile as needed: add socket to sendfile and end
  369. if (sendfileData != null && !error) {
  370. ka.setSendfileData(sendfileData);
  371. sendfileData.keepAlive = keepAlive;
  372. SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
  373. //do the first write on this thread, might as well
  374. openSocket = socket.getPoller().processSendfile(key,ka,true,true);
  375. break;
  376. }
  377. rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
  378. }//while
  379. rp.setStage(org.apache.coyote.Constants.STAGE_ENDED);
  380. if (comet || async) {
  381. if (error) {
  382. recycle();
  383. return SocketState.CLOSED;
  384. } else {
  385. return SocketState.LONG;
  386. }
  387. } else {
  388. if ( recycle ) {
  389. recycle();
  390. }
  391. //return (openSocket) ? (SocketState.OPEN) : SocketState.CLOSED;
  392. return (openSocket) ? (recycle?SocketState.OPEN:SocketState.LONG) : SocketState.CLOSED;
  393. }
  394. }
  395. public void endRequest() {
  396. // Finish the handling of the request
  397. try {
  398. inputBuffer.endRequest();
  399. } catch (IOException e) {
  400. error = true;
  401. } catch (Throwable t) {
  402. log.error(sm.getString("http11processor.request.finish"), t);
  403. // 500 - Internal Server Error
  404. response.setStatus(500);
  405. adapter.log(request, response, 0);
  406. error = true;
  407. }
  408. try {
  409. outputBuffer.endRequest();
  410. } catch (IOException e) {
  411. error = true;
  412. } catch (Throwable t) {
  413. log.error(sm.getString("http11processor.response.finish"), t);
  414. error = true;
  415. }
  416. }
  417. public void recycle() {
  418. inputBuffer.recycle();
  419. outputBuffer.recycle();
  420. this.socket = null;
  421. this.cometClose = false;
  422. this.comet = false;
  423. remoteAddr = null;
  424. remoteHost = null;
  425. localAddr = null;
  426. localName = null;
  427. remotePort = -1;
  428. localPort = -1;
  429. }
  430. // ----------------------------------------------------- ActionHook Methods
  431. /**
  432. * Send an action to the connector.
  433. *
  434. * @param actionCode Type of the action
  435. * @param param Action parameter
  436. */
  437. public void action(ActionCode actionCode, Object param) {
  438. if (actionCode == ActionCode.ACTION_COMMIT) {
  439. // Commit current response
  440. if (response.isCommitted())
  441. return;
  442. // Validate and write response headers
  443. try {
  444. prepareResponse();
  445. outputBuffer.commit();
  446. } catch (IOException e) {
  447. // Set error flag
  448. error = true;
  449. }
  450. } else if (actionCode == ActionCode.ACTION_ACK) {
  451. // Acknowledge request
  452. // Send a 100 status back if it makes sense (response not committed
  453. // yet, and client specified an expectation for 100-continue)
  454. if ((response.isCommitted()) || !expectation)
  455. return;
  456. inputBuffer.setSwallowInput(true);
  457. try {
  458. outputBuffer.sendAck();
  459. } catch (IOException e) {
  460. // Set error flag
  461. error = true;
  462. }
  463. } else if (actionCode == ActionCode.ACTION_CLIENT_FLUSH) {
  464. try {
  465. outputBuffer.flush();
  466. } catch (IOException e) {
  467. // Set error flag
  468. error = true;
  469. response.setErrorException(e);
  470. }
  471. } else if (actionCode == ActionCode.ACTION_CLOSE) {
  472. // Close
  473. // End the processing of the current request, and stop any further
  474. // transactions with the client
  475. comet = false;
  476. cometClose = true;
  477. async = false;
  478. SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
  479. if ( key != null ) {
  480. NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment();
  481. if ( attach!=null && attach.getComet()) {
  482. //if this is a comet connection
  483. //then execute the connection closure at the next selector loop
  484. //request.getAttributes().remove("org.apache.tomcat.comet.timeout");
  485. //attach.setTimeout(5000); //force a cleanup in 5 seconds
  486. //attach.setError(true); //this has caused concurrency errors
  487. }
  488. }
  489. try {
  490. outputBuffer.endRequest();
  491. } catch (IOException e) {
  492. // Set error flag
  493. error = true;
  494. }
  495. } else if (actionCode == ActionCode.ACTION_RESET) {
  496. // Reset response
  497. // Note: This must be called before the response is committed
  498. outputBuffer.reset();
  499. } else if (actionCode == ActionCode.ACTION_CUSTOM) {
  500. // Do nothing
  501. } else if (actionCode == ActionCode.ACTION_REQ_HOST_ADDR_ATTRIBUTE) {
  502. // Get remote host address
  503. if ((remoteAddr == null) && (socket != null)) {
  504. InetAddress inetAddr = socket.getIOChannel().socket().getInetAddress();
  505. if (inetAddr != null) {
  506. remoteAddr = inetAddr.getHostAddress();
  507. }
  508. }
  509. request.remoteAddr().setString(remoteAddr);
  510. } else if (actionCode == ActionCode.ACTION_REQ_LOCAL_NAME_ATTRIBUTE) {
  511. // Get local host name
  512. if ((localName == null) && (socket != null)) {
  513. InetAddress inetAddr = socket.getIOChannel().socket().getLocalAddress();
  514. if (inetAddr != null) {
  515. localName = inetAddr.getHostName();
  516. }
  517. }
  518. request.localName().setString(localName);
  519. } else if (actionCode == ActionCode.ACTION_REQ_HOST_ATTRIBUTE) {
  520. // Get remote host name
  521. if ((remoteHost == null) && (socket != null)) {
  522. InetAddress inetAddr = socket.getIOChannel().socket().getInetAddress();
  523. if (inetAddr != null) {
  524. remoteHost = inetAddr.getHostName();
  525. }
  526. if(remoteHost == null) {
  527. if(remoteAddr != null) {
  528. remoteHost = remoteAddr;
  529. } else { // all we can do is punt
  530. request.remoteHost().recycle();
  531. }
  532. }
  533. }
  534. request.remoteHost().setString(remoteHost);
  535. } else if (actionCode == ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE) {
  536. if (localAddr == null)
  537. localAddr = socket.getIOChannel().socket().getLocalAddress().getHostAddress();
  538. request.localAddr().setString(localAddr);
  539. } else if (actionCode == ActionCode.ACTION_REQ_REMOTEPORT_ATTRIBUTE) {
  540. if ((remotePort == -1 ) && (socket !=null)) {
  541. remotePort = socket.getIOChannel().socket().getPort();
  542. }
  543. request.setRemotePort(remotePort);
  544. } else if (actionCode == ActionCode.ACTION_REQ_LOCALPORT_ATTRIBUTE) {
  545. if ((localPort == -1 ) && (socket !=null)) {
  546. localPort = socket.getIOChannel().socket().getLocalPort();
  547. }
  548. request.setLocalPort(localPort);
  549. } else if (actionCode == ActionCode.ACTION_REQ_SSL_ATTRIBUTE ) {
  550. try {
  551. if (sslSupport != null) {
  552. Object sslO = sslSupport.getCipherSuite();
  553. if (sslO != null)
  554. request.setAttribute
  555. (SSLSupport.CIPHER_SUITE_KEY, sslO);
  556. sslO = sslSupport.getPeerCertificateChain(false);
  557. if (sslO != null)
  558. request.setAttribute
  559. (SSLSupport.CERTIFICATE_KEY, sslO);
  560. sslO = sslSupport.getKeySize();
  561. if (sslO != null)
  562. request.setAttribute
  563. (SSLSupport.KEY_SIZE_KEY, sslO);
  564. sslO = sslSupport.getSessionId();
  565. if (sslO != null)
  566. request.setAttribute
  567. (SSLSupport.SESSION_ID_KEY, sslO);
  568. request.setAttribute(SSLSupport.SESSION_MGR, sslSupport);
  569. }
  570. } catch (Exception e) {
  571. log.warn(sm.getString("http11processor.socket.ssl"), e);
  572. }
  573. } else if (actionCode == ActionCode.ACTION_REQ_SSL_CERTIFICATE) {
  574. if( sslSupport != null) {
  575. /*
  576. * Consume and buffer the request body, so that it does not
  577. * interfere with the client's handshake messages
  578. */
  579. InputFilter[] inputFilters = inputBuffer.getFilters();
  580. ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER])
  581. .setLimit(maxSavePostSize);
  582. inputBuffer.addActiveFilter
  583. (inputFilters[Constants.BUFFERED_FILTER]);
  584. try {
  585. Object sslO = sslSupport.getPeerCertificateChain(true);
  586. if( sslO != null) {
  587. request.setAttribute
  588. (SSLSupport.CERTIFICATE_KEY, sslO);
  589. }
  590. } catch (Exception e) {
  591. log.warn(sm.getString("http11processor.socket.ssl"), e);
  592. }
  593. }
  594. } else if (actionCode == ActionCode.ACTION_REQ_SET_BODY_REPLAY) {
  595. ByteChunk body = (ByteChunk) param;
  596. InputFilter savedBody = new SavedRequestInputFilter(body);
  597. savedBody.setRequest(request);
  598. InternalNioInputBuffer internalBuffer = (InternalNioInputBuffer)
  599. request.getInputBuffer();
  600. internalBuffer.addActiveFilter(savedBody);
  601. } else if (actionCode == ActionCode.ACTION_AVAILABLE) {
  602. request.setAvailable(inputBuffer.available());
  603. } else if (actionCode == ActionCode.ACTION_COMET_BEGIN) {
  604. comet = true;
  605. } else if (actionCode == ActionCode.ACTION_COMET_END) {
  606. comet = false;
  607. } else if (actionCode == ActionCode.ACTION_COMET_CLOSE) {
  608. if (socket==null || socket.getAttachment(false)==null) return;
  609. NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
  610. attach.setCometOps(NioEndpoint.OP_CALLBACK);
  611. //notify poller if not on a tomcat thread
  612. RequestInfo rp = request.getRequestProcessor();
  613. if ( rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE ) //async handling
  614. socket.getPoller().cometInterest(socket);
  615. } else if (actionCode == ActionCode.ACTION_COMET_SETTIMEOUT) {
  616. if (param==null) return;
  617. if (socket==null || socket.getAttachment(false)==null) return;
  618. NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
  619. long timeout = ((Long)param).longValue();
  620. //if we are not piggy backing on a worker thread, set the timeout
  621. RequestInfo rp = request.getRequestProcessor();
  622. if ( rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE ) //async handling
  623. attach.setTimeout(timeout);
  624. } else if (actionCode == ActionCode.ACTION_ASYNC_START) {
  625. //TODO SERVLET3 - async
  626. async = true;
  627. } else if (actionCode == ActionCode.ACTION_ASYNC_COMPLETE) {
  628. //TODO SERVLET3 - async
  629. AtomicBoolean dispatch = (AtomicBoolean)param;
  630. RequestInfo rp = request.getRequestProcessor();
  631. if ( rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE ) { //async handling
  632. dispatch.set(true);
  633. endpoint.processSocket(this.socket, SocketStatus.STOP, true);
  634. } else {
  635. dispatch.set(false);
  636. }
  637. } else if (actionCode == ActionCode.ACTION_ASYNC_SETTIMEOUT) {
  638. //TODO SERVLET3 - async
  639. if (param==null) return;
  640. if (socket==null || socket.getAttachment(false)==null) return;
  641. NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socket.getAttachment(false);
  642. long timeout = ((Long)param).longValue();
  643. //if we are not piggy backing on a worker thread, set the timeout
  644. attach.setTimeout(timeout);
  645. } else if (actionCode == ActionCode.ACTION_ASYNC_DISPATCH) {
  646. RequestInfo rp = request.getRequestProcessor();
  647. AtomicBoolean dispatch = (AtomicBoolean)param;
  648. if ( rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE ) {//async handling
  649. endpoint.processSocket(this.socket, SocketStatus.OPEN, true);
  650. dispatch.set(true);
  651. } else {
  652. dispatch.set(true);
  653. }
  654. }
  655. }
  656. // ------------------------------------------------------ Connector Methods
  657. public SSLSupport getSslSupport() {
  658. return sslSupport;
  659. }
  660. // ------------------------------------------------------ Protected Methods
  661. /**
  662. * After reading the request headers, we have to setup the request filters.
  663. */
  664. protected void prepareRequest() {
  665. http11 = true;
  666. http09 = false;
  667. contentDelimitation = false;
  668. expectation = false;
  669. sendfileData = null;
  670. if (ssl) {
  671. request.scheme().setString("https");
  672. }
  673. MessageBytes protocolMB = request.protocol();
  674. if (protocolMB.equals(Constants.HTTP_11)) {
  675. http11 = true;
  676. protocolMB.setString(Constants.HTTP_11);
  677. } else if (protocolMB.equals(Constants.HTTP_10)) {
  678. http11 = false;
  679. keepAlive = false;
  680. protocolMB.setString(Constants.HTTP_10);
  681. } else if (protocolMB.equals("")) {
  682. // HTTP/0.9
  683. http09 = true;
  684. http11 = false;
  685. keepAlive = false;
  686. } else {
  687. // Unsupported protocol
  688. http11 = false;
  689. error = true;
  690. // Send 505; Unsupported HTTP version
  691. response.setStatus(505);
  692. adapter.log(request, response, 0);
  693. }
  694. MessageBytes methodMB = request.method();
  695. if (methodMB.equals(Constants.GET)) {
  696. methodMB.setString(Constants.GET);
  697. } else if (methodMB.equals(Constants.POST)) {
  698. methodMB.setString(Constants.POST);
  699. }
  700. MimeHeaders headers = request.getMimeHeaders();
  701. // Check connection header
  702. MessageBytes connectionValueMB = headers.getValue("connection");
  703. if (connectionValueMB != null) {
  704. ByteChunk connectionValueBC = connectionValueMB.getByteChunk();
  705. if (findBytes(connectionValueBC, Constants.CLOSE_BYTES) != -1) {
  706. keepAlive = false;
  707. } else if (findBytes(connectionValueBC,
  708. Constants.KEEPALIVE_BYTES) != -1) {
  709. keepAlive = true;
  710. }
  711. }
  712. MessageBytes expectMB = null;
  713. if (http11)
  714. expectMB = headers.getValue("expect");
  715. if ((expectMB != null)
  716. && (expectMB.indexOfIgnoreCase("100-continue", 0) != -1)) {
  717. inputBuffer.setSwallowInput(false);
  718. expectation = true;
  719. }
  720. // Check user-agent header
  721. if ((restrictedUserAgents != null) && ((http11) || (keepAlive))) {
  722. MessageBytes userAgentValueMB = headers.getValue("user-agent");
  723. // Check in the restricted list, and adjust the http11
  724. // and keepAlive flags accordingly
  725. if(userAgentValueMB != null) {
  726. String userAgentValue = userAgentValueMB.toString();
  727. for (int i = 0; i < restrictedUserAgents.length; i++) {
  728. if (restrictedUserAgents[i].matcher(userAgentValue).matches()) {
  729. http11 = false;
  730. keepAlive = false;
  731. break;
  732. }
  733. }
  734. }
  735. }
  736. // Check for a full URI (including protocol://host:port/)
  737. ByteChunk uriBC = request.requestURI().getByteChunk();
  738. if (uriBC.startsWithIgnoreCase("http", 0)) {
  739. int pos = uriBC.indexOf("://", 0, 3, 4);
  740. int uriBCStart = uriBC.getStart();
  741. int slashPos = -1;
  742. if (pos != -1) {
  743. byte[] uriB = uriBC.getBytes();
  744. slashPos = uriBC.indexOf('/', pos + 3);
  745. if (slashPos == -1) {
  746. slashPos = uriBC.getLength();
  747. // Set URI as "/"
  748. request.requestURI().setBytes
  749. (uriB, uriBCStart + pos + 1, 1);
  750. } else {
  751. request.requestURI().setBytes
  752. (uriB, uriBCStart + slashPos,
  753. uriBC.getLength() - slashPos);
  754. }
  755. MessageBytes hostMB = headers.setValue("host");
  756. hostMB.setBytes(uriB, uriBCStart + pos + 3,
  757. slashPos - pos - 3);
  758. }
  759. }
  760. // Input filter setup
  761. InputFilter[] inputFilters = inputBuffer.getFilters();
  762. // Parse transfer-encoding header
  763. MessageBytes transferEncodingValueMB = null;
  764. if (http11)
  765. transferEncodingValueMB = headers.getValue("transfer-encoding");
  766. if (transferEncodingValueMB != null) {
  767. String transferEncodingValue = transferEncodingValueMB.toString();
  768. // Parse the comma separated list. "identity" codings are ignored
  769. int startPos = 0;
  770. int commaPos = transferEncodingValue.indexOf(',');
  771. String encodingName = null;
  772. while (commaPos != -1) {
  773. encodingName = transferEncodingValue.substring
  774. (startPos, commaPos).toLowerCase(Locale.ENGLISH).trim();
  775. if (!addInputFilter(inputFilters, encodingName)) {
  776. // Unsupported transfer encoding
  777. error = true;
  778. // 501 - Unimplemented
  779. response.setStatus(501);
  780. adapter.log(request, response, 0);
  781. }
  782. startPos = commaPos + 1;
  783. commaPos = transferEncodingValue.indexOf(',', startPos);
  784. }
  785. encodingName = transferEncodingValue.substring(startPos)
  786. .toLowerCase(Locale.ENGLISH).trim();
  787. if (!addInputFilter(inputFilters, encodingName)) {
  788. // Unsupported transfer encoding
  789. error = true;
  790. // 501 - Unimplemented
  791. response.setStatus(501);
  792. adapter.log(request, response, 0);
  793. }
  794. }
  795. // Parse content-length header
  796. long contentLength = request.getContentLengthLong();
  797. if (contentLength >= 0 && !contentDelimitation) {
  798. inputBuffer.addActiveFilter
  799. (inputFilters[Constants.IDENTITY_FILTER]);
  800. contentDelimitation = true;
  801. }
  802. MessageBytes valueMB = headers.getValue("host");
  803. // Check host header
  804. if (http11 && (valueMB == null)) {
  805. error = true;
  806. // 400 - Bad request
  807. response.setStatus(400);
  808. adapter.log(request, response, 0);
  809. }
  810. parseHost(valueMB);
  811. if (!contentDelimitation) {
  812. // If there's no content length
  813. // (broken HTTP/1.0 or HTTP/1.1), assume
  814. // the client is not broken and didn't send a body
  815. inputBuffer.addActiveFilter
  816. (inputFilters[Constants.VOID_FILTER]);
  817. contentDelimitation = true;
  818. }
  819. // Advertise sendfile support through a request attribute
  820. if (endpoint.getUseSendfile())
  821. request.setAttribute("org.apache.tomcat.sendfile.support", Boolean.TRUE);
  822. // Advertise comet support through a request attribute
  823. request.setAttribute("org.apache.tomcat.comet.support", Boolean.TRUE);
  824. // Advertise comet timeout support
  825. request.setAttribute("org.apache.tomcat.comet.timeout.support", Boolean.TRUE);
  826. }
  827. /**
  828. * Parse host.
  829. */
  830. public void parseHost(MessageBytes valueMB) {
  831. if (valueMB == null || valueMB.isNull()) {
  832. // HTTP/1.0
  833. // Default is what the socket tells us. Overridden if a host is
  834. // found/parsed
  835. request.setServerPort(endpoint.getPort());
  836. return;
  837. }
  838. ByteChunk valueBC = valueMB.getByteChunk();
  839. byte[] valueB = valueBC.getBytes();
  840. int valueL = valueBC.getLength();
  841. int valueS = valueBC.getStart();
  842. int colonPos = -1;
  843. if (hostNameC.length < valueL) {
  844. hostNameC = new char[valueL];
  845. }
  846. boolean ipv6 = (valueB[valueS] == '[');
  847. boolean bracketClosed = false;
  848. for (int i = 0; i < valueL; i++) {
  849. char b = (char) valueB[i + valueS];
  850. hostNameC[i] = b;
  851. if (b == ']') {
  852. bracketClosed = true;
  853. } else if (b == ':') {
  854. if (!ipv6 || bracketClosed) {
  855. colonPos = i;
  856. break;
  857. }
  858. }
  859. }
  860. if (colonPos < 0) {
  861. if (!ssl) {
  862. // 80 - Default HTTP port
  863. request.setServerPort(80);
  864. } else {
  865. // 443 - Default HTTPS port
  866. request.setServerPort(443);
  867. }
  868. request.serverName().setChars(hostNameC, 0, valueL);
  869. } else {
  870. request.serverName().setChars(hostNameC, 0, colonPos);
  871. int port = 0;
  872. int mult = 1;
  873. for (int i = valueL - 1; i > colonPos; i--) {
  874. int charValue = HexUtils.getDec(valueB[i + valueS]);
  875. if (charValue == -1) {
  876. // Invalid character
  877. error = true;
  878. // 400 - Bad request
  879. response.setStatus(400);
  880. adapter.log(request, response, 0);
  881. break;
  882. }
  883. port = port + (charValue * mult);
  884. mult = 10 * mult;
  885. }
  886. request.setServerPort(port);
  887. }
  888. }
  889. /**
  890. * When committing the response, we have to validate the set of headers, as
  891. * well as setup the response filters.
  892. */
  893. protected void prepareResponse() throws IOException {
  894. boolean entityBody = true;
  895. contentDelimitation = false;
  896. OutputFilter[] outputFilters = outputBuffer.getFilters();
  897. if (http09 == true) {
  898. // HTTP/0.9
  899. outputBuffer.addActiveFilter
  900. (outputFilters[Constants.IDENTITY_FILTER]);
  901. return;
  902. }
  903. int statusCode = response.getStatus();
  904. if ((statusCode == 204) || (statusCode == 205)
  905. || (statusCode == 304)) {
  906. // No entity body
  907. outputBuffer.addActiveFilter
  908. (outputFilters[Constants.VOID_FILTER]);
  909. entityBody = false;
  910. contentDelimitation = true;
  911. }
  912. MessageBytes methodMB = request.method();
  913. if (methodMB.equals("HEAD")) {
  914. // No entity body
  915. outputBuffer.addActiveFilter
  916. (outputFilters[Constants.VOID_FILTER]);
  917. contentDelimitation = true;
  918. }
  919. // Sendfile support
  920. if (this.endpoint.getUseSendfile()) {
  921. String fileName = (String) request.getAttribute("org.apache.tomcat.sendfile.filename");
  922. if (fileName != null) {
  923. // No entity body sent here
  924. outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
  925. contentDelimitation = true;
  926. sendfileData = new NioEndpoint.SendfileData();
  927. sendfileData.fileName = fileName;
  928. sendfileData.pos = ((Long) request.getAttribute("org.apache.tomcat.sendfile.start")).longValue();
  929. sendfileData.length = ((Long) request.getAttribute("org.apache.tomcat.sendfile.end")).longValue() - sendfileData.pos;
  930. }
  931. }
  932. // Check for compression
  933. boolean useCompression = false;
  934. if (entityBody && (compressionLevel > 0) && (sendfileData == null)) {
  935. useCompression = isCompressable();
  936. // Change content-length to -1 to force chunking
  937. if (useCompression) {
  938. response.setContentLength(-1);
  939. }
  940. }
  941. MimeHeaders headers = response.getMimeHeaders();
  942. if (!entityBody) {
  943. response.setContentLength(-1);
  944. } else {
  945. String contentType = response.getContentType();
  946. if (contentType != null) {
  947. headers.setValue("Content-Type").setString(contentType);
  948. }
  949. String contentLanguage = response.getContentLanguage();
  950. if (contentLanguage != null) {
  951. headers.setValue("Content-Language")
  952. .setString(contentLanguage);
  953. }
  954. }
  955. long contentLength = response.getContentLengthLong();
  956. if (contentLength != -1) {
  957. headers.setValue("Content-Length").setLong(contentLength);
  958. outputBuffer.addActiveFilter
  959. (outputFilters[Constants.IDENTITY_FILTER]);
  960. contentDelimitation = true;
  961. } else {
  962. if (entityBody && http11) {
  963. outputBuffer.addActiveFilter
  964. (outputFilters[Constants.CHUNKED_FILTER]);
  965. contentDelimitation = true;
  966. headers.addValue(Constants.TRANSFERENCODING).setString(Constants.CHUNKED);
  967. } else {
  968. outputBuffer.addActiveFilter
  969. (outputFilters[Constants.IDENTITY_FILTER]);
  970. }
  971. }
  972. if (useCompression) {
  973. outputBuffer.addActiveFilter(outputFilters[Constants.GZIP_FILTER]);
  974. headers.setValue("Content-Encoding").setString("gzip");
  975. // Make Proxies happy via Vary (from mod_deflate)
  976. MessageBytes vary = headers.getValue("Vary");
  977. if (vary == null) {
  978. // Add a new Vary header
  979. headers.setValue("Vary").setString("Accept-Encoding");
  980. } else if (vary.equals("*")) {
  981. // No action required
  982. } else {
  983. // Merge into current header
  984. headers.setValue("Vary").setString(
  985. vary.getString() + ",Accept-Encoding");
  986. }
  987. }
  988. // Add date header
  989. headers.setValue("Date").setString(FastHttpDateFormat.getCurrentDate());
  990. // FIXME: Add transfer encoding header
  991. if ((entityBody) && (!contentDelimitation)) {
  992. // Mark as close the connection after the request, and add the
  993. // connection: close header
  994. keepAlive = false;
  995. }
  996. // If we know that the request is bad this early, add the
  997. // Connection: close header.
  998. keepAlive = keepAlive && !statusDropsConnection(statusCode);
  999. if (!keepAlive) {
  1000. headers.addValue(Constants.CONNECTION).setString(Constants.CLOSE);
  1001. } else if (!http11 && !error) {
  1002. headers.addValue(Constants.CONNECTION).setString(Constants.KEEPALIVE);
  1003. }
  1004. // Build the response header
  1005. outputBuffer.sendStatus();
  1006. // Add server header
  1007. if (server != null) {
  1008. // Always overrides anything the app might set
  1009. headers.setValue("Server").setString(server);
  1010. } else if (headers.getValue("Server") == null) {
  1011. // If app didn't set the header, use the default
  1012. outputBuffer.write(Constants.SERVER_BYTES);
  1013. }
  1014. int size = headers.size();
  1015. for (int i = 0; i < size; i++) {
  1016. outputBuffer.sendHeader(headers.getName(i), headers.getValue(i));
  1017. }
  1018. outputBuffer.endHeaders();
  1019. }
  1020. /**
  1021. * Specialized utility method: find a sequence of lower case bytes inside
  1022. * a ByteChunk.
  1023. */
  1024. @Override
  1025. protected int findBytes(ByteChunk bc, byte[] b) {
  1026. byte first = b[0];
  1027. byte[] buff = bc.getBuffer();
  1028. int start = bc.getStart();
  1029. int end = bc.getEnd();
  1030. // Look for first char
  1031. int srcEnd = b.length;
  1032. for (int i = start; i <= (end - srcEnd); i++) {
  1033. if (Ascii.toLower(buff[i]) != first) continue;
  1034. // found first char, now look for a match
  1035. int myPos = i+1;
  1036. for (int srcPos = 1; srcPos < srcEnd; ) {
  1037. if (Ascii.toLower(buff[myPos++]) != b[srcPos++])
  1038. break;
  1039. if (srcPos == srcEnd) return i - start; // found it
  1040. }
  1041. }
  1042. return -1;
  1043. }
  1044. /**
  1045. * Determine if we must drop the connection because of the HTTP status
  1046. * code. Use the same list of codes as Apache/httpd.
  1047. */
  1048. @Override
  1049. protected boolean statusDropsConnection(int status) {
  1050. return status == 400 /* SC_BAD_REQUEST */ ||
  1051. status == 408 /* SC_REQUEST_TIMEOUT */ ||
  1052. status == 411 /* SC_LENGTH_REQUIRED */ ||
  1053. status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ ||
  1054. status == 414 /* SC_REQUEST_URI_TOO_LONG */ ||
  1055. status == 500 /* SC_INTERNAL_SERVER_ERROR */ ||
  1056. status == 503 /* SC_SERVICE_UNAVAILABLE */ ||
  1057. status == 501 /* SC_NOT_IMPLEMENTED */;
  1058. }
  1059. @Override
  1060. protected AbstractInputBuffer getInputBuffer() {
  1061. return inputBuffer;
  1062. }
  1063. @Override
  1064. protected AbstractOutputBuffer getOutputBuffer() {
  1065. return outputBuffer;
  1066. }
  1067. /**
  1068. * Set the SSL information for this HTTP connection.
  1069. */
  1070. public void setSslSupport(SSLSupport sslSupport) {
  1071. this.sslSupport = sslSupport;
  1072. }
  1073. }