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 even more unrelated changes Created April 28, 2014, 9:42 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 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
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 3.1
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, 505 0, 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
(...skipping 14 matching lines...) Expand all
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
393 * using Java reflection. 393 * using Java reflection.
394 */ 394 */
395 private void clearConnectionProxy() 395 private void clearConnectionProxy()
396 { 396 {
397 String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost"); 397 final String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost") ;
398 String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort"); 398 final String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort") ;
399 String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl"); 399 final String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl") ;
400 int port = 0; 400 int port = 0;
401 try 401 try
402 { 402 {
403 if (proxyHost != null) 403 if (proxyHost != null)
404 port = Integer.valueOf(proxyPort); 404 port = Integer.valueOf(proxyPort);
405 } 405 }
406 catch (NumberFormatException e) 406 catch (final NumberFormatException e)
407 { 407 {
408 Log.e(TAG, "Bad port setting", e); 408 Log.e(TAG, "Bad port setting", e);
409 } 409 }
410 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p roxyExcl); 410 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p roxyExcl);
411 } 411 }
412 412
413 /** 413 /**
414 * Sets user proxy settings in proxy service properties. 414 * Sets user proxy settings in proxy service properties.
415 */ 415 */
416 private void configureUserProxy(Properties config, String proxyHost, String pr oxyPort, String proxyExcl, String proxyUser, String proxyPass) 416 private void configureUserProxy(final Properties config, final String proxyHos t, final String proxyPort, final String proxyExcl, final String proxyUser, final String proxyPass)
417 { 417 {
418 // Clean previous settings 418 // Clean previous settings
419 config.remove("adblock.proxyHost"); 419 config.remove("adblock.proxyHost");
420 config.remove("adblock.proxyPort"); 420 config.remove("adblock.proxyPort");
421 config.remove("adblock.auth"); 421 config.remove("adblock.auth");
422 config.remove("adblock.proxyExcl"); 422 config.remove("adblock.proxyExcl");
423 if (!transparent) 423 if (!transparent)
424 { 424 {
425 config.remove("https.proxyHost"); 425 config.remove("https.proxyHost");
426 config.remove("https.proxyPort"); 426 config.remove("https.proxyPort");
(...skipping 11 matching lines...) Expand all
438 // proxy points to ourselves 438 // proxy points to ourselves
439 // proxy port is null, 0 or not a number 439 // proxy port is null, 0 or not a number
440 // proxy is 127.0.0.1:8080 440 // proxy is 127.0.0.1:8080
441 if (proxyPort == null) 441 if (proxyPort == null)
442 return; 442 return;
443 int p = 0; 443 int p = 0;
444 try 444 try
445 { 445 {
446 p = Integer.valueOf(proxyPort); 446 p = Integer.valueOf(proxyPort);
447 } 447 }
448 catch (NumberFormatException e) 448 catch (final NumberFormatException e)
449 { 449 {
450 return; 450 return;
451 } 451 }
452 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080)) 452 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080))
453 { 453 {
454 if (nativeProxyAutoConfigured) 454 if (nativeProxyAutoConfigured)
455 passProxySettings(null, null, null); 455 passProxySettings(null, null, null);
456 return; 456 return;
457 } 457 }
458 458
459 config.put("adblock.proxyHost", proxyHost); 459 config.put("adblock.proxyHost", proxyHost);
460 config.put("adblock.proxyPort", proxyPort); 460 config.put("adblock.proxyPort", proxyPort);
461 if (!transparent) 461 if (!transparent)
462 { 462 {
463 config.put("https.proxyHost", proxyHost); 463 config.put("https.proxyHost", proxyHost);
464 config.put("https.proxyPort", proxyPort); 464 config.put("https.proxyPort", proxyPort);
465 } 465 }
466 466
467 // TODO Not implemented in our proxy but needed to restore settings 467 // TODO Not implemented in our proxy but needed to restore settings
468 if (proxyExcl != null) 468 if (proxyExcl != null)
469 config.put("adblock.proxyExcl", proxyExcl); 469 config.put("adblock.proxyExcl", proxyExcl);
470 470
471 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e quals(proxyPass)) 471 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e quals(proxyPass))
472 { 472 {
473 // Base64 encode user:password 473 // Base64 encode user:password
474 String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + ":" + p roxyPass)); 474 final String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + " :" + proxyPass));
475 config.put("adblock.auth", proxyAuth); 475 config.put("adblock.auth", proxyAuth);
476 if (!transparent) 476 if (!transparent)
477 config.put("https.auth", proxyAuth); 477 config.put("https.auth", proxyAuth);
478 } 478 }
479 } 479 }
480 480
481 private void passProxySettings(String proxyHost, String proxyPort, String prox yExcl) 481 private void passProxySettings(final String proxyHost, final String proxyPort, final String proxyExcl)
482 { 482 {
483 try 483 try
484 { 484 {
485 CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExceptionHa ndler(); 485 final CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExcep tionHandler();
486 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl); 486 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl);
487 } 487 }
488 catch (ClassCastException e) 488 catch (final ClassCastException e)
489 { 489 {
490 // ignore - default handler in use 490 // ignore - default handler in use
491 } 491 }
492 } 492 }
493 493
494 @Override 494 @Override
495 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Str ing key) 495 public void onSharedPreferenceChanged(final SharedPreferences sharedPreference s, final String key)
496 { 496 {
497 if (!NATIVE_PROXY_SUPPORTED) 497 if (!NATIVE_PROXY_SUPPORTED)
498 { 498 {
499 String ketHost = getString(R.string.pref_proxyhost); 499 final String ketHost = getString(R.string.pref_proxyhost);
500 String keyPort = getString(R.string.pref_proxyport); 500 final String keyPort = getString(R.string.pref_proxyport);
501 String keyUser = getString(R.string.pref_proxyuser); 501 final String keyUser = getString(R.string.pref_proxyuser);
502 String keyPass = getString(R.string.pref_proxypass); 502 final String keyPass = getString(R.string.pref_proxypass);
503 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k ey.equals(keyPass)) 503 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k ey.equals(keyPass))
504 { 504 {
505 String proxyHost = sharedPreferences.getString(ketHost, null); 505 final String proxyHost = sharedPreferences.getString(ketHost, null);
506 String proxyPort = sharedPreferences.getString(keyPort, null); 506 final String proxyPort = sharedPreferences.getString(keyPort, null);
507 String proxyUser = sharedPreferences.getString(keyUser, null); 507 final String proxyUser = sharedPreferences.getString(keyUser, null);
508 String proxyPass = sharedPreferences.getString(keyPass, null); 508 final String proxyPass = sharedPreferences.getString(keyPass, null);
509 if (proxy != null) 509 if (proxy != null)
510 { 510 {
511 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro xyUser, proxyPass); 511 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro xyUser, proxyPass);
512 proxy.restart(proxyConfiguration.getProperty("handler")); 512 proxy.restart(proxyConfiguration.getProperty("handler"));
513 } 513 }
514 } 514 }
515 } 515 }
516 } 516 }
517 517
518 public boolean isTransparent() 518 public boolean isTransparent()
(...skipping 18 matching lines...) Expand all
537 * Checks whether traffic check is pending 537 * Checks whether traffic check is pending
538 */ 538 */
539 public boolean noTraffic() 539 public boolean noTraffic()
540 { 540 {
541 return notrafficHandler != null; 541 return notrafficHandler != null;
542 } 542 }
543 543
544 /** 544 /**
545 * Checks if specified host is local. 545 * Checks if specified host is local.
546 */ 546 */
547 private static final boolean isLocalHost(String host) 547 private static final boolean isLocalHost(final String host)
548 { 548 {
549 if (host == null) 549 if (host == null)
550 return false; 550 return false;
551 551
552 try 552 try
553 { 553 {
554 if (host.equalsIgnoreCase("localhost")) 554 if (host.equalsIgnoreCase("localhost"))
555 return true; 555 return true;
556 556
557 String className = "android.net.NetworkUtils"; 557 final String className = "android.net.NetworkUtils";
558 Class<?> c = Class.forName(className); 558 final Class<?> c = Class.forName(className);
559 /* 559 /*
560 * InetAddress address = NetworkUtils.numericToInetAddress(host); 560 * InetAddress address = NetworkUtils.numericToInetAddress(host);
561 */ 561 */
562 Method method = c.getMethod("numericToInetAddress", String.class); 562 final Method method = c.getMethod("numericToInetAddress", String.class);
563 InetAddress address = (InetAddress) method.invoke(null, host); 563 final InetAddress address = (InetAddress) method.invoke(null, host);
564 564
565 if (address.isLoopbackAddress()) 565 if (address.isLoopbackAddress())
566 return true; 566 return true;
567 } 567 }
568 catch (Exception e) 568 catch (final Exception e)
569 { 569 {
570 Log.w(TAG, null, e); 570 Log.w(TAG, null, e);
571 } 571 }
572 return false; 572 return false;
573 } 573 }
574 574
575 /** 575 /**
576 * Initializes iptables executable. 576 * Initializes iptables executable.
577 * 577 *
578 * @throws FileNotFoundException 578 * @throws FileNotFoundException
579 * If iptables initialization failed due to provided reasons. 579 * If iptables initialization failed due to provided reasons.
580 */ 580 */
581 private void initIptables() throws IOException, RootToolsException, TimeoutExc eption, FileNotFoundException 581 private void initIptables() throws IOException, RootToolsException, TimeoutExc eption, FileNotFoundException
582 { 582 {
583 if (!RootTools.isAccessGiven()) 583 if (!RootTools.isAccessGiven())
584 throw new FileNotFoundException("No root access"); 584 throw new FileNotFoundException("No root access");
585 585
586 File ipt = getFileStreamPath("iptables"); 586 final File ipt = getFileStreamPath("iptables");
587 587
588 if (!ipt.exists()) 588 if (!ipt.exists())
589 { 589 {
590 Log.e(TAG, "No iptables excutable found"); 590 Log.e(TAG, "No iptables excutable found");
591 throw new FileNotFoundException("No iptables executable"); 591 throw new FileNotFoundException("No iptables executable");
592 } 592 }
593 593
594 String path = ipt.getAbsolutePath(); 594 final String path = ipt.getAbsolutePath();
595 595
596 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT); 596 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT);
597 597
598 boolean compatible = false; 598 boolean compatible = false;
599 boolean version = false; 599 boolean version = false;
600 600
601 String command = path + " --version\n" + path + " -L -t nat -n\n"; 601 final String command = path + " --version\n" + path + " -L -t nat -n\n";
602 602
603 List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT); 603 final List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT);
604 for (String line : result) 604 for (final String line : result)
605 { 605 {
606 if (line.contains("OUTPUT")) 606 if (line.contains("OUTPUT"))
607 compatible = true; 607 compatible = true;
608 if (line.contains("v1.4.")) 608 if (line.contains("v1.4."))
609 version = true; 609 version = true;
610 } 610 }
611 611
612 if (!compatible || !version) 612 if (!compatible || !version)
613 { 613 {
614 Log.e(TAG, "Incompatible iptables excutable"); 614 Log.e(TAG, "Incompatible iptables excutable");
615 throw new FileNotFoundException("Incompatible iptables excutable"); 615 throw new FileNotFoundException("Incompatible iptables excutable");
616 } 616 }
617 617
618 iptables = path; 618 iptables = path;
619 } 619 }
620 620
621 public List<String> getIptablesOutput() 621 public List<String> getIptablesOutput()
622 { 622 {
623 if (iptables == null) 623 if (iptables == null)
624 return null; 624 return null;
625 625
626 String command = iptables + " -L -t nat -n\n"; 626 final String command = iptables + " -L -t nat -n\n";
627 try 627 try
628 { 628 {
629 return RootTools.sendShell(command, DEFAULT_TIMEOUT); 629 return RootTools.sendShell(command, DEFAULT_TIMEOUT);
630 } 630 }
631 catch (Exception e) 631 catch (final Exception e)
632 { 632 {
633 Log.e(TAG, "Failed to get iptables configuration", e); 633 Log.e(TAG, "Failed to get iptables configuration", e);
634 return null; 634 return null;
635 } 635 }
636 } 636 }
637 637
638 /** 638 /**
639 * Raises or removes no traffic notification based on current link proxy 639 * Raises or removes no traffic notification based on current link proxy
640 * settings 640 * settings
641 */ 641 */
642 private void updateNoTrafficCheck(ConnectivityManager connectivityManager) 642 private void updateNoTrafficCheck(final ConnectivityManager connectivityManage r)
643 { 643 {
644 try 644 try
645 { 645 {
646 Object pp = ProxySettings.getActiveLinkProxy(connectivityManager); 646 final Object pp = ProxySettings.getActiveLinkProxy(connectivityManager);
647 String[] userProxy = ProxySettings.getUserProxy(pp); 647 final String[] userProxy = ProxySettings.getUserProxy(pp);
648 if (userProxy != null) 648 if (userProxy != null)
649 Log.i(TAG, "Proxy settings: " + userProxy[0] + ":" + userProxy[1] + "(" + userProxy[2] + ")"); 649 Log.i(TAG, "Proxy settings: " + userProxy[0] + ":" + userProxy[1] + "(" + userProxy[2] + ")");
650 updateNoTrafficCheck(userProxy); 650 updateNoTrafficCheck(userProxy);
651 } 651 }
652 catch (Exception e) 652 catch (final Exception e)
653 { 653 {
654 // This should not happen 654 // This should not happen
655 Log.e(TAG, null, e); 655 Log.e(TAG, null, e);
656 } 656 }
657 } 657 }
658 658
659 /** 659 /**
660 * Raises or removes no traffic notification based on the user proxy settings 660 * Raises or removes no traffic notification based on the user proxy settings
661 */ 661 */
662 private void updateNoTrafficCheck(String[] userProxy) 662 private void updateNoTrafficCheck(final String[] userProxy)
663 { 663 {
664 boolean ourProxy = userProxy != null && isLocalHost(userProxy[0]) && Integer .valueOf(userProxy[1]) == port; 664 final boolean ourProxy = userProxy != null && isLocalHost(userProxy[0]) && I nteger.valueOf(userProxy[1]) == port;
665 if (ourProxy != proxyManualyConfigured) 665 if (ourProxy != proxyManualyConfigured)
666 { 666 {
667 proxyManualyConfigured = ourProxy; 667 proxyManualyConfigured = ourProxy;
668 sendStateChangedBroadcast(); 668 sendStateChangedBroadcast();
669 } 669 }
670 if (ourProxy) 670 if (ourProxy)
671 { 671 {
672 stopNoTrafficCheck(); 672 stopNoTrafficCheck();
673 } 673 }
674 else 674 else
675 { 675 {
676 // Initiate no traffic check 676 // Initiate no traffic check
677 notrafficHandler = new Handler(); 677 notrafficHandler = new Handler();
678 notrafficHandler.postDelayed(noTraffic, NO_TRAFFIC_TIMEOUT); 678 notrafficHandler.postDelayed(noTraffic, NO_TRAFFIC_TIMEOUT);
679 } 679 }
680 NotificationManager notificationManager = (NotificationManager) getSystemSer vice(NOTIFICATION_SERVICE); 680 final NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE);
681 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 681 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
682 } 682 }
683 683
684 /** 684 /**
685 * Stops no traffic check and resets notification message. 685 * Stops no traffic check and resets notification message.
686 */ 686 */
687 private void stopNoTrafficCheck() 687 private void stopNoTrafficCheck()
688 { 688 {
689 if (notrafficHandler != null) 689 if (notrafficHandler != null)
690 { 690 {
691 notrafficHandler.removeCallbacks(noTraffic); 691 notrafficHandler.removeCallbacks(noTraffic);
692 sendStateChangedBroadcast(); 692 sendStateChangedBroadcast();
693 NotificationManager notificationManager = (NotificationManager) getSystemS ervice(NOTIFICATION_SERVICE); 693 final NotificationManager notificationManager = (NotificationManager) getS ystemService(NOTIFICATION_SERVICE);
694 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 694 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
695 notificationManager.cancel(NOTRAFFIC_NOTIFICATION_ID); 695 notificationManager.cancel(NOTRAFFIC_NOTIFICATION_ID);
696 } 696 }
697 notrafficHandler = null; 697 notrafficHandler = null;
698 } 698 }
699 699
700 @SuppressLint("NewApi") 700 @SuppressLint("NewApi")
701 private Notification getNotification() 701 private Notification getNotification()
702 { 702 {
703 boolean filtering = AdblockPlus.getApplication().isFilteringEnabled(); 703 final boolean filtering = AdblockPlus.getApplication().isFilteringEnabled();
704 704
705 int msgId = R.string.notif_waiting; 705 int msgId = R.string.notif_waiting;
706 if (nativeProxyAutoConfigured || proxyManualyConfigured) 706 if (nativeProxyAutoConfigured || proxyManualyConfigured)
707 msgId = filtering ? R.string.notif_wifi : R.string.notif_wifi_nofiltering; 707 msgId = filtering ? R.string.notif_wifi : R.string.notif_wifi_nofiltering;
708 if (transparent) 708 if (transparent)
709 msgId = R.string.notif_all; 709 msgId = R.string.notif_all;
710 710
711 NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 711 final NotificationCompat.Builder builder = new NotificationCompat.Builder(th is);
712 if (hideIcon && msgId != R.string.notif_waiting) 712 if (hideIcon && msgId != R.string.notif_waiting)
713 { 713 {
714 builder.setWhen(POSITION_RIGHT); 714 builder.setWhen(POSITION_RIGHT);
715 builder.setSmallIcon(R.drawable.transparent); 715 builder.setSmallIcon(R.drawable.transparent);
716 //builder.setContent(new RemoteViews(getPackageName(), R.layout.notif_hidd en)); 716 // builder.setContent(new RemoteViews(getPackageName(), R.layout.notif_hid den));
717 } 717 }
718 else 718 else
719 { 719 {
720 builder.setWhen(0); 720 builder.setWhen(0);
721 builder.setSmallIcon(R.drawable.ic_stat_blocking); 721 builder.setSmallIcon(R.drawable.ic_stat_blocking);
722 } 722 }
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); 723 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); 724 builder.setContentIntent(contentIntent);
725 builder.setContentTitle(getText(R.string.app_name)); 725 builder.setContentTitle(getText(R.string.app_name));
726 builder.setContentText(getString(msgId, port)); 726 builder.setContentText(getString(msgId, port));
727 builder.setOngoing(true); 727 builder.setOngoing(true);
728 728
729 Notification notification = builder.getNotification(); 729 final Notification notification = builder.getNotification();
730 return notification; 730 return notification;
731 } 731 }
732 732
733 public void setEmptyIcon(boolean hide) 733 public void setEmptyIcon(final boolean hide)
734 { 734 {
735 hideIcon = hide; 735 hideIcon = hide;
736 NotificationManager notificationManager = (NotificationManager) getSystemSer vice(NOTIFICATION_SERVICE); 736 final NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE);
737 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()); 737 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification());
738 } 738 }
739 739
740 public void sendStateChangedBroadcast() 740 public void sendStateChangedBroadcast()
741 { 741 {
742 Log.i(TAG, "Broadcasting " + BROADCAST_STATE_CHANGED); 742 Log.i(TAG, "Broadcasting " + BROADCAST_STATE_CHANGED);
743 boolean manual = isManual(); 743 final boolean manual = isManual();
744 Intent stateIntent = new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", true).putExtra("port", port).putExtra("manual", manual); 744 final Intent stateIntent = new Intent(BROADCAST_STATE_CHANGED).putExtra("ena bled", true).putExtra("port", port).putExtra("manual", manual);
745 if (manual) 745 if (manual)
746 stateIntent.putExtra("configured", proxyManualyConfigured); 746 stateIntent.putExtra("configured", proxyManualyConfigured);
747 sendBroadcast(stateIntent); 747 sendBroadcast(stateIntent);
748 } 748 }
749 749
750 private final IBinder binder = new LocalBinder(); 750 private final IBinder binder = new LocalBinder();
751 751
752 public final class LocalBinder extends Binder 752 public final class LocalBinder extends Binder
753 { 753 {
754 public ProxyService getService() 754 public ProxyService getService()
755 { 755 {
756 return ProxyService.this; 756 return ProxyService.this;
757 } 757 }
758 } 758 }
759 759
760 @Override 760 @Override
761 public IBinder onBind(Intent intent) 761 public IBinder onBind(final Intent intent)
762 { 762 {
763 return binder; 763 return binder;
764 } 764 }
765 765
766 /** 766 /**
767 * Executed if no traffic is detected after a period of time. Notifies user 767 * Executed if no traffic is detected after a period of time. Notifies user
768 * about possible configuration problems. 768 * about possible configuration problems.
769 */ 769 */
770 private Runnable noTraffic = new Runnable() 770 private final Runnable noTraffic = new Runnable()
771 { 771 {
772 @Override
772 public void run() 773 public void run()
773 { 774 {
774 // It's weird but notrafficHandler.removeCallbacks(noTraffic) does not rem ove this callback 775 // It's weird but notrafficHandler.removeCallbacks(noTraffic) does not rem ove this callback
775 if (notrafficHandler == null) 776 if (notrafficHandler == null)
776 return; 777 return;
777 // Show warning notification 778 // Show warning notification
778 NotificationCompat.Builder builder = new NotificationCompat.Builder(ProxyS ervice.this); 779 final NotificationCompat.Builder builder = new NotificationCompat.Builder( ProxyService.this);
779 builder.setSmallIcon(R.drawable.ic_stat_warning); 780 builder.setSmallIcon(R.drawable.ic_stat_warning);
780 builder.setWhen(System.currentTimeMillis()); 781 builder.setWhen(System.currentTimeMillis());
781 builder.setAutoCancel(true); 782 builder.setAutoCancel(true);
782 Intent intent = new Intent(ProxyService.this, ConfigurationActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 783 final Intent intent = new Intent(ProxyService.this, ConfigurationActivity. class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
783 intent.putExtra("port", port); 784 intent.putExtra("port", port);
784 PendingIntent contentIntent = PendingIntent.getActivity(ProxyService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 785 final PendingIntent contentIntent = PendingIntent.getActivity(ProxyService .this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
785 builder.setContentIntent(contentIntent); 786 builder.setContentIntent(contentIntent);
786 builder.setContentTitle(getText(R.string.app_name)); 787 builder.setContentTitle(getText(R.string.app_name));
787 builder.setContentText(getText(R.string.notif_notraffic)); 788 builder.setContentText(getText(R.string.notif_notraffic));
788 NotificationManager notificationManager = (NotificationManager) getSystemS ervice(NOTIFICATION_SERVICE); 789 final NotificationManager notificationManager = (NotificationManager) getS ystemService(NOTIFICATION_SERVICE);
789 notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, builder.getNotificat ion()); 790 notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, builder.getNotificat ion());
790 } 791 }
791 }; 792 };
792 793
793 /** 794 /**
794 * Stops no traffic check if traffic is detected by proxy service. 795 * Stops no traffic check if traffic is detected by proxy service.
795 */ 796 */
796 private BroadcastReceiver filterReceiver = new BroadcastReceiver() 797 private final BroadcastReceiver filterReceiver = new BroadcastReceiver()
797 { 798 {
798 @Override 799 @Override
799 public void onReceive(final Context context, Intent intent) 800 public void onReceive(final Context context, final Intent intent)
800 { 801 {
801 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTERING_CHANGE)) 802 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTERING_CHANGE))
802 { 803 {
803 // It's rather a hack but things are happening simultaneously and we 804 // It's rather a hack but things are happening simultaneously and we
804 // receive this broadcast despite the fact we have unsubscribed from 805 // receive this broadcast despite the fact we have unsubscribed from
805 // it and notification is not removed because it is changed to new one 806 // it and notification is not removed because it is changed to new one
806 // during removal. 807 // during removal.
807 if (!ProxyService.this.isNativeProxyAutoConfigured()) 808 if (!isNativeProxyAutoConfigured())
808 { 809 {
809 NotificationManager notificationManager = (NotificationManager) getSys temService(NOTIFICATION_SERVICE); 810 final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
810 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()) ; 811 notificationManager.notify(ONGOING_NOTIFICATION_ID, getNotification()) ;
811 } 812 }
812 } 813 }
813 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTER_MATCHES)) 814 if (intent.getAction().equals(AdblockPlus.BROADCAST_FILTER_MATCHES))
814 { 815 {
815 proxyManualyConfigured = true; 816 proxyManualyConfigured = true;
816 stopNoTrafficCheck(); 817 stopNoTrafficCheck();
817 } 818 }
818 } 819 }
819 }; 820 };
820 821
821 /** 822 /**
822 * Stops service if proxy fails. 823 * Stops service if proxy fails.
823 */ 824 */
824 private BroadcastReceiver proxyReceiver = new BroadcastReceiver() 825 private final BroadcastReceiver proxyReceiver = new BroadcastReceiver()
825 { 826 {
826 @Override 827 @Override
827 public void onReceive(final Context context, Intent intent) 828 public void onReceive(final Context context, final Intent intent)
828 { 829 {
829 if (intent.getAction().equals(ProxyService.BROADCAST_PROXY_FAILED)) 830 if (intent.getAction().equals(ProxyService.BROADCAST_PROXY_FAILED))
830 { 831 {
831 stopSelf(); 832 stopSelf();
832 } 833 }
833 } 834 }
834 }; 835 };
835 836
836 /** 837 /**
837 * Monitors system network connection settings changes and updates proxy 838 * Monitors system network connection settings changes and updates proxy
838 * settings accordingly. 839 * settings accordingly.
839 */ 840 */
840 private BroadcastReceiver connectionReceiver = new BroadcastReceiver() 841 private final BroadcastReceiver connectionReceiver = new BroadcastReceiver()
841 { 842 {
842 @Override 843 @Override
843 public void onReceive(Context ctx, Intent intent) 844 public void onReceive(final Context ctx, final Intent intent)
844 { 845 {
845 String action = intent.getAction(); 846 final String action = intent.getAction();
846 Log.i(TAG, "Action: " + action); 847 Log.i(TAG, "Action: " + action);
847 // Connectivity change 848 // Connectivity change
848 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) 849 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
849 { 850 {
850 ConnectivityManager connectivityManager = (ConnectivityManager) getSyste mService(Context.CONNECTIVITY_SERVICE); 851 final ConnectivityManager connectivityManager = (ConnectivityManager) ge tSystemService(Context.CONNECTIVITY_SERVICE);
851 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc ast() instead? 852 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc ast() instead?
852 NetworkInfo info = connectivityManager.getActiveNetworkInfo(); 853 final NetworkInfo info = connectivityManager.getActiveNetworkInfo();
853 if (info == null) 854 if (info == null)
854 return; 855 return;
855 String typeName = info.getTypeName(); 856 final String typeName = info.getTypeName();
856 String subtypeName = info.getSubtypeName(); 857 final String subtypeName = info.getSubtypeName();
857 boolean available = info.isAvailable(); 858 final boolean available = info.isAvailable();
858 859
859 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + " , available: " + available); 860 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + " , available: " + available);
860 if (info.getType() == ConnectivityManager.TYPE_WIFI) 861 if (info.getType() == ConnectivityManager.TYPE_WIFI)
861 { 862 {
862 if (nativeProxyAutoConfigured) 863 if (nativeProxyAutoConfigured)
863 { 864 {
864 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port, ""); 865 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port, "");
865 } 866 }
866 else 867 else
867 { 868 {
868 updateNoTrafficCheck(connectivityManager); 869 updateNoTrafficCheck(connectivityManager);
869 } 870 }
870 } 871 }
871 } 872 }
872 // Proxy change 873 // Proxy change
873 else if (Proxy.PROXY_CHANGE_ACTION.equals(action)) 874 else if (Proxy.PROXY_CHANGE_ACTION.equals(action))
874 { 875 {
875 Object pp = intent.getParcelableExtra("proxy"); 876 final Object pp = intent.getParcelableExtra("proxy");
876 try 877 try
877 { 878 {
878 String[] userProxy = ProxySettings.getUserProxy(pp); 879 final String[] userProxy = ProxySettings.getUserProxy(pp);
879 if (nativeProxyAutoConfigured) 880 if (nativeProxyAutoConfigured)
880 { 881 {
881 if (userProxy != null && Integer.valueOf(userProxy[1]) != port) 882 if (userProxy != null && Integer.valueOf(userProxy[1]) != port)
882 { 883 {
883 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP roxy[1] + "(" + userProxy[2] + ")"); 884 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP roxy[1] + "(" + userProxy[2] + ")");
884 if (proxy != null) 885 if (proxy != null)
885 { 886 {
886 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1 ], userProxy[2], null, null); 887 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1 ], userProxy[2], null, null);
887 proxy.restart(proxyConfiguration.getProperty("handler")); 888 proxy.restart(proxyConfiguration.getProperty("handler"));
888 } 889 }
889 } 890 }
890 } 891 }
891 else 892 else
892 { 893 {
893 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1 ] + "(" + userProxy[2] + ")"); 894 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1 ] + "(" + userProxy[2] + ")");
894 updateNoTrafficCheck(userProxy); 895 updateNoTrafficCheck(userProxy);
895 } 896 }
896 } 897 }
897 catch (Exception e) 898 catch (final Exception e)
898 { 899 {
899 // This should not happen 900 // This should not happen
900 Log.e(TAG, null, e); 901 Log.e(TAG, null, e);
901 } 902 }
902 } 903 }
903 } 904 }
904 }; 905 };
905 906
906 final class ProxyServer extends Server 907 final class ProxyServer extends Server
907 { 908 {
908 @Override 909 @Override
909 public void close() 910 public void close()
910 { 911 {
911 try 912 try
912 { 913 {
913 listen.close(); 914 listen.close();
914 this.interrupt(); 915 this.interrupt();
915 this.join(); 916 this.join();
916 } 917 }
917 catch (Exception e) 918 catch (final Exception e)
918 { 919 {
919 // ignore - it always happens 920 // ignore - it always happens
920 } 921 }
921 log(LOG_WARNING, null, "server stopped"); 922 log(LOG_WARNING, null, "server stopped");
922 } 923 }
923 924
924 @Override 925 @Override
925 public void log(int level, Object obj, String message) 926 public void log(final int level, final Object obj, final String message)
926 { 927 {
927 if (level <= logLevel) 928 if (level <= logLevel)
928 { 929 {
929 Log.println(7 - level, obj != null ? obj.toString() : TAG, message); 930 Log.println(7 - level, obj != null ? obj.toString() : TAG, message);
930 } 931 }
931 } 932 }
932 } 933 }
933 } 934 }
OLDNEW

Powered by Google App Engine
This is Rietveld