1 | package simplejavaproxy; |
---|
2 | |
---|
3 | /* |
---|
4 | * This is a simple multi-threaded Java proxy server |
---|
5 | * for HTTP requests (HTTPS doesn't seem to work, because |
---|
6 | * the CONNECT requests aren't always handled properly). |
---|
7 | * I implemented the class as a thread so you can call it |
---|
8 | * from other programs and kill it, if necessary (by using |
---|
9 | * the closeSocket() method). |
---|
10 | * |
---|
11 | * We'll call this the 1.1 version of this class. All I |
---|
12 | * changed was to separate the HTTP header elements with |
---|
13 | * \r\n instead of just \n, to comply with the official |
---|
14 | * HTTP specification. |
---|
15 | * |
---|
16 | * This can be used either as a direct proxy to other |
---|
17 | * servers, or as a forwarding proxy to another proxy |
---|
18 | * server. This makes it useful if you want to monitor |
---|
19 | * traffic going to and from a proxy server (for example, |
---|
20 | * you can run this on your local machine and set the |
---|
21 | * fwdServer and fwdPort to a real proxy server, and then |
---|
22 | * tell your browser to use "localhost" as the proxy, and |
---|
23 | * you can watch the browser traffic going in and out). |
---|
24 | * |
---|
25 | * One limitation of this implementation is that it doesn't |
---|
26 | * close the ProxyThread socket if the client disconnects |
---|
27 | * or the server never responds, so you could end up with |
---|
28 | * a bunch of loose threads running amuck and waiting for |
---|
29 | * connections. As a band-aid, you can set the server socket |
---|
30 | * to timeout after a certain amount of time (use the |
---|
31 | * setTimeout() method in the ProxyThread class), although |
---|
32 | * this can cause false timeouts if a remote server is simply |
---|
33 | * slow to respond. |
---|
34 | * |
---|
35 | * Another thing is that it doesn't limit the number of |
---|
36 | * socket threads it will create, so if you use this on a |
---|
37 | * really busy machine that processed a bunch of requests, |
---|
38 | * you may have problems. You should use thread pools if |
---|
39 | * you're going to try something like this in a "real" |
---|
40 | * application. |
---|
41 | * |
---|
42 | * Note that if you're using the "main" method to run this |
---|
43 | * by itself and you don't need the debug output, it will |
---|
44 | * run a bit faster if you pipe the std output to 'nul'. |
---|
45 | * |
---|
46 | * You may use this code as you wish, just don't pretend |
---|
47 | * that you wrote it yourself, and don't hold me liable for |
---|
48 | * anything that it does or doesn't do. If you're feeling |
---|
49 | * especially honest, please include a link to nsftools.com |
---|
50 | * along with the code. Thanks, and good luck. |
---|
51 | * |
---|
52 | * Julian Robichaux -- http://www.nsftools.com |
---|
53 | */ |
---|
54 | import java.io.*; |
---|
55 | import java.net.*; |
---|
56 | import java.lang.reflect.Array; |
---|
57 | import java.util.HashMap; |
---|
58 | import java.util.Iterator; |
---|
59 | import java.util.Map; |
---|
60 | import java.util.concurrent.ConcurrentHashMap; |
---|
61 | |
---|
62 | public class SimpleProxy extends Thread { |
---|
63 | public static final int DEFAULT_PORT = 8080; |
---|
64 | private ServerSocket server = null; |
---|
65 | private int thisPort = DEFAULT_PORT; |
---|
66 | private String fwdServer = ""; |
---|
67 | private int fwdPort = 0; |
---|
68 | private int ptTimeout = ProxyThread.DEFAULT_TIMEOUT; |
---|
69 | private int debugLevel = 1; |
---|
70 | private PrintStream debugOut = System.out; |
---|
71 | //FMG>> |
---|
72 | public static String safariKey = ""; |
---|
73 | public static Map cookieMap = new ConcurrentHashMap(); |
---|
74 | |
---|
75 | |
---|
76 | /* here's a main method, in case you want to run this by itself */ |
---|
77 | public static void main(String args[]) { |
---|
78 | int port = 0; |
---|
79 | String fwdProxyServer = ""; |
---|
80 | int fwdProxyPort = 0; |
---|
81 | |
---|
82 | if (args.length == 0) { |
---|
83 | System.err.println("USAGE: java jProxy <port number> [<fwd proxy> <fwd port>]"); |
---|
84 | System.err.println(" <port number> the port this service listens on"); |
---|
85 | System.err.println(" <fwd proxy> optional proxy server to forward requests to"); |
---|
86 | System.err.println(" <fwd port> the port that the optional proxy server is on"); |
---|
87 | System.err.println("\nHINT: if you don't want to see all the debug information flying by,"); |
---|
88 | System.err.println("you can pipe the output to a file or to 'nul' using \">\". For example:"); |
---|
89 | System.err.println(" to send output to the file prox.txt: java jProxy 8080 > prox.txt"); |
---|
90 | System.err.println(" to make the output go away: java jProxy 8080 > nul"); |
---|
91 | return; |
---|
92 | } |
---|
93 | |
---|
94 | // get the command-line parameters |
---|
95 | port = Integer.parseInt(args[0]); |
---|
96 | if (args.length > 2) { |
---|
97 | fwdProxyServer = args[1]; |
---|
98 | fwdProxyPort = Integer.parseInt(args[2]); |
---|
99 | } |
---|
100 | |
---|
101 | // create and start the jProxy thread, using a 20 second timeout |
---|
102 | // value to keep the threads from piling up too much |
---|
103 | System.err.println(" ** Starting jProxy on port " + port + ". Press CTRL-C to end. **\n"); |
---|
104 | SimpleProxy jp = new SimpleProxy(port, fwdProxyServer, fwdProxyPort, 20); |
---|
105 | jp.setDebug(1, System.out); // or set the debug level to 2 for tons of output |
---|
106 | jp.start(); |
---|
107 | |
---|
108 | // run forever; if you were calling this class from another |
---|
109 | // program and you wanted to stop the jProxy thread at some |
---|
110 | // point, you could write a loop that waits for a certain |
---|
111 | // condition and then calls jProxy.closeSocket() to kill |
---|
112 | // the running jProxy thread |
---|
113 | while (true) { |
---|
114 | try { |
---|
115 | Thread.sleep(3000); |
---|
116 | } catch (Exception e) { |
---|
117 | } |
---|
118 | } |
---|
119 | |
---|
120 | // if we ever had a condition that stopped the loop above, |
---|
121 | // we'd want to do this to kill the running thread |
---|
122 | //jp.closeSocket(); |
---|
123 | //return; |
---|
124 | } |
---|
125 | |
---|
126 | |
---|
127 | /* the proxy server just listens for connections and creates |
---|
128 | * a new thread for each connection attempt (the ProxyThread |
---|
129 | * class really does all the work) |
---|
130 | */ |
---|
131 | public SimpleProxy(int port) { |
---|
132 | thisPort = port; |
---|
133 | } |
---|
134 | |
---|
135 | public SimpleProxy(int port, String proxyServer, int proxyPort) { |
---|
136 | thisPort = port; |
---|
137 | fwdServer = proxyServer; |
---|
138 | fwdPort = proxyPort; |
---|
139 | } |
---|
140 | |
---|
141 | public SimpleProxy(int port, String proxyServer, int proxyPort, int timeout) { |
---|
142 | thisPort = port; |
---|
143 | fwdServer = proxyServer; |
---|
144 | fwdPort = proxyPort; |
---|
145 | ptTimeout = timeout; |
---|
146 | } |
---|
147 | |
---|
148 | |
---|
149 | /* allow the user to decide whether or not to send debug |
---|
150 | * output to the console or some other PrintStream |
---|
151 | */ |
---|
152 | public void setDebug(int level, PrintStream out) { |
---|
153 | debugLevel = level; |
---|
154 | debugOut = out; |
---|
155 | } |
---|
156 | |
---|
157 | |
---|
158 | /* get the port that we're supposed to be listening on |
---|
159 | */ |
---|
160 | public int getPort() { |
---|
161 | return thisPort; |
---|
162 | } |
---|
163 | |
---|
164 | |
---|
165 | /* return whether or not the socket is currently open |
---|
166 | */ |
---|
167 | public boolean isRunning() { |
---|
168 | if (server == null) { |
---|
169 | return false; |
---|
170 | } else { |
---|
171 | return true; |
---|
172 | } |
---|
173 | } |
---|
174 | |
---|
175 | |
---|
176 | /* closeSocket will close the open ServerSocket; use this |
---|
177 | * to halt a running jProxy thread |
---|
178 | */ |
---|
179 | public void closeSocket() { |
---|
180 | try { |
---|
181 | // close the open server socket |
---|
182 | server.close(); |
---|
183 | // send it a message to make it stop waiting immediately |
---|
184 | // (not really necessary) |
---|
185 | /*Socket s = new Socket("localhost", thisPort); |
---|
186 | OutputStream os = s.getOutputStream(); |
---|
187 | os.write((byte)0); |
---|
188 | os.close(); |
---|
189 | s.close();*/ |
---|
190 | } catch (Exception e) { |
---|
191 | if (debugLevel > 0) { |
---|
192 | debugOut.println(e); |
---|
193 | } |
---|
194 | } |
---|
195 | |
---|
196 | server = null; |
---|
197 | } |
---|
198 | |
---|
199 | public void run() { |
---|
200 | try { |
---|
201 | // create a server socket, and loop forever listening for |
---|
202 | // client connections |
---|
203 | server = new ServerSocket(thisPort); |
---|
204 | if (debugLevel > 0) { |
---|
205 | debugOut.println("Started jProxy on port " + thisPort); |
---|
206 | } |
---|
207 | |
---|
208 | while (true) { |
---|
209 | Socket client = server.accept(); |
---|
210 | ProxyThread t = new ProxyThread(client, fwdServer, fwdPort); |
---|
211 | t.setDebug(debugLevel, debugOut); |
---|
212 | t.setTimeout(ptTimeout); |
---|
213 | t.start(); |
---|
214 | } |
---|
215 | } catch (Exception e) { |
---|
216 | if (debugLevel > 0) { |
---|
217 | debugOut.println("jProxy Thread error: " + e); |
---|
218 | } |
---|
219 | } |
---|
220 | |
---|
221 | closeSocket(); |
---|
222 | } |
---|
223 | } |
---|
224 | |
---|
225 | |
---|
226 | /* |
---|
227 | * The ProxyThread will take an HTTP request from the client |
---|
228 | * socket and send it to either the server that the client is |
---|
229 | * trying to contact, or another proxy server |
---|
230 | */ |
---|
231 | class ProxyThread extends Thread { |
---|
232 | private Socket pSocket; |
---|
233 | private String fwdServer = ""; |
---|
234 | private int fwdPort = 0; |
---|
235 | private int debugLevel = 0; |
---|
236 | private PrintStream debugOut = System.out; |
---|
237 | // the socketTimeout is used to time out the connection to |
---|
238 | // the remote server after a certain period of inactivity; |
---|
239 | // the value is in milliseconds -- use zero if you don't want |
---|
240 | // a timeout |
---|
241 | public static final int DEFAULT_TIMEOUT = 20 * 1000; |
---|
242 | private int socketTimeout = DEFAULT_TIMEOUT; |
---|
243 | |
---|
244 | public ProxyThread(Socket s) { |
---|
245 | pSocket = s; |
---|
246 | } |
---|
247 | |
---|
248 | public ProxyThread(Socket s, String proxy, int port) { |
---|
249 | pSocket = s; |
---|
250 | fwdServer = proxy; |
---|
251 | fwdPort = port; |
---|
252 | } |
---|
253 | |
---|
254 | public void setTimeout(int timeout) { |
---|
255 | // assume that the user will pass the timeout value |
---|
256 | // in seconds (because that's just more intuitive) |
---|
257 | socketTimeout = timeout * 1000; |
---|
258 | } |
---|
259 | |
---|
260 | public void setDebug(int level, PrintStream out) { |
---|
261 | debugLevel = level; |
---|
262 | debugOut = out; |
---|
263 | } |
---|
264 | |
---|
265 | public void run() { |
---|
266 | try { |
---|
267 | long startTime = System.currentTimeMillis(); |
---|
268 | |
---|
269 | // client streams (make sure you're using streams that use |
---|
270 | // byte arrays, so things like GIF and JPEG files and file |
---|
271 | // downloads will transfer properly) |
---|
272 | BufferedInputStream clientIn = new BufferedInputStream(pSocket.getInputStream()); |
---|
273 | BufferedOutputStream clientOut = new BufferedOutputStream(pSocket.getOutputStream()); |
---|
274 | |
---|
275 | // the socket to the remote server |
---|
276 | Socket server = null; |
---|
277 | |
---|
278 | // other variables |
---|
279 | byte[] request = null; |
---|
280 | byte[] response = null; |
---|
281 | int requestLength = 0; |
---|
282 | int responseLength = 0; |
---|
283 | int pos = -1; |
---|
284 | StringBuffer host = new StringBuffer(""); |
---|
285 | String hostName = ""; |
---|
286 | int hostPort = 80; |
---|
287 | |
---|
288 | // get the header info (the web browser won't disconnect after |
---|
289 | // it's sent a request, so make sure the waitForDisconnect |
---|
290 | // parameter is false) |
---|
291 | request = getHTTPData(clientIn, host, false); |
---|
292 | requestLength = Array.getLength(request); |
---|
293 | |
---|
294 | // separate the host name from the host port, if necessary |
---|
295 | // (like if it's "servername:8000") |
---|
296 | hostName = host.toString(); |
---|
297 | pos = hostName.indexOf(":"); |
---|
298 | if (pos > 0) { |
---|
299 | try { |
---|
300 | hostPort = Integer.parseInt(hostName.substring(pos + 1)); |
---|
301 | } catch (Exception e) { |
---|
302 | } |
---|
303 | hostName = hostName.substring(0, pos); |
---|
304 | } |
---|
305 | |
---|
306 | // either forward this request to another proxy server or |
---|
307 | // send it straight to the Host |
---|
308 | try { |
---|
309 | if ((fwdServer.length() > 0) && (fwdPort > 0)) { |
---|
310 | server = new Socket(fwdServer, fwdPort); |
---|
311 | } else { |
---|
312 | server = new Socket(hostName, hostPort); |
---|
313 | } |
---|
314 | } catch (Exception e) { |
---|
315 | // tell the client there was an error |
---|
316 | String errMsg = "HTTP/1.0 500\nContent Type: text/plain\n\n" |
---|
317 | + "Error connecting to the server:\n" + e + "\n"; |
---|
318 | clientOut.write(errMsg.getBytes(), 0, errMsg.length()); |
---|
319 | } |
---|
320 | |
---|
321 | if (server != null) { |
---|
322 | server.setSoTimeout(socketTimeout); |
---|
323 | BufferedInputStream serverIn = new BufferedInputStream(server.getInputStream()); |
---|
324 | BufferedOutputStream serverOut = new BufferedOutputStream(server.getOutputStream()); |
---|
325 | |
---|
326 | // send the request out |
---|
327 | serverOut.write(request, 0, requestLength); |
---|
328 | serverOut.flush(); |
---|
329 | |
---|
330 | // and get the response; if we're not at a debug level that |
---|
331 | // requires us to return the data in the response, just stream |
---|
332 | // it back to the client to save ourselves from having to |
---|
333 | // create and destroy an unnecessary byte array. Also, we |
---|
334 | // should set the waitForDisconnect parameter to 'true', |
---|
335 | // because some servers (like Google) don't always set the |
---|
336 | // Content-Length header field, so we have to listen until |
---|
337 | // they decide to disconnect (or the connection times out). |
---|
338 | if (debugLevel > 1) { |
---|
339 | response = getHTTPData(serverIn, true); |
---|
340 | responseLength = Array.getLength(response); |
---|
341 | } else { |
---|
342 | responseLength = streamHTTPData(serverIn, clientOut, true); |
---|
343 | } |
---|
344 | |
---|
345 | serverIn.close(); |
---|
346 | serverOut.close(); |
---|
347 | } |
---|
348 | |
---|
349 | // send the response back to the client, if we haven't already |
---|
350 | if (debugLevel > 1) { |
---|
351 | clientOut.write(response, 0, responseLength); |
---|
352 | } |
---|
353 | |
---|
354 | // if the user wants debug info, send them debug info; however, |
---|
355 | // keep in mind that because we're using threads, the output won't |
---|
356 | // necessarily be synchronous |
---|
357 | if (debugLevel > 5) { |
---|
358 | long endTime = System.currentTimeMillis(); |
---|
359 | debugOut.println("Request from " + pSocket.getInetAddress().getHostAddress() |
---|
360 | + " on Port " + pSocket.getLocalPort() |
---|
361 | + " to host " + hostName + ":" + hostPort |
---|
362 | + "\n (" + requestLength + " bytes sent, " |
---|
363 | + responseLength + " bytes returned, " |
---|
364 | + Long.toString(endTime - startTime) + " ms elapsed)"); |
---|
365 | debugOut.flush(); |
---|
366 | } |
---|
367 | if (debugLevel > 10) { |
---|
368 | debugOut.println("REQUEST:\n" + (new String(request))); |
---|
369 | debugOut.println("RESPONSE:\n" + (new String(response))); |
---|
370 | debugOut.flush(); |
---|
371 | } |
---|
372 | |
---|
373 | // close all the client streams so we can listen again |
---|
374 | clientOut.close(); |
---|
375 | clientIn.close(); |
---|
376 | pSocket.close(); |
---|
377 | } catch (Exception e) { |
---|
378 | if (debugLevel > 0) { |
---|
379 | debugOut.println("Error in ProxyThread: " + e); |
---|
380 | } |
---|
381 | //e.printStackTrace(); |
---|
382 | } |
---|
383 | |
---|
384 | } |
---|
385 | |
---|
386 | private byte[] getHTTPData(InputStream in, boolean waitForDisconnect) { |
---|
387 | // get the HTTP data from an InputStream, and return it as |
---|
388 | // a byte array |
---|
389 | // the waitForDisconnect parameter tells us what to do in case |
---|
390 | // the HTTP header doesn't specify the Content-Length of the |
---|
391 | // transmission |
---|
392 | StringBuffer foo = new StringBuffer(""); |
---|
393 | return getHTTPData(in, foo, waitForDisconnect); |
---|
394 | } |
---|
395 | |
---|
396 | private byte[] getHTTPData(InputStream in, StringBuffer host, boolean waitForDisconnect) { |
---|
397 | // get the HTTP data from an InputStream, and return it as |
---|
398 | // a byte array, and also return the Host entry in the header, |
---|
399 | // if it's specified -- note that we have to use a StringBuffer |
---|
400 | // for the 'host' variable, because a String won't return any |
---|
401 | // information when it's used as a parameter like that |
---|
402 | ByteArrayOutputStream bs = new ByteArrayOutputStream(); |
---|
403 | streamHTTPData(in, bs, host, waitForDisconnect); |
---|
404 | return bs.toByteArray(); |
---|
405 | } |
---|
406 | |
---|
407 | private int streamHTTPData(InputStream in, OutputStream out, boolean waitForDisconnect) { |
---|
408 | StringBuffer foo = new StringBuffer(""); |
---|
409 | return streamHTTPData(in, out, foo, waitForDisconnect); |
---|
410 | } |
---|
411 | |
---|
412 | private int streamHTTPData(InputStream in, OutputStream out, StringBuffer host, boolean waitForDisconnect) { |
---|
413 | // get the HTTP data from an InputStream, and send it to |
---|
414 | // the designated OutputStream |
---|
415 | StringBuffer header = new StringBuffer(""); |
---|
416 | String data = ""; |
---|
417 | int responseCode = 200; |
---|
418 | int contentLength = 0; |
---|
419 | int pos = -1; |
---|
420 | int byteCount = 0; |
---|
421 | String originalCookies = null; |
---|
422 | |
---|
423 | try { |
---|
424 | // get the first line of the header, so we know the response code |
---|
425 | data = readLine(in); |
---|
426 | if (data != null) { |
---|
427 | header.append(data + "\r\n"); |
---|
428 | pos = data.indexOf(" "); |
---|
429 | if ((data.toLowerCase().startsWith("http")) && (pos >= 0) && (data.indexOf(" ", pos + 1) >= 0)) { |
---|
430 | String rcString = data.substring(pos + 1, data.indexOf(" ", pos + 1)); |
---|
431 | try { |
---|
432 | responseCode = Integer.parseInt(rcString); |
---|
433 | } catch (Exception e) { |
---|
434 | if (debugLevel > 0) { |
---|
435 | debugOut.println("Error parsing response code " + rcString); |
---|
436 | } |
---|
437 | } |
---|
438 | } |
---|
439 | } |
---|
440 | |
---|
441 | // get the rest of the header info |
---|
442 | while ((data = readLine(in)) != null) { |
---|
443 | // the header ends at the first blank line |
---|
444 | if (data.length() == 0) { |
---|
445 | break; |
---|
446 | } |
---|
447 | //header.append(data + "\r\n"); //FMG commentlendi, cookie değiştireceğimiz için aşağıya taşıyorum |
---|
448 | |
---|
449 | // check for the Host header |
---|
450 | pos = data.toLowerCase().indexOf("host:"); |
---|
451 | if (pos >= 0) { |
---|
452 | host.setLength(0); |
---|
453 | host.append(data.substring(pos + 5).trim()); |
---|
454 | } |
---|
455 | |
---|
456 | // check for the Content-Length header |
---|
457 | pos = data.toLowerCase().indexOf("content-length:"); |
---|
458 | if (pos >= 0) { |
---|
459 | contentLength = Integer.parseInt(data.substring(pos + 15).trim()); |
---|
460 | } |
---|
461 | |
---|
462 | //************************************************************** |
---|
463 | //FMG>>: simulate browser (User Agent) cookie behaviour |
---|
464 | //We want the server beleive that we are a single browser. |
---|
465 | |
---|
466 | //Set-Cookie: Safari=cookieversion=2&portal=my&key=E894F897E4A4912E6D683D6939BE74D192731C8F4191A3ACAB6B3FEE16588D2954DBF3B9BF495294EE68A4477E3D772EAA5B0E89433D9926603960942389D153574A4D8BAB4095687832999AECDC2C751104CB8D1A30141A9BCD769E3A126390FFDD02DA9C28307232CD000C64D4F0C3D2993A357CCBED2A19E0467900E3884D71&sessionid=1a923806-a923-4442-9579-325c77ae39db&ref=Google&logged=true&oref=http%3a%2f%2fwww.google.com.tr%2furl%3fsa%3dt%26source%3dweb%26ct%3dres%26cd%3d1%26ved%3d0CAYQFjAA%26url%3dhttp%253A%252F%252Fmy.safaribooksonline.com%252F%26rct%3dj%26q%3dsafari%2bbook%26ei%3d2ZHNS_XcBIX0ObjplcwP%26usg%3dAFQjCNFeqvBpwDvMtcrCBnfHPPiUQofzPA; Path=/; Domain=my.safaribooksonline.com |
---|
467 | //Cookie: __utmv=77706120.B2C-BS-10-M-X; __utma=77706120.1457821667.1270626763.1271763865.1271767431.4; __utmb=77706120; __utmz=77706120.1271763865.3.2.utmccn=(organic)|utmcsr=google|utmctr=safari+book|utmcmd=organic; Safari=cookieversion=2&portal=my&key=E894F897E4A4912E6D683D6939BE74D192731C8F4191A3ACAB6B3FEE16588D2954DBF3B9BF495294EE68A4477E3D772EAA5B0E89433D9926603960942389D153574A4D8BAB4095687832999AECDC2C751104CB8D1A30141A9BCD769E3A126390FFDD02DA9C28307232CD000C64D4F0C3D2993A357CCBED2A19E0467900E3884D71&sessionid=1a923806-a923-4442-9579-325c77ae39db&ref=Google&logged=true&oref=http%3a%2f%2fwww.google.com.tr%2furl%3fsa%3dt%26source%3dweb%26ct%3dres%26cd%3d1%26ved%3d0CAYQFjAA%26url%3dhttp%253A%252F%252Fmy.safaribooksonline.com%252F%26rct%3dj%26q%3dsafari%2bbook%26ei%3d2ZHNS_XcBIX0ObjplcwP%26usg%3dAFQjCNFeqvBpwDvMtcrCBnfHPPiUQofzPA; __utmc=77706120; State=aph=LGOjKGanGVMDHURjGSHANHTCDRCFICGGFLNRPYPXOXVNCCJKAAWOeKHTXMIS&uicode=&PromoCode=my_promo_10&itemsperpage=10&savekey=CB68946AF5AC267A97B7C73B7F8A341F83A137D7B0C6094366303123865F960DD622F95860088400226D1FB16FFCF62ED34A33EFF50B6CC3&HttpReferrer=http%3a%2f%2fmy.safaribooksonline.com%2f0201835959&reader=&action=20&search=safari+book&view=book&displaygrbooks=1&xmlid=0201835959%2f5&isbn=0201835959&omniturexmlidown=1&imagepage=5&portal=my; s_cc=true; s_sq=%5B%5BB%5D%5D |
---|
468 | |
---|
469 | // check for the Set-Cookie header |
---|
470 | pos = data.toLowerCase().indexOf("set-cookie:"); |
---|
471 | if (pos >= 0) { |
---|
472 | String setCookie = data.substring(pos + 11).trim(); |
---|
473 | handleSetCookie(setCookie); |
---|
474 | } |
---|
475 | |
---|
476 | //YAP: cookie headerını iptal et, aşağıda biz gönderiyoruz çünkü |
---|
477 | pos = data.toLowerCase().indexOf("cookie:"); |
---|
478 | if (pos >= 0) { |
---|
479 | //we do not send original cookies |
---|
480 | originalCookies = data.substring(pos + 7); |
---|
481 | } else { |
---|
482 | header.append(data + "\r\n"); |
---|
483 | } |
---|
484 | |
---|
485 | //<<FMG |
---|
486 | //************************************************************** |
---|
487 | } |
---|
488 | |
---|
489 | //FMG>> |
---|
490 | //lastly send cookie if applicable for this host |
---|
491 | String cookie = getCookiesForHost(host.toString()); |
---|
492 | if (cookie != null) header.append(cookie + "\r\n"); |
---|
493 | if (originalCookies != null) System.out.println("\t _ookie:" + originalCookies); |
---|
494 | if (cookie == null && originalCookies != null) header.append("Cookie: " + originalCookies + "\r\n"); |
---|
495 | //<<FMG |
---|
496 | |
---|
497 | // add a blank line to terminate the header info |
---|
498 | header.append("\r\n"); |
---|
499 | |
---|
500 | // convert the header to a byte array, and write it to our stream |
---|
501 | out.write(header.toString().getBytes(), 0, header.length()); |
---|
502 | |
---|
503 | // if the header indicated that this was not a 200 response, |
---|
504 | // just return what we've got if there is no Content-Length, |
---|
505 | // because we may not be getting anything else |
---|
506 | if ((responseCode != 200) && (contentLength == 0)) { |
---|
507 | out.flush(); |
---|
508 | return header.length(); |
---|
509 | } |
---|
510 | |
---|
511 | // get the body, if any; we try to use the Content-Length header to |
---|
512 | // determine how much data we're supposed to be getting, because |
---|
513 | // sometimes the client/server won't disconnect after sending us |
---|
514 | // information... |
---|
515 | if (contentLength > 0) { |
---|
516 | waitForDisconnect = false; |
---|
517 | } |
---|
518 | |
---|
519 | if ((contentLength > 0) || (waitForDisconnect)) { |
---|
520 | try { |
---|
521 | byte[] buf = new byte[4096]; |
---|
522 | int bytesIn = 0; |
---|
523 | while (((byteCount < contentLength) || (waitForDisconnect)) |
---|
524 | && ((bytesIn = in.read(buf)) >= 0)) { |
---|
525 | out.write(buf, 0, bytesIn); |
---|
526 | byteCount += bytesIn; |
---|
527 | } |
---|
528 | } catch (Exception e) { |
---|
529 | String errMsg = "Error getting HTTP body: " + e; |
---|
530 | if (debugLevel > 0) { |
---|
531 | debugOut.println(errMsg); |
---|
532 | } |
---|
533 | //bs.write(errMsg.getBytes(), 0, errMsg.length()); |
---|
534 | } |
---|
535 | } |
---|
536 | } catch (Exception e) { |
---|
537 | if (debugLevel > 0) { |
---|
538 | debugOut.println("Error getting HTTP data: " + e); |
---|
539 | } |
---|
540 | e.printStackTrace(); |
---|
541 | } |
---|
542 | |
---|
543 | //flush the OutputStream and return |
---|
544 | try { |
---|
545 | out.flush(); |
---|
546 | } catch (Exception e) { |
---|
547 | } |
---|
548 | return (header.length() + byteCount); |
---|
549 | } |
---|
550 | |
---|
551 | private String readLine(InputStream in) { |
---|
552 | // reads a line of text from an InputStream |
---|
553 | StringBuffer data = new StringBuffer(""); |
---|
554 | int c; |
---|
555 | |
---|
556 | try { |
---|
557 | // if we have nothing to read, just return null |
---|
558 | in.mark(1); |
---|
559 | if (in.read() == -1) { |
---|
560 | return null; |
---|
561 | } else { |
---|
562 | in.reset(); |
---|
563 | } |
---|
564 | |
---|
565 | while ((c = in.read()) >= 0) { |
---|
566 | // check for an end-of-line character |
---|
567 | if ((c == 0) || (c == 10) || (c == 13)) { |
---|
568 | break; |
---|
569 | } else { |
---|
570 | data.append((char)c); |
---|
571 | } |
---|
572 | } |
---|
573 | |
---|
574 | // deal with the case where the end-of-line terminator is \r\n |
---|
575 | if (c == 13) { |
---|
576 | in.mark(1); |
---|
577 | if (in.read() != 10) { |
---|
578 | in.reset(); |
---|
579 | } |
---|
580 | } |
---|
581 | } catch (Exception e) { |
---|
582 | if (debugLevel > 0) { |
---|
583 | debugOut.println("Error getting header: " + e); |
---|
584 | } |
---|
585 | e.printStackTrace(); |
---|
586 | } |
---|
587 | |
---|
588 | // and return what we have |
---|
589 | return data.toString(); |
---|
590 | } |
---|
591 | |
---|
592 | //FMG>> |
---|
593 | //We are simulating the User Agent role as in RFC2965 |
---|
594 | //the cookies coming from server, for a host |
---|
595 | private void handleSetCookie(String setCookie) { |
---|
596 | //global cookie map for each domain |
---|
597 | Map cookieMap = SimpleProxy.cookieMap; |
---|
598 | |
---|
599 | //parsed attribute value pair for setCookie (we should not send Domain, Path, Expires cookies back to server, so remove them) |
---|
600 | Map cookieValues = parseCookies(setCookie); |
---|
601 | String domain = (String)cookieValues.remove("Domain"); |
---|
602 | if (domain == null) domain = (String)cookieValues.remove("domain"); |
---|
603 | if (domain == null) domain = ""; |
---|
604 | cookieValues.remove("Path"); |
---|
605 | cookieValues.remove("Expires"); |
---|
606 | cookieValues.remove("path"); |
---|
607 | cookieValues.remove("expires"); |
---|
608 | |
---|
609 | //get cookies for this domain |
---|
610 | Map cookiesForDomain = (Map)cookieMap.get(domain); |
---|
611 | //create if not exists |
---|
612 | if (cookiesForDomain == null) cookiesForDomain = new ConcurrentHashMap(); |
---|
613 | //put & override the existing values |
---|
614 | cookiesForDomain.putAll(cookieValues); |
---|
615 | //set cookies for this host |
---|
616 | cookieMap.put(domain, cookiesForDomain); |
---|
617 | |
---|
618 | if (debugLevel > 0) { |
---|
619 | System.out.println(">>>> Got new cookie for domain: '" + domain); |
---|
620 | Iterator it = cookiesForDomain.keySet().iterator(); |
---|
621 | while (it.hasNext()) { |
---|
622 | String key = (String)it.next(); |
---|
623 | System.out.print("\tKey: " + key); |
---|
624 | System.out.println(" Value: " + cookiesForDomain.get(key)); |
---|
625 | } |
---|
626 | } |
---|
627 | |
---|
628 | } |
---|
629 | |
---|
630 | private Map parseCookies(String cookies) { |
---|
631 | Map result = new HashMap(); |
---|
632 | String[] cookieArray = cookies.split(";"); |
---|
633 | for (int i = 0; i < cookieArray.length; i++) { |
---|
634 | String attributeValue = cookieArray[i]; |
---|
635 | int eqIndex = attributeValue.indexOf("="); |
---|
636 | if (eqIndex == -1) continue; |
---|
637 | String attribute = attributeValue.substring(0, eqIndex); |
---|
638 | String value = attributeValue.substring(eqIndex + 1); |
---|
639 | result.put(attribute.trim(), value.trim()); |
---|
640 | } |
---|
641 | |
---|
642 | return result; |
---|
643 | } |
---|
644 | |
---|
645 | //returns the cookies to be sent for a host |
---|
646 | private String getCookiesForHost(String host) { |
---|
647 | //global cookie map for each domain |
---|
648 | Map cookieMap = SimpleProxy.cookieMap; |
---|
649 | |
---|
650 | //get cookies for this domain |
---|
651 | Map cookiesForDomain = (Map)cookieMap.get(host); |
---|
652 | if (cookiesForDomain == null) return null; |
---|
653 | |
---|
654 | StringBuffer cookie = new StringBuffer(); |
---|
655 | cookie.append("Cookie: "); |
---|
656 | |
---|
657 | Iterator it = cookiesForDomain.keySet().iterator(); |
---|
658 | while (it.hasNext()) { |
---|
659 | String key = (String)it.next(); |
---|
660 | cookie.append(key); |
---|
661 | cookie.append("="); |
---|
662 | cookie.append(cookiesForDomain.get(key)); |
---|
663 | if (it.hasNext()) cookie.append(";"); |
---|
664 | } |
---|
665 | |
---|
666 | if (debugLevel > 0) { |
---|
667 | System.out.println("Sending cookie for host: " + host); |
---|
668 | System.out.println("\t " + cookie.toString()); |
---|
669 | } |
---|
670 | |
---|
671 | |
---|
672 | return cookie.toString(); |
---|
673 | } |
---|
674 | } |
---|