2 * Copyright (C) 2009 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
{
53 /** Preferences: Port. */
54 static final String PREFS_PORT
= "port";
55 /** Preferences: Filter. */
56 static final String PREFS_FILTER
= "filter";
58 /** HTTP Response: blocked. */
59 private static final String HTTP_BLOCK
= "HTTP/1.1 500 blocked by AdBlock";
60 /** HTTP Response: error. */
61 private static final String HTTP_ERROR
= "HTTP/1.1 500 error by AdBlock";
62 /** HTTP Response: connected. */
63 private static final String HTTP_CONNECTED
= "HTTP/1.1 200 connected";
64 /** HTTP Response: flush. */
65 private static final String HTTP_RESPONSE
= "\n\n";
67 /** Default Port for HTTP. */
68 private static final int PORT_HTTP
= 80;
69 /** Default Port for HTTPS. */
70 private static final int PORT_HTTPS
= 443;
73 private Thread proxy
= null;
75 private int port
= -1;
76 /** Proxy's filter. */
77 private ArrayList
<String
> filter
= new ArrayList
<String
>();
79 private boolean stop
= false;
81 /** Tag for output. */
82 private static final String TAG
= "AdBlock.Proxy";
85 * Connection handles a single HTTP Connection. Run this as a Thread.
87 * @author Felix Bechstein
89 class Connection
implements Runnable
{
91 // TODO: cache object.refs
92 // TODO: no private object.refs accessed by inner classes
93 // TODO: reduce object creation
96 private final Socket local
;
98 private Socket remote
;
100 /** State: normal. */
101 private static final short STATE_NORMAL
= 0;
102 /** State: closed by local side. */
103 private static final short STATE_CLOSED_IN
= 1;
104 /** State: closed by remote side. */
105 private static final short STATE_CLOSED_OUT
= 2;
106 /** Connections state. */
107 private short state
= STATE_NORMAL
;
110 * CopyStream reads one stream and writes it's data into an other
111 * stream. Run this as a Thread.
113 * @author Felix Bechstein
115 private class CopyStream
implements Runnable
{
117 private final InputStream reader
;
119 private final OutputStream writer
;
121 /** Size of buffer. */
122 private static final int BUFFSIZE
= 32768;
123 /** Size of header buffer. */
124 private static final int HEADERBUFFSIZE
= 1024;
134 public CopyStream(final InputStream r
, final OutputStream w
) {
135 this.reader
= new BufferedInputStream(r
, BUFFSIZE
);
140 * Run by Thread.start().
144 byte[] buf
= new byte[BUFFSIZE
];
148 read
= this.reader
.available();
149 if (read
< 1 || read
> BUFFSIZE
) {
152 read
= this.reader
.read(buf
, 0, read
);
156 this.writer
.write(buf
, 0, read
);
157 if (this.reader
.available() < 1) {
161 Connection
.this.close(Connection
.STATE_CLOSED_OUT
);
162 // this.writer.close();
163 } catch (IOException e
) {
164 // FIXME: java.net.SocketException: Broken pipe
165 // no idea, what causes this :/
166 // Connection c = Connection.this;
167 // String s = new String(buf, 0, read);
179 public Connection(final Socket socket
) {
184 * Check if URL is blocked.
188 * @return if URL is blocked?
190 private boolean checkURL(final String url
) {
191 if (url
.indexOf("admob") >= 0 || url
.indexOf("google") >= 0) {
194 for (String f
: Proxy
.this.filter
) {
195 if (url
.indexOf(f
) >= 0) {
203 * Read in HTTP Header. Parse for URL to connect to.
206 * buffer reader from which we read the header
208 * buffer into which the header is written
209 * @return URL to which we should connect, port other than 80 is given
211 * @throws IOException
214 private URL
readHeader(final BufferedInputStream reader
,
215 final StringBuilder buffer
) throws IOException
{
219 byte[] buf
= new byte[CopyStream
.HEADERBUFFSIZE
];
221 if (this.state
== STATE_CLOSED_OUT
) {
224 avail
= reader
.available();
225 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
226 avail
= CopyStream
.HEADERBUFFSIZE
;
227 } else if (avail
== 0) {
228 avail
= CopyStream
.HEADERBUFFSIZE
;
230 avail
= reader
.read(buf
, 0, avail
);
234 String line
= new String(buf
, 0, avail
);
235 String testLine
= line
;
236 int i
= line
.indexOf(" http://");
238 // remove "http://host:port" from line
239 int j
= line
.indexOf('/', i
+ 9);
241 testLine
= line
.substring(0, i
+ 1) + line
.substring(j
);
244 buffer
.append(testLine
);
245 strings
= line
.split(" ");
246 if (strings
.length
> 1) {
247 if (strings
[0].equals("CONNECT")) {
248 String targetHost
= strings
[1];
249 int targetPort
= PORT_HTTPS
;
250 strings
= targetHost
.split(":");
251 if (strings
.length
> 1) {
252 targetPort
= Integer
.parseInt(strings
[1]);
253 targetHost
= strings
[0];
255 ret
= new URL("https://" + targetHost
+ ":" + targetPort
);
256 } else if (strings
[0].equals("GET")
257 || strings
[0].equals("POST")) {
259 if (strings
[1].startsWith("http://")) {
260 ret
= new URL(strings
[1]);
261 path
= ret
.getPath();
266 String lastLine
= line
;
268 testLine
= lastLine
+ line
;
269 i
= testLine
.indexOf("\nHost: ");
271 int j
= testLine
.indexOf("\n", i
+ 6);
273 String tHost
= testLine
.substring(i
+ 6, j
)
275 ret
= new URL("http://" + tHost
+ path
);
278 // test for "Host:" again with longer buffer
279 line
= lastLine
+ line
;
282 if (line
.indexOf("\r\n\r\n") >= 0) {
286 avail
= reader
.available();
288 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
289 avail
= CopyStream
.HEADERBUFFSIZE
;
291 avail
= reader
.read(buf
, 0, avail
);
292 // FIXME: this may break
293 line
= new String(buf
, 0, avail
);
298 Log
.d(TAG
, "unknown method: " + strings
[0]);
303 // copy rest of reader's buffer
304 avail
= reader
.available();
306 if (avail
> CopyStream
.HEADERBUFFSIZE
) {
307 avail
= CopyStream
.HEADERBUFFSIZE
;
309 avail
= reader
.read(buf
, 0, avail
);
310 // FIXME: this may break!
311 buffer
.append(new String(buf
, 0, avail
));
312 avail
= reader
.available();
318 * Close local and remote socket.
323 * @throws IOException
326 private synchronized short close(final short nextState
)
328 Log
.d(TAG
, "close(" + nextState
+ ")");
329 short mState
= this.state
;
330 if (mState
== STATE_NORMAL
|| nextState
== STATE_NORMAL
) {
334 if (mState
!= STATE_NORMAL
) {
335 // close remote socket
336 mSocket
= this.remote
;
337 if (mSocket
!= null && mSocket
.isConnected()) {
339 mSocket
.shutdownInput();
340 mSocket
.shutdownOutput();
341 } catch (IOException e
) {
342 // Log.e(TAG, null, e);
348 if (mState
== STATE_CLOSED_OUT
) {
349 // close local socket
350 mSocket
= this.local
;
351 if (mSocket
.isConnected()) {
353 mSocket
.shutdownOutput();
354 mSocket
.shutdownInput();
355 } catch (IOException e
) {
356 // Log.e(TAG, null, e);
370 BufferedInputStream lInStream
;
371 OutputStream lOutStream
;
372 BufferedWriter lWriter
;
374 lInStream
= new BufferedInputStream(
375 this.local
.getInputStream(), CopyStream
.BUFFSIZE
);
376 lOutStream
= this.local
.getOutputStream();
377 lWriter
= new BufferedWriter(
378 new OutputStreamWriter(lOutStream
), CopyStream
.BUFFSIZE
);
379 } catch (IOException e
) {
384 InputStream rInStream
= null;
385 OutputStream rOutStream
= null;
386 BufferedWriter remoteWriter
= null;
387 Thread rThread
= null;
388 StringBuilder buffer
= new StringBuilder();
389 boolean block
= false;
393 boolean connectSSL
= false;
394 while (this.local
.isConnected()) {
395 buffer
= new StringBuilder();
396 url
= this.readHeader(lInStream
, buffer
);
397 if (buffer
.length() == 0) {
400 if (this.local
.isConnected() && rThread
!= null
401 && !rThread
.isAlive()) {
402 // TODO: is this a dead branch? if rThread is dead,
403 // socket should be closed allready..
404 Log
.d(TAG
, "close dead remote");
414 block
= this.checkURL(url
.toString());
415 Log
.d(TAG
, "new url: " + url
.toString());
417 // new connection needed?
418 int p
= url
.getPort();
422 if (tHost
== null || !tHost
.equals(url
.getHost())
424 // create new connection
425 Log
.d(TAG
, "shutdown old remote");
426 this.close(STATE_CLOSED_IN
);
427 if (rThread
!= null) {
432 tHost
= url
.getHost();
434 Log
.d(TAG
, "new socket: " + url
.toString());
435 this.state
= STATE_NORMAL
;
436 this.remote
= new Socket();
437 this.remote
.connect(new InetSocketAddress(
439 rInStream
= this.remote
.getInputStream();
440 rOutStream
= this.remote
.getOutputStream();
441 rThread
= new Thread(new CopyStream(rInStream
,
444 if (url
.getProtocol().startsWith("https")) {
446 lWriter
.write(HTTP_CONNECTED
449 // copy local to remote by blocks
450 Thread t2
= new Thread(new CopyStream(
451 lInStream
, rOutStream
));
455 break; // copy in separate thread. break
458 remoteWriter
= new BufferedWriter(
459 new OutputStreamWriter(rOutStream
),
460 CopyStream
.BUFFSIZE
);
465 // push data to remote if not blocked
467 lWriter
.append(HTTP_BLOCK
+ HTTP_RESPONSE
468 + "BLOCKED by AdBlock!");
471 Socket mSocket
= this.remote
;
472 if (mSocket
!= null && mSocket
.isConnected()
473 && remoteWriter
!= null) {
475 remoteWriter
.append(buffer
);
476 remoteWriter
.flush();
477 } catch (IOException e
) {
478 Log
.d(TAG
, buffer
.toString(), e
);
480 // FIXME: exceptions here!
481 // sync does not fix anything
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
);
522 this.setForeground(true);
523 final Notification notification
= new Notification(
524 R
.drawable
.stat_notify_proxy
, "", System
.currentTimeMillis());
525 final PendingIntent contentIntent
= PendingIntent
.getActivity(this, 0,
526 new Intent(this, AdBlock
.class), 0);
527 notification
.setLatestEventInfo(this, this
528 .getString(R
.string
.notify_proxy
), "", contentIntent
);
529 notification
.defaults
|= Notification
.FLAG_NO_CLEAR
;
531 new HelperAPI5().startForeground(this, 0, notification
);
532 } catch (VerifyError e
) {
533 Log
.i(TAG
, "no api 5");
536 SharedPreferences preferences
= PreferenceManager
537 .getDefaultSharedPreferences(this);
538 int p
= Integer
.parseInt(preferences
.getString(PREFS_PORT
, "8080"));
539 boolean portChanged
= p
!= this.port
;
542 String f
= preferences
.getString(PREFS_FILTER
, "");
544 for (String s
: f
.split("\n")) {
545 if (s
.length() > 0) {
549 if (this.proxy
== null) {
550 // Toast.makeText(this, "starting proxy on port: " + this.port,
551 // Toast.LENGTH_SHORT).show();
552 this.proxy
= new Thread(this);
556 this.getString(R
.string
.proxy_running
) + " " + this.port
,
557 Toast
.LENGTH_SHORT
).show();
559 this.proxy
.interrupt();
560 this.proxy
= new Thread(this);
570 public final void onDestroy() {
572 Toast
.makeText(this, R
.string
.proxy_stopped
, Toast
.LENGTH_LONG
).show();
574 ((NotificationManager
) this
575 .getSystemService(Context
.NOTIFICATION_SERVICE
)).cancelAll();
582 public final void run() {
585 ServerSocket sock
= new ServerSocket(p
);
587 while (!this.stop
&& p
== this.port
) {
588 if (p
!= this.port
) {
591 client
= sock
.accept();
592 if (client
!= null) {
593 Log
.d(TAG
, "new client");
594 Thread t
= new Thread(new Connection(client
));
599 } catch (IOException e
) {