Further attacks on the mysterious TCP CLOSE_WAIT issue
[zxing.git] / zxingorg / src / com / google / zxing / web / DecodeServlet.java
1 /*
2  * Copyright 2008 ZXing authors
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
17 package com.google.zxing.web;
18
19 import com.google.zxing.BarcodeFormat;
20 import com.google.zxing.BinaryBitmap;
21 import com.google.zxing.DecodeHintType;
22 import com.google.zxing.LuminanceSource;
23 import com.google.zxing.MultiFormatReader;
24 import com.google.zxing.Reader;
25 import com.google.zxing.ReaderException;
26 import com.google.zxing.Result;
27 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
28 import com.google.zxing.client.result.ParsedResult;
29 import com.google.zxing.client.result.ResultParser;
30 import com.google.zxing.common.GlobalHistogramBinarizer;
31
32 import org.apache.commons.fileupload.FileItem;
33 import org.apache.commons.fileupload.FileUploadException;
34 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
35 import org.apache.commons.fileupload.servlet.ServletFileUpload;
36 import org.apache.commons.lang.StringEscapeUtils;
37 import org.apache.http.Header;
38 import org.apache.http.HttpMessage;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.HttpVersion;
41 import org.apache.http.HttpEntity;
42 import org.apache.http.client.HttpClient;
43 import org.apache.http.client.methods.HttpGet;
44 import org.apache.http.client.methods.HttpUriRequest;
45 import org.apache.http.conn.scheme.PlainSocketFactory;
46 import org.apache.http.conn.scheme.Scheme;
47 import org.apache.http.conn.scheme.SchemeRegistry;
48 import org.apache.http.conn.ssl.SSLSocketFactory;
49 import org.apache.http.conn.ClientConnectionManager;
50 import org.apache.http.impl.client.DefaultHttpClient;
51 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
52 import org.apache.http.params.BasicHttpParams;
53 import org.apache.http.params.HttpParams;
54 import org.apache.http.params.HttpProtocolParams;
55
56 import java.awt.image.BufferedImage;
57 import java.io.IOException;
58 import java.io.InputStream;
59 import java.io.OutputStreamWriter;
60 import java.io.Writer;
61 import java.net.SocketException;
62 import java.net.URI;
63 import java.net.URISyntaxException;
64 import java.net.UnknownHostException;
65 import java.util.Hashtable;
66 import java.util.List;
67 import java.util.Vector;
68 import java.util.concurrent.TimeUnit;
69 import java.util.logging.Logger;
70
71 import javax.imageio.ImageIO;
72 import javax.servlet.ServletConfig;
73 import javax.servlet.ServletException;
74 import javax.servlet.ServletRequest;
75 import javax.servlet.http.HttpServlet;
76 import javax.servlet.http.HttpServletRequest;
77 import javax.servlet.http.HttpServletResponse;
78
79 /**
80  * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will
81  * retrieve the image and decode it. It can also process image files uploaded via POST.
82  * 
83  * @author Sean Owen
84  */
85 public final class DecodeServlet extends HttpServlet {
86
87   private static final long MAX_IMAGE_SIZE = 500000L;
88
89   private static final Logger log = Logger.getLogger(DecodeServlet.class.getName());
90
91   static final Hashtable<DecodeHintType, Object> HINTS;
92
93   static {
94     HINTS = new Hashtable<DecodeHintType, Object>(5);
95     HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
96     Vector<BarcodeFormat> possibleFormats = new Vector<BarcodeFormat>();
97     possibleFormats.add(BarcodeFormat.UPC_A);
98     possibleFormats.add(BarcodeFormat.UPC_E);
99     possibleFormats.add(BarcodeFormat.EAN_8);
100     possibleFormats.add(BarcodeFormat.EAN_13);
101     possibleFormats.add(BarcodeFormat.CODE_39);
102     possibleFormats.add(BarcodeFormat.CODE_128);
103     possibleFormats.add(BarcodeFormat.ITF);
104     possibleFormats.add(BarcodeFormat.QR_CODE);
105     possibleFormats.add(BarcodeFormat.DATAMATRIX);
106     HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats);
107   }
108
109   private HttpClient client;
110   private ClientConnectionManager connectionManager;
111   private DiskFileItemFactory diskFileItemFactory;
112
113   @Override
114   public void init(ServletConfig servletConfig) {
115
116     Logger logger = Logger.getLogger("com.google.zxing");
117     logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext()));
118
119     HttpParams params = new BasicHttpParams();
120     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
121
122     SchemeRegistry registry = new SchemeRegistry();
123     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
124     registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
125
126     connectionManager = new ThreadSafeClientConnManager(params, registry);
127     client = new DefaultHttpClient(connectionManager, params);
128
129     diskFileItemFactory = new DiskFileItemFactory();
130
131     log.info("DecodeServlet configured");
132   }
133
134   @Override
135   protected void doGet(HttpServletRequest request, HttpServletResponse response)
136       throws ServletException, IOException {
137     String imageURIString = request.getParameter("u");
138     if (imageURIString == null || imageURIString.length() == 0) {
139       response.sendRedirect("badurl.jspx");
140       return;
141     }
142
143     if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) {
144       imageURIString = "http://" + imageURIString;
145     }
146
147     URI imageURI;
148     try {
149       imageURI = new URI(imageURIString);
150     } catch (URISyntaxException urise) {
151       response.sendRedirect("badurl.jspx");
152       return;
153     }
154
155     HttpUriRequest getRequest = new HttpGet(imageURI);
156     getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue?
157
158     HttpResponse getResponse;
159     try {
160       getResponse = client.execute(getRequest);
161     } catch (IllegalArgumentException iae) {
162       // Thrown if hostname is bad or null
163       getRequest.abort();
164       response.sendRedirect("badurl.jspx");
165       return;
166     } catch (SocketException se) {
167       // Thrown if hostname is bad or null
168       getRequest.abort();
169       response.sendRedirect("badurl.jspx");
170       return;
171     } catch (UnknownHostException uhe) {
172       getRequest.abort();
173       response.sendRedirect("badurl.jspx");
174       return;
175     }
176
177     if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
178       response.sendRedirect("badurl.jspx");
179       return;
180     }
181     if (!isSizeOK(getResponse)) {
182       response.sendRedirect("badimage.jspx");
183       return;
184     }
185
186     log.info("Decoding " + imageURI);
187     HttpEntity entity = getResponse.getEntity();
188     InputStream is = entity.getContent();
189     try {
190       processStream(is, request, response);
191     } finally {
192       entity.consumeContent();      
193       is.close();
194       // Hmm, trying harder here to avoid the CLOSE_WAIT problem:
195       connectionManager.closeExpiredConnections();
196       connectionManager.closeIdleConnections(0L, TimeUnit.MILLISECONDS);
197     }
198
199   }
200
201   @Override
202   protected void doPost(HttpServletRequest request, HttpServletResponse response)
203           throws ServletException, IOException {
204
205     if (!ServletFileUpload.isMultipartContent(request)) {
206       response.sendRedirect("badimage.jspx");
207       return;
208     }
209
210     ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
211     upload.setFileSizeMax(MAX_IMAGE_SIZE);
212
213     // Parse the request
214     try {
215       for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
216         if (!item.isFormField()) {
217           if (item.getSize() <= MAX_IMAGE_SIZE) {
218             log.info("Decoding uploaded file");
219             InputStream is = item.getInputStream();
220             try {
221               processStream(is, request, response);
222             } finally {
223               is.close();
224             }
225           } else {
226             response.sendRedirect("badimage.jspx");
227           }
228           break;
229         }
230       }
231     } catch (FileUploadException fue) {
232       response.sendRedirect("badimage.jspx");
233     }
234
235   }
236
237   private static void processStream(InputStream is, ServletRequest request,
238       HttpServletResponse response) throws ServletException, IOException {
239     BufferedImage image = ImageIO.read(is);
240     if (image == null) {
241       response.sendRedirect("badimage.jspx");
242       return;
243     }
244
245     Reader reader = new MultiFormatReader();
246     Result result;
247     try {
248       LuminanceSource source = new BufferedImageLuminanceSource(image);
249       BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
250       result = reader.decode(bitmap, HINTS);
251     } catch (ReaderException re) {
252       log.info("DECODE FAILED: " + re.toString());
253       response.sendRedirect("notfound.jspx");
254       return;
255     }
256
257     if (request.getParameter("full") == null) {
258       response.setContentType("text/plain");
259       response.setCharacterEncoding("UTF8");
260       Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8");
261       try {
262         out.write(result.getText());
263       } finally {
264         out.close();
265       }
266     } else {
267       request.setAttribute("result", result);
268       byte[] rawBytes = result.getRawBytes();
269       if (rawBytes != null) {
270         request.setAttribute("rawBytesString", arrayToString(rawBytes));
271       } else {
272         request.setAttribute("rawBytesString", "(Not applicable)");
273       }
274       String text = result.getText();
275       if (text != null) {
276         request.setAttribute("text", StringEscapeUtils.escapeXml(text));
277       } else {
278         request.setAttribute("text", "(Not applicable)");
279       }
280       ParsedResult parsedResult = ResultParser.parseResult(result);
281       request.setAttribute("parsedResult", parsedResult);
282       String displayResult = parsedResult.getDisplayResult();
283       if (displayResult != null) {
284         request.setAttribute("displayResult", StringEscapeUtils.escapeXml(displayResult));
285       } else {
286         request.setAttribute("displayResult", "(Not applicable)");
287       }
288       request.getRequestDispatcher("decoderesult.jspx").forward(request, response);
289     }
290   }
291
292   private static boolean isSizeOK(HttpMessage getResponse) {
293     Header lengthHeader = getResponse.getLastHeader("Content-Length");
294     if (lengthHeader != null) {
295       long length = Long.parseLong(lengthHeader.getValue());
296       if (length > MAX_IMAGE_SIZE) {
297         return false;
298       }
299     }
300     return true;
301   }
302
303   private static String arrayToString(byte[] bytes) {
304     int length = bytes.length;
305     StringBuilder result = new StringBuilder(length << 2);
306     int i = 0;
307     while (i < length) {
308       int max = Math.min(i + 8, length);
309       for (int j = i; j < max; j++) {
310         int value = bytes[j] & 0xFF;
311         result.append(Integer.toHexString(value / 16));
312         result.append(Integer.toHexString(value % 16));
313         result.append(' ');
314       }
315       result.append('\n');
316       i += 8;
317     }
318     for (int j = i - 8; j < length; j++) {
319       result.append(Integer.toHexString(bytes[j] & 0xFF));
320       result.append(' ');
321     }
322     return result.toString();
323   }
324
325   @Override
326   public void destroy() {
327     log.config("DecodeServlet shutting down...");
328   }
329
330 }