2 * Copyright (C) 2010 Felix Bechstein
4 * This file is part of AdBlock.
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU General Public License as published by the Free Software
8 * Foundation; either version 3 of the License, or (at your option) any later
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * You should have received a copy of the GNU General Public License along with
17 * this program; If not, see <http://www.gnu.org/licenses/>.
19 package de
.ub0r
.android
.adBlock
;
21 import java
.io
.BufferedInputStream
;
22 import java
.io
.BufferedWriter
;
23 import java
.io
.IOException
;
24 import java
.io
.InputStream
;
25 import java
.io
.OutputStream
;
26 import java
.io
.OutputStreamWriter
;
27 import java
.net
.InetSocketAddress
;
28 import java
.net
.ServerSocket
;
29 import java
.net
.Socket
;
31 import java
.util
.ArrayList
;
33 import android
.app
.Notification
;
34 import android
.app
.NotificationManager
;
35 import android
.app
.PendingIntent
;
36 import android
.app
.Service
;
37 import android
.content
.Context
;
38 import android
.content
.Intent
;
39 import android
.content
.SharedPreferences
;
40 import android
.os
.IBinder
;
41 import android
.preference
.PreferenceManager
;
42 import android
.util
.Log
;
43 import android
.widget
.Toast
;
46 * This ad blocking Proxy Service will work as an ordinary HTTP proxy. Set APN's
47 * proxy preferences to proxy's connection parameters.
49 * @author Felix Bechstein
51 public class Proxy
extends Service
implements Runnable
{
52 /** Tag for output. */
53 private static final String TAG
= "AdBlock.Proxy";
55 /** Preferences: Port. */
56 static final String PREFS_PORT
= "port";
57 /** Preferences: Filter. */
58 static final String PREFS_FILTER
= "filter";
60 /** HTTP Response: blocked. */
61 private static final String HTTP_BLOCK
= "HTTP/1.1 500 blocked by AdBlock";
62 /** HTTP Response: error. */
63 private static final String HTTP_ERROR
= "HTTP/1.1 500 error by AdBlock";
64 /** HTTP Response: connected. */
65 private static final String HTTP_CONNECTED
= "HTTP/1.1 200 connected";
66 /** HTTP Response: flush. */
67 private static final String HTTP_RESPONSE
= "\n\n";
69 /** Default Port for HTTP. */
70 private static final int PORT_HTTP
= 80;
71 /** Default Port for HTTPS. */
72 private static final int PORT_HTTPS
= 443;
75 private Thread proxy
= null;
77 private int port
= -1;
78 /** Proxy's filter. */
79 ArrayList
<String
> filter
= new ArrayList
<String
>();
81 private boolean stop
= false;
84 * Connection handles a single HTTP Connection. Run this as a Thread.
86 * @author Felix Bechstein
88 private class Connection
implements Runnable
{
91 // no private object.refs accessed by inner classes
92 // TODO: reduce object creation
95 private final Socket local
;
97 private Socket remote
;
100 private static final short STATE_NORMAL
= 0;
101 /** State: closed by local side. */
102 private static final short STATE_CLOSED_IN
= 1;
103 /** State: closed by remote side. */
104 private static final short STATE_CLOSED_OUT
= 2;
105 /** Connections state. */
106 private short state
= STATE_NORMAL
;
109 * CopyStream reads one stream and writes it's data into an other
110 * stream. Run this as a Thread.
112 * @author Felix Bechstein
114 private class CopyStream
implements Runnable
{
116 private final InputStream reader
;
118 private final OutputStream writer
;
120 /** Size of buffer. */
121 private static final int BUFFSIZE
= 32768;
122 /** Size of header buffer. */
123 private static final int HEADERBUFFSIZE
= 1024;
133 public CopyStream(final InputStream r
, final OutputStream w
) {
134 this.reader
= new BufferedInputStream(r
, BUFFSIZE
);
139 * Run by Thread.start().
143 byte[] buf
= new byte[BUFFSIZE
];
145 final InputStream r
= this.reader
;
146 final OutputStream w
= this.writer
;
149 read
= r
.available();
150 if (read
< 1 || read
> BUFFSIZE
) {
153 read
= r
.read(buf
, 0, read
);
157 w
.write(buf
, 0, read
);
158 if (r
.available() < 1) {
162 Connection
.this.close(Connection
.STATE_CLOSED_OUT
);
163 // this.writer.close();
164 } catch (IOException e
) {
165 // FIXME: java.net.SocketException: Broken pipe
166 // no idea, what causes this :/
167 // Connection c = Connection.this;
168 // String s = new String(buf, 0, read);
180 public Connection(final Socket socket
) {
185 * Check if URL is blocked.
189 * @return if URL is blocked?
191 private boolean checkURL(final String url
) {
192 if (url
.indexOf("admob") >= 0 || url
.indexOf("google") >= 0) {
195 final ArrayList
<String
> f
= Proxy
.this.filter
;
196 final int s
= f
.size();
197 for (int i
= 0; i
< s
; i
++) {
198 if (url
.indexOf(f
.get(i
)) >= 0) {
206 * Read in HTTP Header. Parse for URL to connect to.
209 * buffer reader from which we read the header
211 * buffer into which the header is written
212 * @return URL to which we should connect, port other than 80 is given
214 * @throws IOException
217 private URL
readHeader(final BufferedInputStream reader
,
218 final StringBuilder buffer
) throws IOException
{
222 byte[] buf
= new byte[CopyStream
.HEADERBUFFSIZE
];
224 if (this.state
== STATE_CLOSED_OUT
) {
227 avail
= reader
.available();
228 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
229 avail
= CopyStream
.HEADERBUFFSIZE
;
230 } else if (avail
== 0) {
231 avail
= CopyStream
.HEADERBUFFSIZE
;
233 avail
= reader
.read(buf
, 0, avail
);
237 String line
= new String(buf
, 0, avail
);
238 String testLine
= line
;
239 int i
= line
.indexOf(" http://");
241 // remove "http://host:port" from line
242 int j
= line
.indexOf('/', i
+ 9);
244 testLine
= line
.substring(0, i
+ 1) + line
.substring(j
);
247 buffer
.append(testLine
);
248 strings
= line
.split(" ");
249 if (strings
.length
> 1) {
250 if (strings
[0].equals("CONNECT")) {
251 String targetHost
= strings
[1];
252 int targetPort
= PORT_HTTPS
;
253 strings
= targetHost
.split(":");
254 if (strings
.length
> 1) {
255 targetPort
= Integer
.parseInt(strings
[1]);
256 targetHost
= strings
[0];
258 ret
= new URL("https://" + targetHost
+ ":" + targetPort
);
259 } else if (strings
[0].equals("GET")
260 || strings
[0].equals("POST")) {
262 if (strings
[1].startsWith("http://")) {
263 ret
= new URL(strings
[1]);
264 path
= ret
.getPath();
269 String lastLine
= line
;
271 testLine
= lastLine
+ line
;
272 i
= testLine
.indexOf("\nHost: ");
274 int j
= testLine
.indexOf("\n", i
+ 6);
276 String tHost
= testLine
.substring(i
+ 6, j
)
278 ret
= new URL("http://" + tHost
+ path
);
281 // test for "Host:" again with longer buffer
282 line
= lastLine
+ line
;
285 if (line
.indexOf("\r\n\r\n") >= 0) {
289 avail
= reader
.available();
291 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
292 avail
= CopyStream
.HEADERBUFFSIZE
;
294 avail
= reader
.read(buf
, 0, avail
);
295 // FIXME: this may break
296 line
= new String(buf
, 0, avail
);
301 Log
.d(TAG
, "unknown method: " + strings
[0]);
306 // copy rest of reader's buffer
307 avail
= reader
.available();
309 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
310 avail
= CopyStream
.HEADERBUFFSIZE
;
312 avail
= reader
.read(buf
, 0, avail
);
313 // FIXME: this may break!
314 buffer
.append(new String(buf
, 0, avail
));
315 avail
= reader
.available();
321 * Close local and remote socket.
326 * @throws IOException
329 private synchronized short close(final short nextState
)
331 Log
.d(TAG
, "close(" + nextState
+ ")");
332 short mState
= this.state
;
333 if (mState
== STATE_NORMAL
|| nextState
== STATE_NORMAL
) {
337 if (mState
!= STATE_NORMAL
) {
338 // close remote socket
339 mSocket
= this.remote
;
340 if (mSocket
!= null && mSocket
.isConnected()) {
342 mSocket
.shutdownInput();
343 mSocket
.shutdownOutput();
344 } catch (IOException e
) {
345 // Log.e(TAG, null, e);
351 if (mState
== STATE_CLOSED_OUT
) {
352 // close local socket
353 mSocket
= this.local
;
354 if (mSocket
.isConnected()) {
356 mSocket
.shutdownOutput();
357 mSocket
.shutdownInput();
358 } catch (IOException e
) {
359 // Log.e(TAG, null, e);
373 BufferedInputStream lInStream
;
374 OutputStream lOutStream
;
375 BufferedWriter lWriter
;
377 lInStream
= new BufferedInputStream(
378 this.local
.getInputStream(), CopyStream
.BUFFSIZE
);
379 lOutStream
= this.local
.getOutputStream();
380 lWriter
= new BufferedWriter(
381 new OutputStreamWriter(lOutStream
), CopyStream
.BUFFSIZE
);
382 } catch (IOException e
) {
387 InputStream rInStream
= null;
388 OutputStream rOutStream
= null;
389 BufferedWriter remoteWriter
= null;
390 Thread rThread
= null;
391 StringBuilder buffer
= new StringBuilder();
392 boolean block
= false;
396 boolean connectSSL
= false;
397 while (this.local
.isConnected()) {
398 buffer
= new StringBuilder();
399 url
= this.readHeader(lInStream
, buffer
);
400 if (buffer
.length() == 0) {
403 if (this.local
.isConnected() && rThread
!= null
404 && !rThread
.isAlive()) {
405 // socket should be closed allready..
406 Log
.d(TAG
, "close dead remote");
416 block
= this.checkURL(url
.toString());
417 Log
.d(TAG
, "new url: " + url
.toString());
419 // new connection needed?
420 int p
= url
.getPort();
424 if (tHost
== null || !tHost
.equals(url
.getHost())
426 // create new connection
427 Log
.d(TAG
, "shutdown old remote");
428 this.close(STATE_CLOSED_IN
);
429 if (rThread
!= null) {
434 tHost
= url
.getHost();
436 Log
.d(TAG
, "new socket: " + url
.toString());
437 this.state
= STATE_NORMAL
;
438 this.remote
= new Socket();
439 this.remote
.connect(new InetSocketAddress(
441 rInStream
= this.remote
.getInputStream();
442 rOutStream
= this.remote
.getOutputStream();
443 rThread
= new Thread(new CopyStream(rInStream
,
446 if (url
.getProtocol().startsWith("https")) {
448 lWriter
.write(HTTP_CONNECTED
451 // copy local to remote by blocks
452 Thread t2
= new Thread(new CopyStream(
453 lInStream
, rOutStream
));
457 break; // copy in separate thread. break
460 remoteWriter
= new BufferedWriter(
461 new OutputStreamWriter(rOutStream
),
462 CopyStream
.BUFFSIZE
);
467 // push data to remote if not blocked
469 lWriter
.append(HTTP_BLOCK
+ HTTP_RESPONSE
470 + "BLOCKED by AdBlock!");
473 Socket mSocket
= this.remote
;
474 if (mSocket
!= null && mSocket
.isConnected()
475 && remoteWriter
!= null) {
477 remoteWriter
.append(buffer
);
478 remoteWriter
.flush();
479 } catch (IOException e
) {
480 Log
.d(TAG
, buffer
.toString(), e
);
485 if (rThread
!= null && rThread
.isAlive()) {
488 } catch (InterruptedException e
) {
490 } catch (IOException e
) {
493 lWriter
.append(HTTP_ERROR
+ " - " + e
.toString()
494 + HTTP_RESPONSE
+ e
.toString());
498 } catch (IOException e1
) {
499 Log
.e(TAG
, null, e1
);
502 Log
.d(TAG
, "close connection");
510 public final IBinder
onBind(final Intent intent
) {
518 public final void onStart(final Intent intent
, final int startId
) {
519 super.onStart(intent
, startId
);
521 HelperAPI5 helperAPI5
= null;
523 helperAPI5
= new HelperAPI5();
524 if (!helperAPI5
.isAvailable()) {
527 } catch (VerifyError e
) {
529 Log
.i(TAG
, "no api 5");
533 if (helperAPI5
== null) {
534 this.setForeground(true);
536 final Notification notification
= new Notification(
537 R
.drawable
.stat_notify_proxy
, "", System
538 .currentTimeMillis());
539 final PendingIntent contentIntent
= PendingIntent
.getActivity(this,
540 0, new Intent(this, AdBlock
.class), 0);
541 notification
.setLatestEventInfo(this, this
542 .getString(R
.string
.notify_proxy
), "", contentIntent
);
543 notification
.defaults
|= Notification
.FLAG_NO_CLEAR
;
546 SharedPreferences preferences
= PreferenceManager
547 .getDefaultSharedPreferences(this);
548 int p
= Integer
.parseInt(preferences
.getString(PREFS_PORT
, "8080"));
549 boolean portChanged
= p
!= this.port
;
552 String f
= preferences
.getString(PREFS_FILTER
, "");
553 final ArrayList
<String
> fl
= this.filter
;
555 for (String s
: f
.split("\n")) {
556 if (s
.length() > 0) {
560 if (this.proxy
== null) {
561 // Toast.makeText(this, "starting proxy on port: " + this.port,
562 // Toast.LENGTH_SHORT).show();
563 final Thread pr
= new Thread(this);
568 this.getString(R
.string
.proxy_running
) + " " + this.port
,
569 Toast
.LENGTH_SHORT
).show();
571 Thread pr
= this.proxy
;
573 pr
= new Thread(this);
584 public final void onDestroy() {
586 Toast
.makeText(this, R
.string
.proxy_stopped
, Toast
.LENGTH_LONG
).show();
588 ((NotificationManager
) this
589 .getSystemService(Context
.NOTIFICATION_SERVICE
)).cancelAll();
596 public final void run() {
599 ServerSocket sock
= new ServerSocket(p
);
601 while (!this.stop
&& p
== this.port
) {
602 if (p
!= this.port
) {
605 client
= sock
.accept();
606 if (client
!= null) {
607 Log
.d(TAG
, "new client");
608 Thread t
= new Thread(new Connection(client
));
613 } catch (IOException e
) {