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

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

Issue 5697499218051072: Usage of new API, cleanups (reduced) (Closed)
Patch Set: Removed another whitespace change Created April 28, 2014, 8:36 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
1 /* 1 /*
2 * This file is part of Adblock Plus <http://adblockplus.org/>, 2 * This file is part of Adblock Plus <http://adblockplus.org/>,
3 * Copyright (C) 2006-2014 Eyeo GmbH 3 * Copyright (C) 2006-2014 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
56 56
57 import com.stericson.RootTools.RootTools; 57 import com.stericson.RootTools.RootTools;
58 import com.stericson.RootTools.RootToolsException; 58 import com.stericson.RootTools.RootToolsException;
59 59
60 public class ProxyService extends Service implements OnSharedPreferenceChangeLis tener 60 public class ProxyService extends Service implements OnSharedPreferenceChangeLis tener
61 { 61 {
62 private static final String LOCALHOST = "127.0.0.1"; 62 private static final String LOCALHOST = "127.0.0.1";
63 /** 63 /**
64 * Indicates that system supports native proxy configuration. 64 * Indicates that system supports native proxy configuration.
65 */ 65 */
66 public static final boolean NATIVE_PROXY_SUPPORTED = Build.VERSION.SDK_INT >= 12; // Honeycomb 3.1 66 public static final boolean NATIVE_PROXY_SUPPORTED = Build.VERSION.SDK_INT >= 12; // Honeycomb
67 67
68 static 68 static
69 { 69 {
70 RootTools.debugMode = false; 70 RootTools.debugMode = false;
71 } 71 }
72 72
73 private static final String TAG = "ProxyService"; 73 private static final String TAG = Utils.getTag(ProxyService.class);
74 private static final boolean logRequests = false; 74 private static final boolean logRequests = false;
75 75
76 // Do not use 8080 because it is a "dirty" port, Android uses it if something goes wrong 76 // Do not use 8080 because it is a "dirty" port, Android uses it if something goes wrong
77 // First element is reserved for previously used port 77 // first element is reserved for previously used port
78 private static final int[] portVariants = new int[] {-1, 2020, 3030, 4040, 505 0, 6060, 7070, 9090, 1234, 12345, 4321, 0}; 78 private static final int[] portVariants = new int[] { -1, 2020, 3030, 4040, 50 50, 6060, 7070, 9090, 1234, 12345, 4321, 0 };
79 79
80 private final static int DEFAULT_TIMEOUT = 3000; 80 private static final int DEFAULT_TIMEOUT = 3000;
81 private final static int NO_TRAFFIC_TIMEOUT = 5 * 60 * 1000; // 5 minutes 81 private static final int NO_TRAFFIC_TIMEOUT = 5 * 60 * 1000; // 5 minutes
82 82
83 final static int ONGOING_NOTIFICATION_ID = R.string.app_name; 83 static final int ONGOING_NOTIFICATION_ID = R.string.app_name;
84 private static final long POSITION_RIGHT = Build.VERSION.SDK_INT >= Build.VERS ION_CODES.GINGERBREAD ? Long.MIN_VALUE : Long.MAX_VALUE; 84 private static final long POSITION_RIGHT = Build.VERSION.SDK_INT >= Build.VERS ION_CODES.GINGERBREAD ? Long.MIN_VALUE : Long.MAX_VALUE;
85 private final static int NOTRAFFIC_NOTIFICATION_ID = R.string.app_name + 3; 85 private static final int NOTRAFFIC_NOTIFICATION_ID = R.string.app_name + 3;
86 86
87 /** 87 /**
88 * Broadcasted when service starts or stops. 88 * Broadcasted when service starts or stops.
89 */ 89 */
90 public final static String BROADCAST_STATE_CHANGED = "org.adblockplus.android. service.state"; 90 public static final String BROADCAST_STATE_CHANGED = "org.adblockplus.android. service.state";
91 /** 91 /**
92 * Broadcasted if proxy fails to start. 92 * Broadcasted if proxy fails to start.
93 */ 93 */
94 public final static String BROADCAST_PROXY_FAILED = "org.adblockplus.android.p roxy.failure"; 94 public static final String BROADCAST_PROXY_FAILED = "org.adblockplus.android.p roxy.failure";
95 95
96 private final static String IPTABLES_RETURN = " -t nat -m owner --uid-owner {{ UID}} -A OUTPUT -p tcp -j RETURN\n"; 96 private static final String IPTABLES_RETURN = " -t nat -m owner --uid-owner {{ UID}} -A OUTPUT -p tcp -j RETURN\n";
97 private final static String IPTABLES_ADD_HTTP = " -t nat -A OUTPUT -p tcp --dp ort 80 -j REDIRECT --to {{PORT}}\n"; 97 private static final String IPTABLES_ADD_HTTP = " -t nat -A OUTPUT -p tcp --dp ort 80 -j REDIRECT --to {{PORT}}\n";
98 98
99 boolean hideIcon; 99 boolean hideIcon;
100 private Handler notrafficHandler; 100 private Handler notrafficHandler;
101 101
102 protected ProxyServer proxy = null; 102 protected ProxyServer proxy = null;
103 protected int port; 103 protected int port;
104 private Properties proxyConfiguration = new Properties(); 104 private final Properties proxyConfiguration = new Properties();
105 105
106 /** 106 /**
107 * Indicates that service is working with root privileges. 107 * Indicates that service is working with root privileges.
108 */ 108 */
109 private boolean transparent = false; 109 private boolean transparent = false;
110 /** 110 /**
111 * Indicates that service has autoconfigured Android proxy settings (version 3 .1+). 111 * Indicates that service has autoconfigured Android proxy settings (version 3 .1+).
112 */ 112 */
113 private boolean nativeProxyAutoConfigured = false; 113 private boolean nativeProxyAutoConfigured = false;
114 /** 114 /**
115 * Indicates that Android proxy settings are correctly configured (version 4.1 .2+ 4.2.2+). 115 * Indicates that Android proxy settings are correctly configured (version 4.1 .2+ 4.2.2+).
116 */ 116 */
117 private boolean proxyManualyConfigured = false; 117 private boolean proxyManualyConfigured = false;
118 118
119 private String iptables = null; 119 private String iptables = null;
120 120
121 @SuppressLint("NewApi") 121 @SuppressLint("NewApi")
122 @Override 122 @Override
123 public void onCreate() 123 public void onCreate()
124 { 124 {
125 super.onCreate(); 125 super.onCreate();
126 126
127 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) 127 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
128 { 128 {
129 // Proxy is running in separate thread, it's just some resolution request during initialization. 129 // Proxy is running in separate thread, it's just some resolution request during initialization.
130 // Not worth spawning a separate thread for this. 130 // Not worth spawning a separate thread for this.
131 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().per mitNetwork().build(); 131 final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder ().permitNetwork().build();
132 StrictMode.setThreadPolicy(policy); 132 StrictMode.setThreadPolicy(policy);
133 } 133 }
134 134
135 // Get port for local proxy 135 // Get port for local proxy
136 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this ); 136 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreference s(this);
137 Resources resources = getResources(); 137 final Resources resources = getResources();
138 138
139 // Try to read user proxy settings 139 // Try to read user proxy settings
140 String proxyHost = null; 140 String proxyHost = null;
141 String proxyPort = null; 141 String proxyPort = null;
142 String proxyExcl = null; 142 String proxyExcl = null;
143 String proxyUser = null; 143 String proxyUser = null;
144 String proxyPass = null; 144 String proxyPass = null;
145 145
146 if (NATIVE_PROXY_SUPPORTED) 146 if (NATIVE_PROXY_SUPPORTED)
147 { 147 {
148 // Read system settings 148 // Read system settings
149 proxyHost = System.getProperty("http.proxyHost"); 149 proxyHost = System.getProperty("http.proxyHost");
150 proxyPort = System.getProperty("http.proxyPort"); 150 proxyPort = System.getProperty("http.proxyPort");
151 proxyExcl = System.getProperty("http.nonProxyHosts"); 151 proxyExcl = System.getProperty("http.nonProxyHosts");
152 152
153 Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")"); 153 Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")");
154 // not used but left for future reference 154 // not used but left for future reference
155 String[] px = ProxySettings.getUserProxy(getApplicationContext()); 155 final String[] px = ProxySettings.getUserProxy(getApplicationContext());
156 if (px != null) 156 if (px != null)
157 Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")"); 157 Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")");
158 } 158 }
159 else 159 else
160 { 160 {
161 // Read application settings 161 // Read application settings
162 proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null); 162 proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null);
163 proxyPort = prefs.getString(getString(R.string.pref_proxyport), null); 163 proxyPort = prefs.getString(getString(R.string.pref_proxyport), null);
164 proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null); 164 proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null);
165 proxyPass = prefs.getString(getString(R.string.pref_proxypass), null); 165 proxyPass = prefs.getString(getString(R.string.pref_proxypass), null);
166 } 166 }
167 167
168 // Check for root privileges and try to install transparent proxy 168 // Check for root privileges and try to install transparent proxy
169 if (RootTools.isAccessGiven()) 169 if (RootTools.isAccessGiven())
170 { 170 {
171 try 171 try
172 { 172 {
173 initIptables(); 173 initIptables();
174 174
175 StringBuffer cmd = new StringBuffer(); 175 final StringBuffer cmd = new StringBuffer();
176 int uid = getPackageManager().getPackageInfo(getPackageName(), 0).applic ationInfo.uid; 176 final int uid = getPackageManager().getPackageInfo(getPackageName(), 0). applicationInfo.uid;
177 cmd.append(iptables); 177 cmd.append(iptables);
178 cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid))); 178 cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid)));
179 String rules = cmd.toString(); 179 final String rules = cmd.toString();
180 RootTools.sendShell(rules, DEFAULT_TIMEOUT); 180 RootTools.sendShell(rules, DEFAULT_TIMEOUT);
181 transparent = true; 181 transparent = true;
182 } 182 }
183 catch (FileNotFoundException e) 183 catch (final FileNotFoundException e)
184 { 184 {
185 // ignore - this is "normal" case 185 // ignore - this is "normal" case
186 } 186 }
187 catch (NameNotFoundException e) 187 catch (final NameNotFoundException e)
188 { 188 {
189 Log.e(TAG, "Failed to initialize iptables", e); 189 Log.e(TAG, "Failed to initialize iptables", e);
190 } 190 }
191 catch (IOException e) 191 catch (final IOException e)
192 { 192 {
193 Log.e(TAG, "Failed to initialize iptables", e); 193 Log.e(TAG, "Failed to initialize iptables", e);
194 } 194 }
195 catch (RootToolsException e) 195 catch (final RootToolsException e)
196 { 196 {
197 Log.e(TAG, "Failed to initialize iptables", e); 197 Log.e(TAG, "Failed to initialize iptables", e);
198 } 198 }
199 catch (TimeoutException e) 199 catch (final TimeoutException e)
200 { 200 {
201 Log.e(TAG, "Failed to initialize iptables", e); 201 Log.e(TAG, "Failed to initialize iptables", e);
202 } 202 }
203 } 203 }
204 204
205 if (!transparent) 205 if (!transparent)
206 { 206 {
207 // Try to set native proxy 207 // Try to set native proxy
208 nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicatio nContext(), LOCALHOST, port, ""); 208 nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicatio nContext(), LOCALHOST, port, "");
209 209
210 if (NATIVE_PROXY_SUPPORTED) 210 if (NATIVE_PROXY_SUPPORTED)
211 { 211 {
212 registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManage r.CONNECTIVITY_ACTION)); 212 registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManage r.CONNECTIVITY_ACTION));
213 registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE _ACTION)); 213 registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE _ACTION));
214 } 214 }
215 } 215 }
216 216
217 // Save current native proxy situation. The service is always started on the first run so 217 // Save current native proxy situation. The service is always started on the first run so
218 // we will always have a correct value from the box 218 // we will always have a correct value from the box
219 SharedPreferences.Editor editor = prefs.edit(); 219 final SharedPreferences.Editor editor = prefs.edit();
220 editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent || nativeProxyAutoConfigured); 220 editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent || nativeProxyAutoConfigured);
221 editor.commit(); 221 editor.commit();
222 222
223 registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROX Y_FAILED)); 223 registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROX Y_FAILED));
224 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT ERING_CHANGE)); 224 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT ERING_CHANGE));
225 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT ER_MATCHES)); 225 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT ER_MATCHES));
226 226
227 // Start proxy 227 // Start proxy
228 if (proxy == null) 228 if (proxy == null)
229 { 229 {
230 // Select available port and bind to it, use previously selected port by d efault 230 // Select available port and bind to it, use previously selected port by d efault
231 portVariants[0] = prefs.getInt(getString(R.string.pref_lastport), -1); 231 portVariants[0] = prefs.getInt(getString(R.string.pref_lastport), -1);
232 ServerSocket listen = null; 232 ServerSocket listen = null;
233 String msg = null; 233 String msg = null;
234 for (int p : portVariants) 234 for (final int p : portVariants)
235 { 235 {
236 if (p < 0) 236 if (p < 0)
237 continue; 237 continue;
238 try 238 try
239 { 239 {
240 // Fix for #232, bind proxy socket to loopback only 240 // Fix for #232, bind proxy socket to loopback only
241 listen = new ServerSocket(p, 1024, InetAddress.getByName(LOCALHOST)); 241 listen = new ServerSocket(p, 1024, InetAddress.getByName(LOCALHOST));
242 port = p; 242 port = p;
243 break; 243 break;
244 } 244 }
245 catch (IOException e) 245 catch (final IOException e)
246 { 246 {
247 Log.e(TAG, null, e); 247 Log.e(TAG, null, e);
248 msg = e.getMessage(); 248 msg = e.getMessage();
249 } 249 }
250 } 250 }
251 if (listen == null) 251 if (listen == null)
252 { 252 {
253 sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg)); 253 sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg));
254 return; 254 return;
255 } 255 }
(...skipping 26 matching lines...) Expand all
282 proxy.logLevel = Server.LOG_DIAGNOSTIC; 282 proxy.logLevel = Server.LOG_DIAGNOSTIC;
283 proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfig uration); 283 proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfig uration);
284 proxy.start(); 284 proxy.start();
285 } 285 }
286 286
287 if (transparent) 287 if (transparent)
288 { 288 {
289 // Redirect traffic via iptables 289 // Redirect traffic via iptables
290 try 290 try
291 { 291 {
292 StringBuffer cmd = new StringBuffer(); 292 final StringBuffer cmd = new StringBuffer();
293 cmd.append(iptables); 293 cmd.append(iptables);
294 cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port))); 294 cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port)));
295 String rules = cmd.toString(); 295 final String rules = cmd.toString();
296 RootTools.sendShell(rules, DEFAULT_TIMEOUT); 296 RootTools.sendShell(rules, DEFAULT_TIMEOUT);
297 } 297 }
298 catch (FileNotFoundException e) 298 catch (final FileNotFoundException e)
299 { 299 {
300 // ignore - this is "normal" case 300 // ignore - this is "normal" case
301 } 301 }
302 catch (IOException e) 302 catch (final IOException e)
303 { 303 {
304 Log.e(TAG, "Failed to initialize iptables", e); 304 Log.e(TAG, "Failed to initialize iptables", e);
305 } 305 }
306 catch (RootToolsException e) 306 catch (final RootToolsException e)
307 { 307 {
308 Log.e(TAG, "Failed to initialize iptables", e); 308 Log.e(TAG, "Failed to initialize iptables", e);
309 } 309 }
310 catch (TimeoutException e) 310 catch (final TimeoutException e)
311 { 311 {
312 Log.e(TAG, "Failed to initialize iptables", e); 312 Log.e(TAG, "Failed to initialize iptables", e);
313 } 313 }
314 } 314 }
315 315
316 prefs.registerOnSharedPreferenceChangeListener(this); 316 prefs.registerOnSharedPreferenceChangeListener(this);
317 317
318 // Lock service 318 // Lock service
319 hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.get Boolean(R.bool.def_hideicon)); 319 hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.get Boolean(R.bool.def_hideicon));
320 startForeground(ONGOING_NOTIFICATION_ID, getNotification()); 320 startForeground(ONGOING_NOTIFICATION_ID, getNotification());
321 321
322 // If automatic setting of proxy was blocked, check if user has set it manua lly 322 // If automatic setting of proxy was blocked, check if user has set it manua lly
323 boolean manual = isManual(); 323 final boolean manual = isManual();
324 if (manual && NATIVE_PROXY_SUPPORTED) 324 if (manual && NATIVE_PROXY_SUPPORTED)
325 { 325 {
326 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemS ervice(Context.CONNECTIVITY_SERVICE); 326 final ConnectivityManager connectivityManager = (ConnectivityManager) getS ystemService(Context.CONNECTIVITY_SERVICE);
327 updateNoTrafficCheck(connectivityManager); 327 updateNoTrafficCheck(connectivityManager);
328 } 328 }
329 329
330 sendStateChangedBroadcast(); 330 sendStateChangedBroadcast();
331 Log.i(TAG, "Service started"); 331 Log.i(TAG, "Service started");
332 } 332 }
333 333
334 @Override 334 @Override
335 public int onStartCommand(Intent intent, int flags, int startId) 335 public int onStartCommand(final Intent intent, final int flags, final int star tId)
336 { 336 {
337 return START_STICKY; 337 return START_STICKY;
338 } 338 }
339 339
340 @Override 340 @Override
341 public void onDestroy() 341 public void onDestroy()
342 { 342 {
343 super.onDestroy(); 343 super.onDestroy();
344 344
345 stopNoTrafficCheck(); 345 stopNoTrafficCheck();
346 346
347 unregisterReceiver(filterReceiver); 347 unregisterReceiver(filterReceiver);
348 unregisterReceiver(proxyReceiver); 348 unregisterReceiver(proxyReceiver);
349 349
350 // Stop IP redirecting 350 // Stop IP redirecting
351 if (transparent) 351 if (transparent)
352 { 352 {
353 new Thread() 353 new Thread()
354 { 354 {
355 @Override 355 @Override
356 public void run() 356 public void run()
357 { 357 {
358 try 358 try
359 { 359 {
360 RootTools.sendShell(iptables + " -t nat -F OUTPUT", DEFAULT_TIMEOUT) ; 360 RootTools.sendShell(iptables + " -t nat -F OUTPUT", DEFAULT_TIMEOUT) ;
361 } 361 }
362 catch (Exception e) 362 catch (final Exception e)
363 { 363 {
364 Log.e(TAG, "Failed to clear iptables", e); 364 Log.e(TAG, "Failed to clear iptables", e);
365 } 365 }
366 } 366 }
367 }.start(); 367 }.start();
368 } 368 }
369 369
370 if (!transparent && NATIVE_PROXY_SUPPORTED) 370 if (!transparent && NATIVE_PROXY_SUPPORTED)
371 unregisterReceiver(connectionReceiver); 371 unregisterReceiver(connectionReceiver);
372 372
373 // Clear native proxy 373 // Clear native proxy
374 if (nativeProxyAutoConfigured) 374 if (nativeProxyAutoConfigured)
375 { 375 {
376 clearConnectionProxy(); 376 clearConnectionProxy();
377 } 377 }
378 378
379 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", false) ); 379 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", false) );
380 380
381 // Stop proxy server 381 // Stop proxy server
382 if (proxy != null) 382 if (proxy != null)
383 proxy.close(); 383 proxy.close();
384 384
385 // Release service lock 385 // Release service lock
386 stopForeground(true); 386 stopForeground(true);
387 387
388 Log.i(TAG, "Service stopped"); 388 Log.i(TAG, "Service stopped");
389 } 389 }
390 390
391 /** 391 /**
392 * Restores system proxy settings via native call on Android 3.1+ devices 392 * Restores system proxy settings via native call on Android 3.1+ devices usin g Java reflection.
393 * using Java reflection.
394 */ 393 */
395 private void clearConnectionProxy() 394 private void clearConnectionProxy()
396 { 395 {
397 String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost"); 396 final String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost") ;
398 String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort"); 397 final String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort") ;
399 String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl"); 398 final String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl") ;
400 int port = 0; 399 int port = 0;
401 try 400 try
402 { 401 {
403 if (proxyHost != null) 402 if (proxyHost != null)
404 port = Integer.valueOf(proxyPort); 403 port = Integer.valueOf(proxyPort);
405 } 404 }
406 catch (NumberFormatException e) 405 catch (final NumberFormatException e)
407 { 406 {
408 Log.e(TAG, "Bad port setting", e); 407 Log.e(TAG, "Bad port setting", e);
409 } 408 }
410 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p roxyExcl); 409 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p roxyExcl);
411 } 410 }
412 411
413 /** 412 /**
414 * Sets user proxy settings in proxy service properties. 413 * Sets user proxy settings in proxy service properties.
415 */ 414 */
416 private void configureUserProxy(Properties config, String proxyHost, String pr oxyPort, String proxyExcl, String proxyUser, String proxyPass) 415 private void configureUserProxy(final Properties config, final String proxyHos t, final String proxyPort, final String proxyExcl, final String proxyUser, final String proxyPass)
417 { 416 {
418 // Clean previous settings 417 // Clean previous settings
419 config.remove("adblock.proxyHost"); 418 config.remove("adblock.proxyHost");
420 config.remove("adblock.proxyPort"); 419 config.remove("adblock.proxyPort");
421 config.remove("adblock.auth"); 420 config.remove("adblock.auth");
422 config.remove("adblock.proxyExcl"); 421 config.remove("adblock.proxyExcl");
423 if (!transparent) 422 if (!transparent)
424 { 423 {
425 config.remove("https.proxyHost"); 424 config.remove("https.proxyHost");
426 config.remove("https.proxyPort"); 425 config.remove("https.proxyPort");
(...skipping 11 matching lines...) Expand all
438 // proxy points to ourselves 437 // proxy points to ourselves
439 // proxy port is null, 0 or not a number 438 // proxy port is null, 0 or not a number
440 // proxy is 127.0.0.1:8080 439 // proxy is 127.0.0.1:8080
441 if (proxyPort == null) 440 if (proxyPort == null)
442 return; 441 return;
443 int p = 0; 442 int p = 0;
444 try 443 try
445 { 444 {
446 p = Integer.valueOf(proxyPort); 445 p = Integer.valueOf(proxyPort);
447 } 446 }
448 catch (NumberFormatException e) 447 catch (final NumberFormatException e)
449 { 448 {
450 return; 449 return;
451 } 450 }
452 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080)) 451 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080))
453 { 452 {
454 if (nativeProxyAutoConfigured) 453 if (nativeProxyAutoConfigured)
455 passProxySettings(null, null, null); 454 passProxySettings(null, null, null);
456 return; 455 return;
457 } 456 }
458 457
459 config.put("adblock.proxyHost", proxyHost); 458 config.put("adblock.proxyHost", proxyHost);
460 config.put("adblock.proxyPort", proxyPort); 459 config.put("adblock.proxyPort", proxyPort);
461 if (!transparent) 460 if (!transparent)
462 { 461 {
463 config.put("https.proxyHost", proxyHost); 462 config.put("https.proxyHost", proxyHost);
464 config.put("https.proxyPort", proxyPort); 463 config.put("https.proxyPort", proxyPort);
465 } 464 }
466 465
467 // TODO Not implemented in our proxy but needed to restore settings 466 // TODO Not implemented in our proxy but needed to restore settings
468 if (proxyExcl != null) 467 if (proxyExcl != null)
469 config.put("adblock.proxyExcl", proxyExcl); 468 config.put("adblock.proxyExcl", proxyExcl);
470 469
471 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e quals(proxyPass)) 470 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e quals(proxyPass))
472 { 471 {
473 // Base64 encode user:password 472 // Base64 encode user:password
474 String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + ":" + p roxyPass)); 473 final String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + " :" + proxyPass));
475 config.put("adblock.auth", proxyAuth); 474 config.put("adblock.auth", proxyAuth);
476 if (!transparent) 475 if (!transparent)
477 config.put("https.auth", proxyAuth); 476 config.put("https.auth", proxyAuth);
478 } 477 }
479 } 478 }
480 479
481 private void passProxySettings(String proxyHost, String proxyPort, String prox yExcl) 480 private void passProxySettings(final String proxyHost, final String proxyPort, final String proxyExcl)
482 { 481 {
483 try 482 try
484 { 483 {
485 CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExceptionHa ndler(); 484 final CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExcep tionHandler();
486 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl); 485 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl);
487 } 486 }
488 catch (ClassCastException e) 487 catch (final ClassCastException e)
489 { 488 {
490 // ignore - default handler in use 489 // ignore - default handler in use
491 } 490 }
492 } 491 }
493 492
494 @Override 493 @Override
495 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Str ing key) 494 public void onSharedPreferenceChanged(final SharedPreferences sharedPreference s, final String key)
496 { 495 {
497 if (!NATIVE_PROXY_SUPPORTED) 496 if (!NATIVE_PROXY_SUPPORTED)
498 { 497 {
499 String ketHost = getString(R.string.pref_proxyhost); 498 final String ketHost = getString(R.string.pref_proxyhost);
500 String keyPort = getString(R.string.pref_proxyport); 499 final String keyPort = getString(R.string.pref_proxyport);
501 String keyUser = getString(R.string.pref_proxyuser); 500 final String keyUser = getString(R.string.pref_proxyuser);
502 String keyPass = getString(R.string.pref_proxypass); 501 final String keyPass = getString(R.string.pref_proxypass);
503 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k ey.equals(keyPass)) 502 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k ey.equals(keyPass))
504 { 503 {
505 String proxyHost = sharedPreferences.getString(ketHost, null); 504 final String proxyHost = sharedPreferences.getString(ketHost, null);
506 String proxyPort = sharedPreferences.getString(keyPort, null); 505 final String proxyPort = sharedPreferences.getString(keyPort, null);
507 String proxyUser = sharedPreferences.getString(keyUser, null); 506 final String proxyUser = sharedPreferences.getString(keyUser, null);
508 String proxyPass = sharedPreferences.getString(keyPass, null); 507 final String proxyPass = sharedPreferences.getString(keyPass, null);
509 if (proxy != null) 508 if (proxy != null)
510 { 509 {
511 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro xyUser, proxyPass); 510 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro xyUser, proxyPass);
512 proxy.restart(proxyConfiguration.getProperty("handler")); 511 proxy.restart(proxyConfiguration.getProperty("handler"));
513 } 512 }
514 } 513 }
515 } 514 }
516 } 515 }
517 516
518 public boolean isTransparent() 517 public boolean isTransparent()
(...skipping 18 matching lines...) Expand all
537 * Checks whether traffic check is pending 536 * Checks whether traffic check is pending
538 */ 537 */
539 public boolean noTraffic() 538 public boolean noTraffic()
540 { 539 {
541 return notrafficHandler != null; 540 return notrafficHandler != null;
542 } 541 }
543 542
544 /** 543 /**
545 * Checks if specified host is local. 544 * Checks if specified host is local.
546 */ 545 */
547 private static final boolean isLocalHost(String host) 546 private static final boolean isLocalHost(final String host)
548 { 547 {
549 if (host == null) 548 if (host == null)
550 return false; 549 return false;
551 550
552 try 551 try
553 { 552 {
554 if (host.equalsIgnoreCase("localhost")) 553 if (host.equalsIgnoreCase("localhost"))
555 return true; 554 return true;
556 555
557 String className = "android.net.NetworkUtils"; 556 final String className = "android.net.NetworkUtils";
558 Class<?> c = Class.forName(className); 557 final Class<?> c = Class.forName(className);
559 /* 558 /*
560 * InetAddress address = NetworkUtils.numericToInetAddress(host); 559 * InetAddress address = NetworkUtils.numericToInetAddress(host);
561 */ 560 */
562 Method method = c.getMethod("numericToInetAddress", String.class); 561 final Method method = c.getMethod("numericToInetAddress", String.class);
563 InetAddress address = (InetAddress) method.invoke(null, host); 562 final InetAddress address = (InetAddress) method.invoke(null, host);
564 563
565 if (address.isLoopbackAddress()) 564 if (address.isLoopbackAddress())
566 return true; 565 return true;
567 } 566 }
568 catch (Exception e) 567 catch (final Exception e)
569 { 568 {
570 Log.w(TAG, null, e); 569 Log.w(TAG, null, e);
571 } 570 }
572 return false; 571 return false;
573 } 572 }
574 573
575 /** 574 /**
576 * Initializes iptables executable. 575 * Initializes iptables executable.
577 * 576 *
578 * @throws FileNotFoundException 577 * @throws FileNotFoundException
579 * If iptables initialization failed due to provided reasons. 578 * If iptables initialization failed due to provided reasons.
580 */ 579 */
581 private void initIptables() throws IOException, RootToolsException, TimeoutExc eption, FileNotFoundException 580 private void initIptables() throws IOException, RootToolsException, TimeoutExc eption, FileNotFoundException
582 { 581 {
583 if (!RootTools.isAccessGiven()) 582 if (!RootTools.isAccessGiven())
584 throw new FileNotFoundException("No root access"); 583 throw new FileNotFoundException("No root access");
585 584
586 File ipt = getFileStreamPath("iptables"); 585 final File ipt = getFileStreamPath("iptables");
587 586
588 if (!ipt.exists()) 587 if (!ipt.exists())
589 { 588 {
590 Log.e(TAG, "No iptables excutable found"); 589 Log.e(TAG, "No iptables excutable found");
591 throw new FileNotFoundException("No iptables executable"); 590 throw new FileNotFoundException("No iptables executable");
592 } 591 }
593 592
594 String path = ipt.getAbsolutePath(); 593 final String path = ipt.getAbsolutePath();
595 594
596 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT); 595 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT);
597 596
598 boolean compatible = false; 597 boolean compatible = false;
599 boolean version = false; 598 boolean version = false;
600 599
601 String command = path + " --version\n" + path + " -L -t nat -n\n"; 600 final String command = path + " --version\n" + path + " -L -t nat -n\n";
602 601
603 List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT); 602 final List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT);
604 for (String line : result) 603 for (final String line : result)
605 { 604 {
606 if (line.contains("OUTPUT")) 605 if (line.contains("OUTPUT"))
607 compatible = true; 606 compatible = true;
608 if (line.contains("v1.4.")) 607 if (line.contains("v1.4."))
609 version = true; 608 version = true;
610 } 609 }
611 610
612 if (!compatible || !version) 611 if (!compatible || !version)
613 { 612 {
614 Log.e(TAG, "Incompatible iptables excutable"); 613 Log.e(TAG, "Incompatible iptables excutable");
615 throw new FileNotFoundException("Incompatible iptables excutable"); 614 throw new FileNotFoundException("Incompatible iptables excutable");
616 } 615 }
617 616
618 iptables = path; 617 iptables = path;
619 } 618 }
620 619
621 public List<String> getIptablesOutput() 620 public List<String> getIptablesOutput()
622 { 621 {
623 if (iptables == null) 622 if (iptables == null)
624 return null; 623 return null;
625 624
626 String command = iptables + " -L -t nat -n\n"; 625 final String command = iptables + " -L -t nat -n\n";
627 try 626 try
628 { 627 {
629 return RootTools.sendShell(command, DEFAULT_TIMEOUT); 628 return RootTools.sendShell(command, DEFAULT_TIMEOUT);
630 } 629 }
631 catch (Exception e) 630 catch (final Exception e)
632 { 631 {
633 Log.e(TAG, "Failed to get iptables configuration", e); 632 Log.e(TAG, "Failed to get iptables configuration", e);
634 return null; 633 return null;
635 } 634 }
636 } 635 }
637 636
638 /** 637 /**
639 * Raises or removes no traffic notification based on current link proxy 638 * Raises or removes no traffic notification based on current link proxy setti ngs
640 * settings
641 */ 639 */
642 private void updateNoTrafficCheck(ConnectivityManager connectivityManager) 640 private void updateNoTrafficCheck(final ConnectivityManager connectivityManage r)
643 { 641 {
644 try 642 try
645 { 643 {
646 Object pp = ProxySettings.getActiveLinkProxy(connectivityManager); 644 final Object pp = ProxySettings.getActiveLinkProxy(connectivityManager);
647 String[] userProxy = ProxySettings.getUserProxy(pp); 645 final String[] userProxy = ProxySettings.getUserProxy(pp);
648 if (userProxy != null) 646 if (userProxy != null)
649 Log.i(TAG, "Proxy settings: " + userProxy[0] + ":" + userProxy[1] + "(" + userProxy[2] + ")"); 647 Log.i(TAG, "Proxy settings: " + userProxy[0] + ":" + userProxy[1] + "(" + userProxy[2] + ")");
650 updateNoTrafficCheck(userProxy); 648 updateNoTrafficCheck(userProxy);
651 } 649 }
652 catch (Exception e) 650 catch (final Exception e)
653 { 651 {
654 // This should not happen 652 // This should not happen
655 Log.e(TAG, null, e); 653 Log.e(TAG, null, e);
656 } 654 }
657 } 655 }
658 656
659 /** 657 /**
660 * Raises or removes no traffic notification based on the user proxy settings 658 * Raises or removes no traffic notification based on the user proxy settings
661 */ 659 */
662 private void updateNoTrafficCheck(String[] userProxy) 660 private void updateNoTrafficCheck(final String[] userProxy)
663 { 661 {
664 boolean ourProxy = userProxy != null && isLocalHost(userProxy[0]) && Integer .valueOf(userProxy[1]) == port; 662 final boolean ourProxy = userProxy != null && isLocalHost(userProxy[0]) && I nteger.valueOf(userProxy[1]) == port;
665 if (ourProxy != proxyManualyConfigured) 663 if (ourProxy != proxyManualyConfigured)
666 { 664 {
667 proxyManualyConfigured = ourProxy; 665 proxyManualyConfigured = ourProxy;
668 sendStateChangedBroadcast(); 666 sendStateChangedBroadcast();
669 } 667 }
670 if (ourProxy) 668 if (ourProxy)
671 { 669 {
672 stopNoTrafficCheck(); 670 stopNoTrafficCheck();
673 } 671 }
674 else 672 else
675 { 673 {
676 // Initiate no traffic check 674 // Initiate no traffic check
677 notrafficHandler = new Handler(); 675 notrafficHandler = new Handler();
678 notrafficHandler.postDelayed(noTraffic, NO_TRAFFIC_TIMEOUT); 676 notrafficHandler.postDelayed(noTraffic, NO_TRAFFIC_TIMEOUT);
679 } 677 }
680 NotificationManager notificationManager = (NotificationManager) getSystemSer vice(NOTIFICATION_SERVICE); 678 final NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE);
681 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 679 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
682 } 680 }
683 681
684 /** 682 /**
685 * Stops no traffic check and resets notification message. 683 * Stops no traffic check and resets notification message.
686 */ 684 */
687 private void stopNoTrafficCheck() 685 private void stopNoTrafficCheck()
688 { 686 {
689 if (notrafficHandler != null) 687 if (notrafficHandler != null)
690 { 688 {
691 notrafficHandler.removeCallbacks(noTraffic); 689 notrafficHandler.removeCallbacks(noTraffic);
692 sendStateChangedBroadcast(); 690 sendStateChangedBroadcast();
693 NotificationManager notificationManager = (NotificationManager) getSystemS ervice(NOTIFICATION_SERVICE); 691 final NotificationManager notificationManager = (NotificationManager) getS ystemService(NOTIFICATION_SERVICE);
694 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 692 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
695 notificationManager.cancel(NOTRAFFIC_NOTIFICATION_ID); 693 notificationManager.cancel(NOTRAFFIC_NOTIFICATION_ID);
696 } 694 }
697 notrafficHandler = null; 695 notrafficHandler = null;
698 } 696 }
699 697
700 @SuppressLint("NewApi") 698 @SuppressLint("NewApi")
701 private Notification getNotification() 699 private Notification getNotification()
702 { 700 {
703 boolean filtering = AdblockPlus.getApplication().isFilteringEnabled(); 701 final boolean filtering = AdblockPlus.getApplication().isFilteringEnabled();
704 702
705 int msgId = R.string.notif_waiting; 703 int msgId = R.string.notif_waiting;
706 if (nativeProxyAutoConfigured || proxyManualyConfigured) 704 if (nativeProxyAutoConfigured || proxyManualyConfigured)
707 msgId = filtering ? R.string.notif_wifi : R.string.notif_wifi_nofiltering; 705 msgId = filtering ? R.string.notif_wifi : R.string.notif_wifi_nofiltering;
708 if (transparent) 706 if (transparent)
709 msgId = R.string.notif_all; 707 msgId = R.string.notif_all;
710 708
711 NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 709 final NotificationCompat.Builder builder = new NotificationCompat.Builder(th is);
712 if (hideIcon && msgId != R.string.notif_waiting) 710 if (hideIcon && msgId != R.string.notif_waiting)
713 { 711 {
714 builder.setWhen(POSITION_RIGHT); 712 builder.setWhen(POSITION_RIGHT);
715 builder.setSmallIcon(R.drawable.transparent); 713 builder.setSmallIcon(R.drawable.transparent);
716 //builder.setContent(new RemoteViews(getPackageName(), R.layout.notif_hidd en)); 714 // builder.setContent(new RemoteViews(getPackageName(), R.layout.notif_hid den));
717 } 715 }
718 else 716 else
719 { 717 {
720 builder.setWhen(0); 718 builder.setWhen(0);
721 builder.setSmallIcon(R.drawable.ic_stat_blocking); 719 builder.setSmallIcon(R.drawable.ic_stat_blocking);
722 } 720 }
723 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent( this, Preferences.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_A CTIVITY_NEW_TASK), 0); 721 final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new I ntent(this, Preferences.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_NEW_TASK), 0);
724 builder.setContentIntent(contentIntent); 722 builder.setContentIntent(contentIntent);
725 builder.setContentTitle(getText(R.string.app_name)); 723 builder.setContentTitle(getText(R.string.app_name));
726 builder.setContentText(getString(msgId, port)); 724 builder.setContentText(getString(msgId, port));
727 builder.setOngoing(true); 725 builder.setOngoing(true);
728 726
729 Notification notification = builder.getNotification(); 727 final Notification notification = builder.getNotification();
730 return notification; 728 return notification;
731 } 729 }
732 730
733 public void setEmptyIcon(boolean hide) 731 public void setEmptyIcon(final boolean hide)
734 { 732 {
735 hideIcon = hide; 733 hideIcon = hide;
736 NotificationManager notificationManager = (NotificationManager) getSystemSer vice(NOTIFICATION_SERVICE); 734 final NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE);
737 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 735 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
738 } 736 }
739 737
740 public void sendStateChangedBroadcast() 738 public void sendStateChangedBroadcast()
741 { 739 {
742 Log.i(TAG, "Broadcasting " + BROADCAST_STATE_CHANGED); 740 Log.i(TAG, "Broadcasting " + BROADCAST_STATE_CHANGED);
743 boolean manual = isManual(); 741 final boolean manual = isManual();
744 Intent stateIntent = new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", true).putExtra("port", port).putExtra("manual", manual); 742 final Intent stateIntent = new Intent(BROADCAST_STATE_CHANGED).putExtra("ena bled", true).putExtra("port", port).putExtra("manual", manual);
745 if (manual) 743 if (manual)
746 stateIntent.putExtra("configured", proxyManualyConfigured); 744 stateIntent.putExtra("configured", proxyManualyConfigured);
747 sendBroadcast(stateIntent); 745 sendBroadcast(stateIntent);
748 } 746 }
749 747
750 private final IBinder binder = new LocalBinder(); 748 private final IBinder binder = new LocalBinder();
751 749
752 public final class LocalBinder extends Binder 750 public final class LocalBinder extends Binder
753 { 751 {
754 public ProxyService getService() 752 public ProxyService getService()
755 { 753 {
756 return ProxyService.this; 754 return ProxyService.this;
757 } 755 }
758 } 756 }
759 757
760 @Override 758 @Override
761 public IBinder onBind(Intent intent) 759 public IBinder onBind(final Intent intent)
762 { 760 {
763 return binder; 761 return binder;
764 } 762 }
765 763
766 /** 764 /**
767 * Executed if no traffic is detected after a period of time. Notifies user 765 * Executed if no traffic is detected after a period of time. Notifies user ab out possible
768 * about possible configuration problems. 766 * configuration problems.
769 */ 767 */
770 private Runnable noTraffic = new Runnable() 768 private final Runnable noTraffic = new Runnable()
771 { 769 {
770 @Override
772 public void run() 771 public void run()
773 { 772 {
774 // It's weird but notrafficHandler.removeCallbacks(noTraffic) does not rem ove this callback 773 // It's weird but notrafficHandler.removeCallbacks(noTraffic) does not rem ove this callback
775 if (notrafficHandler == null) 774 if (notrafficHandler == null)
776 return; 775 return;
777 // Show warning notification 776 // Show warning notification
778 NotificationCompat.Builder builder = new NotificationCompat.Builder(ProxyS ervice.this); 777 final NotificationCompat.Builder builder = new NotificationCompat.Builder( ProxyService.this);
779 builder.setSmallIcon(R.drawable.ic_stat_warning); 778 builder.setSmallIcon(R.drawable.ic_stat_warning);
780 builder.setWhen(System.currentTimeMillis()); 779 builder.setWhen(System.currentTimeMillis());
781 builder.setAutoCancel(true); 780 builder.setAutoCancel(true);
782 Intent intent = new Intent(ProxyService.this, ConfigurationActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 781 final Intent intent = new Intent(ProxyService.this, ConfigurationActivity. class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
783 intent.putExtra("port", port); 782 intent.putExtra("port", port);
784 PendingIntent contentIntent = PendingIntent.getActivity(ProxyService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 783 final PendingIntent contentIntent = PendingIntent.getActivity(ProxyService .this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
785 builder.setContentIntent(contentIntent); 784 builder.setContentIntent(contentIntent);
786 builder.setContentTitle(getText(R.string.app_name)); 785 builder.setContentTitle(getText(R.string.app_name));
787 builder.setContentText(getText(R.string.notif_notraffic)); 786 builder.setContentText(getText(R.string.notif_notraffic));
788 NotificationManager notificationManager = (NotificationManager) getSystemS ervice(NOTIFICATION_SERVICE); 787 final NotificationManager notificationManager = (NotificationManager) getS ystemService(NOTIFICATION_SERVICE);
789 notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, builder.getNotificat ion()); 788 notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, builder.getNotificat ion());
790 } 789 }
791 }; 790 };
792 791
793 /** 792 /**
794 * Stops no traffic check if traffic is detected by proxy service. 793 * Stops no traffic check if traffic is detected by proxy service.
795 */ 794 */
796 private BroadcastReceiver filterReceiver = new BroadcastReceiver() 795 private final BroadcastReceiver filterReceiver = new BroadcastReceiver()
797 { 796 {
798 @Override 797 @Override
799 public void onReceive(final Context context, Intent intent) 798 public void onReceive(final Context context, final Intent intent)
800 { 799 {
801 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTERING_CHANGE)) 800 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTERING_CHANGE))
802 { 801 {
803 // It's rather a hack but things are happening simultaneously and we 802 // It's rather a hack but things are happening simultaneously and we
804 // receive this broadcast despite the fact we have unsubscribed from 803 // receive this broadcast despite the fact we have unsubscribed from
805 // it and notification is not removed because it is changed to new one 804 // it and notification is not removed because it is changed to new one
806 // during removal. 805 // during removal.
807 if (!ProxyService.this.isNativeProxyAutoConfigured()) 806 if (!isNativeProxyAutoConfigured())
808 { 807 {
809 NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE); 808 final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
810 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()) ; 809 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()) ;
811 } 810 }
812 } 811 }
813 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTER_MATCHES)) 812 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTER_MATCHES))
814 { 813 {
815 proxyManualyConfigured = true; 814 proxyManualyConfigured = true;
816 stopNoTrafficCheck(); 815 stopNoTrafficCheck();
817 } 816 }
818 } 817 }
819 }; 818 };
820 819
821 /** 820 /**
822 * Stops service if proxy fails. 821 * Stops service if proxy fails.
823 */ 822 */
824 private BroadcastReceiver proxyReceiver = new BroadcastReceiver() 823 private final BroadcastReceiver proxyReceiver = new BroadcastReceiver()
825 { 824 {
826 @Override 825 @Override
827 public void onReceive(final Context context, Intent intent) 826 public void onReceive(final Context context, final Intent intent)
828 { 827 {
829 if (intent.getAction().equals(ProxyService.BROADCAST_PROXY_FAILED)) 828 if (intent.getAction().equals(ProxyService.BROADCAST_PROXY_FAILED))
830 { 829 {
831 stopSelf(); 830 stopSelf();
832 } 831 }
833 } 832 }
834 }; 833 };
835 834
836 /** 835 /**
837 * Monitors system network connection settings changes and updates proxy 836 * Monitors system network connection settings changes and updates proxy setti ngs accordingly.
838 * settings accordingly.
839 */ 837 */
840 private BroadcastReceiver connectionReceiver = new BroadcastReceiver() 838 private final BroadcastReceiver connectionReceiver = new BroadcastReceiver()
841 { 839 {
842 @Override 840 @Override
843 public void onReceive(Context ctx, Intent intent) 841 public void onReceive(final Context ctx, final Intent intent)
844 { 842 {
845 String action = intent.getAction(); 843 final String action = intent.getAction();
846 Log.i(TAG, "Action: " + action); 844 Log.i(TAG, "Action: " + action);
847 // Connectivity change 845 // Connectivity change
848 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) 846 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
849 { 847 {
850 ConnectivityManager connectivityManager = (ConnectivityManager) getSyste mService(Context.CONNECTIVITY_SERVICE); 848 final ConnectivityManager connectivityManager = (ConnectivityManager) ge tSystemService(Context.CONNECTIVITY_SERVICE);
851 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc ast() instead? 849 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc ast() instead?
852 NetworkInfo info = connectivityManager.getActiveNetworkInfo(); 850 final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
853 if (info == null) 851 if (info == null)
854 return; 852 return;
855 String typeName = info.getTypeName(); 853 final String typeName = info.getTypeName();
856 String subtypeName = info.getSubtypeName(); 854 final String subtypeName = info.getSubtypeName();
857 boolean available = info.isAvailable(); 855 final boolean available = info.isAvailable();
858 856
859 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + " , available: " + available); 857 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + " , available: " + available);
860 if (info.getType() == ConnectivityManager.TYPE_WIFI) 858 if (info.getType() == ConnectivityManager.TYPE_WIFI)
861 { 859 {
862 if (nativeProxyAutoConfigured) 860 if (nativeProxyAutoConfigured)
863 { 861 {
864 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port, ""); 862 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port, "");
865 } 863 }
866 else 864 else
867 { 865 {
868 updateNoTrafficCheck(connectivityManager); 866 updateNoTrafficCheck(connectivityManager);
869 } 867 }
870 } 868 }
871 } 869 }
872 // Proxy change 870 // Proxy change
873 else if (Proxy.PROXY_CHANGE_ACTION.equals(action)) 871 else if (Proxy.PROXY_CHANGE_ACTION.equals(action))
874 { 872 {
875 Object pp = intent.getParcelableExtra("proxy"); 873 final Object pp = intent.getParcelableExtra("proxy");
876 try 874 try
877 { 875 {
878 String[] userProxy = ProxySettings.getUserProxy(pp); 876 final String[] userProxy = ProxySettings.getUserProxy(pp);
879 if (nativeProxyAutoConfigured) 877 if (nativeProxyAutoConfigured)
880 { 878 {
881 if (userProxy != null && Integer.valueOf(userProxy[1]) != port) 879 if (userProxy != null && Integer.valueOf(userProxy[1]) != port)
882 { 880 {
883 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP roxy[1] + "(" + userProxy[2] + ")"); 881 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP roxy[1] + "(" + userProxy[2] + ")");
884 if (proxy != null) 882 if (proxy != null)
885 { 883 {
886 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1 ], userProxy[2], null, null); 884 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1 ], userProxy[2], null, null);
887 proxy.restart(proxyConfiguration.getProperty("handler")); 885 proxy.restart(proxyConfiguration.getProperty("handler"));
888 } 886 }
889 } 887 }
890 } 888 }
891 else 889 else
892 { 890 {
893 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1 ] + "(" + userProxy[2] + ")"); 891 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1 ] + "(" + userProxy[2] + ")");
894 updateNoTrafficCheck(userProxy); 892 updateNoTrafficCheck(userProxy);
895 } 893 }
896 } 894 }
897 catch (Exception e) 895 catch (final Exception e)
898 { 896 {
899 // This should not happen 897 // This should not happen
900 Log.e(TAG, null, e); 898 Log.e(TAG, null, e);
901 } 899 }
902 } 900 }
903 } 901 }
904 }; 902 };
905 903
906 final class ProxyServer extends Server 904 final class ProxyServer extends Server
907 { 905 {
908 @Override 906 @Override
909 public void close() 907 public void close()
910 { 908 {
911 try 909 try
912 { 910 {
913 listen.close(); 911 listen.close();
914 this.interrupt(); 912 this.interrupt();
915 this.join(); 913 this.join();
916 } 914 }
917 catch (Exception e) 915 catch (final Exception e)
918 { 916 {
919 // ignore - it always happens 917 // ignore - it always happens
920 } 918 }
921 log(LOG_WARNING, null, "server stopped"); 919 log(LOG_WARNING, null, "server stopped");
922 } 920 }
923 921
924 @Override 922 @Override
925 public void log(int level, Object obj, String message) 923 public void log(final int level, final Object obj, final String message)
926 { 924 {
927 if (level <= logLevel) 925 if (level <= logLevel)
928 { 926 {
929 Log.println(7 - level, obj != null ? obj.toString() : TAG, message); 927 Log.println(7 - level, obj != null ? obj.toString() : TAG, message);
930 } 928 }
931 } 929 }
932 } 930 }
933 } 931 }
OLDNEW
« no previous file with comments | « src/org/adblockplus/android/ProxyConfigurationActivity.java ('k') | src/org/adblockplus/android/ProxySettings.java » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld