Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: src/org/adblockplus/android/ProxyService.java

Issue 8484110: ABP/Android proxy service (Closed)
Patch Set: ABP/Android proxy service Created Nov. 12, 2012, 8:53 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 package org.adblockplus.android;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.IOException;
6 import java.lang.reflect.Method;
7 import java.net.InetAddress;
8 import java.net.ServerSocket;
9 import java.util.List;
10 import java.util.Properties;
11 import java.util.concurrent.TimeoutException;
12
13 import sunlabs.brazil.server.Server;
14 import sunlabs.brazil.util.Base64;
15 import android.app.Notification;
16 import android.app.NotificationManager;
17 import android.app.PendingIntent;
18 import android.app.Service;
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 import android.content.SharedPreferences;
24 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
25 import android.content.pm.PackageManager.NameNotFoundException;
26 import android.net.ConnectivityManager;
27 import android.net.NetworkInfo;
28 import android.os.Binder;
29 import android.os.Build;
30 import android.os.Handler;
31 import android.os.IBinder;
32 import android.preference.PreferenceManager;
33 import android.util.Log;
34 import android.widget.Toast;
35
36 import com.stericson.RootTools.RootTools;
37 import com.stericson.RootTools.RootToolsException;
38
39 public class ProxyService extends Service implements OnSharedPreferenceChangeLis tener
40 {
41 private static final String LOCALHOST = "127.0.0.1";
42 /**
43 * Indicates that system supports native proxy configuration.
44 */
45 public static boolean hasNativeProxy = Build.VERSION.SDK_INT >= 12; // Honeyco mb 3.1
46
47 static
48 {
49 RootTools.debugMode = false;
50 }
51
52 private static final String TAG = "ProxyService";
53 private static final boolean logRequests = false;
54
55 private final static int DEFAULT_TIMEOUT = 3000;
56 private final static int NO_TRAFFIC_TIMEOUT = 5 * 60 * 1000; // 5 minutes
57
58 final static int ONGOING_NOTIFICATION_ID = R.string.app_name;
59 private final static int NOTRAFFIC_NOTIFICATION_ID = R.string.app_name + 3;
60
61 /**
62 * Broadcasted when service starts or stops.
63 */
64 public final static String BROADCAST_STATE_CHANGED = "org.adblockplus.android. service.state";
65 /**
66 * Broadcasted if proxy fails to start.
67 */
68 public final static String BROADCAST_PROXY_FAILED = "org.adblockplus.android.p roxy.failure";
69
70 private final static String IPTABLES_RETURN = " -t nat -m owner --uid-owner {{ UID}} -A OUTPUT -p tcp -j RETURN\n";
71 private final static String IPTABLES_ADD_HTTP = " -t nat -A OUTPUT -p tcp --dp ort 80 -j REDIRECT --to {{PORT}}\n";
72
73 private Notification ongoingNotification;
74 private PendingIntent contentIntent;
75
76 private Handler notrafficHandler;
77
78 protected ProxyServer proxy = null;
79 protected int port;
80
81 /**
82 * Indicates that service is working with root privileges.
83 */
84 private boolean transparent = false;
85 /**
86 * Indicates that service has autoconfigured Android proxy settings (version
87 * 3.1+).
88 */
89 private boolean nativeProxy = false;
90
91 private String iptables = null;
92
93 @Override
94 public void onCreate()
95 {
96 super.onCreate();
97
98 // Get port for local proxy
99 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this );
100 String p = prefs.getString(getString(R.string.pref_port), null);
101 try
102 {
103 port = p != null ? Integer.valueOf(p) : getResources().getInteger(R.intege r.def_port);
104 }
105 catch (NumberFormatException e)
106 {
107 Toast.makeText(this, getString(R.string.msg_badport) + ": " + p, Toast.LEN GTH_LONG).show();
108 port = getResources().getInteger(R.integer.def_port);
109 }
110
111 // Try to read user proxy settings
112 String proxyHost = null;
113 String proxyPort = null;
114 String proxyExcl = null;
115 String proxyUser = null;
116 String proxyPass = null;
117
118 if (hasNativeProxy)
119 {
120 // Read system settings
121 proxyHost = System.getProperty("http.proxyHost");
122 proxyPort = System.getProperty("http.proxyPort");
123 proxyExcl = System.getProperty("http.nonProxyHosts");
124
125 Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")");
126 String[] px = ProxySettings.getUserProxy(getApplicationContext()); // not used but left for future reference
127 if (px != null)
128 Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")");
129 }
130 else
131 {
132 // Read application settings
133 proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null);
134 proxyPort = prefs.getString(getString(R.string.pref_proxyport), null);
135 proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null);
136 proxyPass = prefs.getString(getString(R.string.pref_proxypass), null);
137 }
138
139 // Check for root privileges and try to install transparent proxy
140 if (RootTools.isAccessGiven())
141 {
142 try
143 {
144 initIptables();
145
146 StringBuffer cmd = new StringBuffer();
147 int uid = getPackageManager().getPackageInfo(getPackageName(), 0).applic ationInfo.uid;
148 cmd.append(iptables);
149 cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid)));
150 cmd.append(iptables);
151 cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port)));
152 String rules = cmd.toString();
153 RootTools.sendShell(rules, DEFAULT_TIMEOUT);
154 transparent = true;
155 }
156 catch (FileNotFoundException e)
157 {
158 // ignore - this is "normal" case
159 }
160 catch (NameNotFoundException e)
161 {
162 Log.e(TAG, "Failed to initialize iptables", e);
163 }
164 catch (IOException e)
165 {
166 Log.e(TAG, "Failed to initialize iptables", e);
167 }
168 catch (RootToolsException e)
169 {
170 Log.e(TAG, "Failed to initialize iptables", e);
171 }
172 catch (TimeoutException e)
173 {
174 Log.e(TAG, "Failed to initialize iptables", e);
175 }
176 }
177
178 if (!transparent)
179 {
180 // Try to set native proxy
181 nativeProxy = ProxySettings.setConnectionProxy(getApplicationContext(), LO CALHOST, port, "");
182
183 if (nativeProxy)
184 {
185 registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManage r.CONNECTIVITY_ACTION));
186 registerReceiver(connectionReceiver, new IntentFilter("android.net.wifi. LINK_CONFIGURATION_CHANGED"));
187 }
188 }
189
190 // Start engine
191 AdblockPlus.getApplication().startEngine();
192
193 registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROX Y_FAILED));
194 registerReceiver(matchesReceiver, new IntentFilter(AdblockPlus.BROADCAST_FIL TER_MATCHES));
195
196 // Start proxy
197 if (proxy == null)
198 {
199 ServerSocket listen = null;
200 try
201 {
202 // TODO Add port travel
203 listen = new ServerSocket(port, 1024);
204 }
205 catch (IOException e)
206 {
207 sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", e.getMe ssage()));
208 Log.e(TAG, null, e);
209 return;
210 }
211
212 Properties config = new Properties();
213 config.put("handler", "main");
214 config.put("main.prefix", "");
215 config.put("main.class", "sunlabs.brazil.server.ChainHandler");
216 if (transparent)
217 {
218 config.put("main.handlers", "urlmodifier adblock");
219 config.put("urlmodifier.class", "org.adblockplus.brazil.TransparentProxy Handler");
220 }
221 else
222 {
223 config.put("main.handlers", "https adblock");
224 config.put("https.class", "org.adblockplus.brazil.SSLConnectionHandler") ;
225 }
226 config.put("adblock.class", "org.adblockplus.brazil.RequestHandler");
227 if (logRequests)
228 config.put("adblock.proxylog", "yes");
229
230 configureUserProxy(config, proxyHost, proxyPort, proxyExcl, proxyUser, pro xyPass);
231
232 proxy = new ProxyServer();
233 proxy.logLevel = Server.LOG_DIAGNOSTIC;
234 proxy.setup(listen, config.getProperty("handler"), config);
235 proxy.start();
236 }
237
238 prefs.registerOnSharedPreferenceChangeListener(this);
239
240 String msg = getString(transparent ? R.string.notif_all : nativeProxy ? R.st ring.notif_wifi : R.string.notif_waiting);
241 if (!transparent && !nativeProxy)
242 {
243 // Initiate no traffic check
244 notrafficHandler = new Handler();
245 notrafficHandler.postDelayed(noTraffic, NO_TRAFFIC_TIMEOUT);
246 }
247 // Lock service
248 ongoingNotification = new Notification();
249 ongoingNotification.when = 0;
250 contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Preferen ces.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TA SK), 0);
251 ongoingNotification.icon = R.drawable.ic_stat_blocking;
252 ongoingNotification.setLatestEventInfo(getApplicationContext(), getText(R.st ring.app_name), msg, contentIntent);
253 startForeground(ONGOING_NOTIFICATION_ID, ongoingNotification);
254
255 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", true). putExtra("port", port).putExtra("manual", !transparent && !nativeProxy));
256 Log.i(TAG, "Service started");
257 }
258
259 @Override
260 public void onDestroy()
261 {
262 super.onDestroy();
263
264 stopNoTrafficCheck(false);
265
266 unregisterReceiver(matchesReceiver);
267 unregisterReceiver(proxyReceiver);
268
269 // Stop IP redirecting
270 if (transparent)
271 {
272 new Thread() {
273 @Override
274 public void run()
275 {
276 try
277 {
278 RootTools.sendShell(iptables + " -t nat -F OUTPUT", DEFAULT_TIMEOUT) ;
279 }
280 catch (Exception e)
281 {
282 Log.e(TAG, "Failed to clear iptables", e);
283 }
284 }
285 }.start();
286 }
287
288 // Clear native proxy
289 if (nativeProxy)
290 {
291 unregisterReceiver(connectionReceiver);
292 clearConnectionProxy();
293 }
294
295 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", false) );
296
297 // Stop proxy server
298 proxy.close();
299
300 // Stop engine if not in interactive mode
301 AdblockPlus.getApplication().stopEngine(false);
302
303 // Release service lock
304 stopForeground(true);
305
306 Log.i(TAG, "Service stopped");
307 }
308
309 /**
310 * Restores system proxy settings via native call on Android 3.1+ devices usin g
311 * Java reflection.
312 */
313 private void clearConnectionProxy()
314 {
315 String proxyHost = (String) proxy.props.getProperty("adblock.proxyHost");
316 String proxyPort = (String) proxy.props.getProperty("adblock.proxyPort");
317 String proxyExcl = (String) proxy.props.getProperty("adblock.proxyExcl");
318 int port = 0;
319 try
320 {
321 if (proxyHost != null)
322 port = Integer.valueOf(proxyPort);
323 }
324 catch (NumberFormatException e)
325 {
326 Log.e(TAG, "Bad port setting", e);
327 }
328 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p roxyExcl);
329 }
330
331 /**
332 * Sets user proxy settings in proxy service properties.
333 */
334 private void configureUserProxy(Properties config, String proxyHost, String pr oxyPort, String proxyExcl, String proxyUser, String proxyPass)
335 {
336 // Clean previous settings
337 config.remove("adblock.proxyHost");
338 config.remove("adblock.proxyPort");
339 config.remove("adblock.auth");
340 config.remove("adblock.proxyExcl");
341 if (!transparent)
342 {
343 config.remove("https.proxyHost");
344 config.remove("https.proxyPort");
345 config.remove("https.auth");
346 }
347
348 if (nativeProxy)
349 passProxySettings(proxyHost, proxyPort, proxyExcl);
350
351 // Check if there are any settings
352 if (proxyHost == null || "".equals(proxyHost))
353 return;
354
355 // Check for dirty proxy settings - this indicated previous crash:
356 // proxy points to ourselves
357 // proxy port is null, 0 or not a number
358 // proxy is 127.0.0.1:8080
359 if (proxyPort == null)
360 return;
361 int p = 0;
362 try
363 {
364 p = Integer.valueOf(proxyPort);
365 }
366 catch (NumberFormatException e)
367 {
368 return;
369 }
370 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080))
371 {
372 if (nativeProxy)
373 passProxySettings(null, null, null);
374 return;
375 }
376
377 config.put("adblock.proxyHost", proxyHost);
378 config.put("adblock.proxyPort", proxyPort);
379 if (!transparent)
380 {
381 config.put("https.proxyHost", proxyHost);
382 config.put("https.proxyPort", proxyPort);
383 }
384
385 // TODO Not implemented in our proxy but needed to restore settings
386 if (proxyExcl != null)
387 config.put("adblock.proxyExcl", proxyExcl);
388
389 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e quals(proxyPass))
390 {
391 // Base64 encode user:password
392 String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + ":" + p roxyPass));
393 config.put("adblock.auth", proxyAuth);
394 if (!transparent)
395 config.put("https.auth", proxyAuth);
396 }
397 }
398
399 private void passProxySettings(String proxyHost, String proxyPort, String prox yExcl)
400 {
401 try
402 {
403 CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExceptionHa ndler();
404 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl);
405 }
406 catch (ClassCastException e)
407 {
408 // ignore - default handler in use
409 }
410 }
411
412 @Override
413 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Str ing key)
414 {
415 if (hasNativeProxy)
416 {
417 String ketHost = getString(R.string.pref_proxyhost);
418 String keyPort = getString(R.string.pref_proxyport);
419 String keyUser = getString(R.string.pref_proxyuser);
420 String keyPass = getString(R.string.pref_proxypass);
421 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k ey.equals(keyPass))
422 {
423 String proxyHost = sharedPreferences.getString(ketHost, null);
424 String proxyPort = sharedPreferences.getString(keyPort, null);
425 String proxyUser = sharedPreferences.getString(keyUser, null);
426 String proxyPass = sharedPreferences.getString(keyPass, null);
427 if (proxy != null)
428 {
429 configureUserProxy(proxy.props, proxyHost, proxyPort, null, proxyUser, proxyPass);
430 proxy.restart(proxy.props.getProperty("handler"));
431 }
432 }
433 }
434 }
435
436 public boolean isTransparent()
437 {
438 return transparent;
439 }
440
441 public boolean isNativeProxy()
442 {
443 return nativeProxy;
444 }
445
446 /**
447 * Checks if specified host is local.
448 */
449 private static final boolean isLocalHost(String host)
450 {
451 if (host == null)
452 return false;
453
454 try
455 {
456 if (host.equalsIgnoreCase("localhost"))
457 return true;
458
459 String className = "android.net.NetworkUtils";
460 Class<?> c = Class.forName(className);
461 /*
462 * InetAddress address = NetworkUtils.numericToInetAddress(host);
463 */
464 Method method = c.getMethod("numericToInetAddress", String.class);
465 InetAddress address = (InetAddress) method.invoke(null, host);
466
467 if (address.isLoopbackAddress())
468 return true;
469 }
470 catch (Exception e)
471 {
472 Log.w(TAG, null, e);
473 }
474 return false;
475 }
476
477 /**
478 * Initializes iptables executable.
479 *
480 * @throws FileNotFoundException If iptables initialization failed due to prov ided reasons.
481 */
482 private void initIptables() throws IOException, RootToolsException, TimeoutExc eption, FileNotFoundException
483 {
484 if (!RootTools.isAccessGiven())
485 throw new FileNotFoundException("No root access");
486
487 File ipt = getFileStreamPath("iptables");
488
489 if (!ipt.exists())
490 {
491 Log.e(TAG, "No iptables excutable found");
492 throw new FileNotFoundException("No iptables executable");
493 }
494
495 String path = ipt.getAbsolutePath();
496
497 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT);
498
499 boolean compatible = false;
500 boolean version = false;
501
502 String command = path + " --version\n" + path + " -L -t nat -n\n";
503
504 List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT);
505 for (String line : result)
506 {
507 if (line.contains("OUTPUT"))
508 compatible = true;
509 if (line.contains("v1.4."))
510 version = true;
511 }
512
513 if (!compatible || !version)
514 {
515 Log.e(TAG, "Incompatible iptables excutable");
516 throw new FileNotFoundException("Incompatible iptables excutable");
517 }
518
519 iptables = path;
520 }
521
522 public List<String> getIptablesOutput()
523 {
524 if (iptables == null)
525 return null;
526
527 String command = iptables + " -L -t nat -n\n";
528 try
529 {
530 return RootTools.sendShell(command, DEFAULT_TIMEOUT);
531 }
532 catch (Exception e)
533 {
534 Log.e(TAG, "Failed to get iptables configuration", e);
535 return null;
536 }
537 }
538
539 /**
540 * Stops no traffic check, optionally resetting notification message.
541 *
542 * @param changeStatus
543 * true if notification message should be set to normal operating
544 * mode
545 */
546 private void stopNoTrafficCheck(boolean changeStatus)
547 {
548 if (notrafficHandler != null)
549 {
550 notrafficHandler.removeCallbacks(noTraffic);
551 if (changeStatus)
552 {
553 NotificationManager notificationManager = (NotificationManager) getSyste mService(NOTIFICATION_SERVICE);
554 ongoingNotification.setLatestEventInfo(ProxyService.this, getText(R.stri ng.app_name), getText(R.string.notif_wifi), contentIntent);
555 notificationManager.notify(ONGOING_NOTIFICATION_ID, ongoingNotification) ;
556 }
557 }
558 notrafficHandler = null;
559 }
560
561 private final IBinder binder = new LocalBinder();
562
563 public final class LocalBinder extends Binder
564 {
565 public ProxyService getService()
566 {
567 return ProxyService.this;
568 }
569 }
570
571 @Override
572 public IBinder onBind(Intent intent)
573 {
574 return binder;
575 }
576
577 /**
578 * Executed if no traffic is detected after a period of time. Notifies user
579 * about possible configuration problems.
580 */
581 private Runnable noTraffic = new Runnable() {
582 public void run()
583 {
584 // Show warning notification
585 Notification notification = new Notification();
586 notification.icon = R.drawable.ic_stat_warning;
587 notification.when = System.currentTimeMillis();
588 notification.flags |= Notification.FLAG_AUTO_CANCEL;
589 notification.defaults |= Notification.DEFAULT_SOUND;
590 Intent intent = new Intent(ProxyService.this, ConfigurationActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
591 intent.putExtra("port", port);
592 PendingIntent contentIntent = PendingIntent.getActivity(ProxyService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
593 notification.setLatestEventInfo(ProxyService.this, getText(R.string.app_na me), getString(R.string.notif_notraffic), contentIntent);
594 NotificationManager notificationManager = (NotificationManager) getSystemS ervice(NOTIFICATION_SERVICE);
595 notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, notification);
596 }
597 };
598
599 /**
600 * Stops no traffic check if traffic is detected by proxy service.
601 */
602 private BroadcastReceiver matchesReceiver = new BroadcastReceiver() {
603 @Override
604 public void onReceive(final Context context, Intent intent)
605 {
606 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTER_MATCHES))
607 stopNoTrafficCheck(true);
608 }
609 };
610
611 /**
612 * Stops service if proxy fails.
613 */
614 private BroadcastReceiver proxyReceiver = new BroadcastReceiver() {
615 @Override
616 public void onReceive(final Context context, Intent intent)
617 {
618 if (intent.getAction().equals(ProxyService.BROADCAST_PROXY_FAILED))
619 {
620 stopSelf();
621 }
622 }
623 };
624
625 /**
626 * Monitors system network connection settings changes and updates proxy
627 * settings accordingly.
628 */
629 private BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
630 @Override
631 public void onReceive(Context ctx, Intent intent)
632 {
633 String action = intent.getAction();
634 Log.i(TAG, "Action: " + action);
635 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
636 {
637 NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_N ETWORK_INFO);
638 String typeName = info.getTypeName();
639 String subtypeName = info.getSubtypeName();
640 boolean available = info.isAvailable();
641 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + " , available: " + available);
642 if (info.getType() == ConnectivityManager.TYPE_WIFI)
643 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, p ort, "");
644 }
645 else if ("android.net.wifi.LINK_CONFIGURATION_CHANGED".equals(action))
646 {
647 Object lp = intent.getParcelableExtra("linkProperties");
648 Method method;
649 try
650 {
651 /*
652 * lp.getHttpProxy();
653 */
654 method = lp.getClass().getMethod("getHttpProxy");
655 Object pp = method.invoke(lp);
656
657 String[] userProxy = ProxySettings.getUserProxy(pp);
658 if (userProxy != null && Integer.valueOf(userProxy[1]) != port)
659 {
660 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userPro xy[1] + "(" + userProxy[2] + ")");
661 if (proxy != null)
662 {
663 configureUserProxy(proxy.props, userProxy[0], userProxy[1], userPr oxy[2], null, null);
664 proxy.restart(proxy.props.getProperty("handler"));
665 }
666 }
667 }
668 catch (Exception e)
669 {
670 // This should not happen
671 Log.e(TAG, null, e);
672 }
673
674 }
675 }
676 };
677
678 final class ProxyServer extends Server
679 {
680 @Override
681 public void close()
682 {
683 try
684 {
685 listen.close();
686 this.interrupt();
687 this.join();
688 }
689 catch (Exception e)
690 {
691 // ignore - it always happens
692 }
693 log(LOG_WARNING, null, "server stopped");
694 }
695
696 @Override
697 public void log(int level, Object obj, String message)
698 {
699 if (level <= logLevel)
700 {
701 Log.println(7 - level, obj != null ? obj.toString() : TAG, message);
702 }
703 }
704 }
705 }
OLDNEW

Powered by Google App Engine
This is Rietveld