OLD | NEW |
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 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
52 import android.os.StrictMode; | 52 import android.os.StrictMode; |
53 import android.preference.PreferenceManager; | 53 import android.preference.PreferenceManager; |
54 import android.support.v4.app.NotificationCompat; | 54 import android.support.v4.app.NotificationCompat; |
55 import android.util.Log; | 55 import android.util.Log; |
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"; | |
63 /** | |
64 * Indicates that system supports native proxy configuration. | |
65 */ | |
66 public static final boolean NATIVE_PROXY_SUPPORTED = Build.VERSION.SDK_INT >=
12; // Honeycomb 3.1 | |
67 | |
68 static | 62 static |
69 { | 63 { |
70 RootTools.debugMode = false; | 64 RootTools.debugMode = false; |
71 } | 65 } |
72 | 66 |
73 private static final String TAG = "ProxyService"; | 67 private static final String TAG = Utils.getTag(ProxyService.class); |
| 68 |
| 69 private static final String LOCALHOST = "127.0.0.1"; |
| 70 /** |
| 71 * Indicates that system supports native proxy configuration. |
| 72 */ |
74 private static final boolean logRequests = false; | 73 private static final boolean logRequests = false; |
75 | 74 |
76 // Do not use 8080 because it is a "dirty" port, Android uses it if something
goes wrong | 75 public static final boolean NATIVE_PROXY_SUPPORTED = Build.VERSION.SDK_INT >=
12; // Honeycomb |
77 // First element is reserved for previously used port | 76 private static final int NOTRAFFIC_NOTIFICATION_ID = R.string.app_name + 3; |
78 private static final int[] portVariants = new int[] {-1, 2020, 3030, 4040, 505
0, 6060, 7070, 9090, 1234, 12345, 4321, 0}; | 77 static final int ONGOING_NOTIFICATION_ID = R.string.app_name; |
79 | 78 |
80 private final static int DEFAULT_TIMEOUT = 3000; | 79 private static final long POSITION_RIGHT = Build.VERSION.SDK_INT >= Build.VERS
ION_CODES.GINGERBREAD ? Long.MIN_VALUE : Long.MAX_VALUE; |
81 private final static int NO_TRAFFIC_TIMEOUT = 5 * 60 * 1000; // 5 minutes | |
82 | 80 |
83 final static int ONGOING_NOTIFICATION_ID = R.string.app_name; | 81 private static final int DEFAULT_TIMEOUT = 3000; |
84 private static final long POSITION_RIGHT = Build.VERSION.SDK_INT >= Build.VERS
ION_CODES.GINGERBREAD ? Long.MIN_VALUE : Long.MAX_VALUE; | 82 private static final int NO_TRAFFIC_TIMEOUT = 5 * 60 * 1000; // 5 minutes |
85 private final static int NOTRAFFIC_NOTIFICATION_ID = R.string.app_name + 3; | 83 |
| 84 // Do not use 8080 because it is a "dirty" port, Android uses it if something |
| 85 // goes wrong |
| 86 // first element is reserved for previously used port |
| 87 private static final int[] portVariants = new int[] { -1, 2020, 3030, 4040, 50
50, 6060, 7070, 9090, 1234, 12345, 4321, 0 }; |
86 | 88 |
87 /** | 89 /** |
88 * Broadcasted when service starts or stops. | 90 * Broadcasted when service starts or stops. |
89 */ | 91 */ |
90 public final static String BROADCAST_STATE_CHANGED = "org.adblockplus.android.
service.state"; | 92 public static final String BROADCAST_STATE_CHANGED = "org.adblockplus.android.
service.state"; |
91 /** | 93 /** |
92 * Broadcasted if proxy fails to start. | 94 * Broadcasted if proxy fails to start. |
93 */ | 95 */ |
94 public final static String BROADCAST_PROXY_FAILED = "org.adblockplus.android.p
roxy.failure"; | 96 public static final String BROADCAST_PROXY_FAILED = "org.adblockplus.android.p
roxy.failure"; |
95 | 97 |
96 private final static String IPTABLES_RETURN = " -t nat -m owner --uid-owner {{
UID}} -A OUTPUT -p tcp -j RETURN\n"; | 98 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"; | 99 private static final String IPTABLES_ADD_HTTP = " -t nat -A OUTPUT -p tcp --dp
ort 80 -j REDIRECT --to {{PORT}}\n"; |
98 | 100 |
99 boolean hideIcon; | 101 boolean hideIcon; |
100 private Handler notrafficHandler; | 102 private Handler notrafficHandler; |
101 | 103 |
102 protected ProxyServer proxy = null; | 104 protected ProxyServer proxy = null; |
103 protected int port; | 105 protected int port; |
104 private Properties proxyConfiguration = new Properties(); | 106 private final Properties proxyConfiguration = new Properties(); |
105 | 107 |
106 /** | 108 /** |
107 * Indicates that service is working with root privileges. | 109 * Indicates that service is working with root privileges. |
108 */ | 110 */ |
109 private boolean transparent = false; | 111 private boolean transparent = false; |
110 /** | 112 /** |
111 * Indicates that service has autoconfigured Android proxy settings (version 3
.1+). | 113 * Indicates that service has autoconfigured Android proxy settings (version 3
.1+). |
112 */ | 114 */ |
113 private boolean nativeProxyAutoConfigured = false; | 115 private boolean nativeProxyAutoConfigured = false; |
114 /** | 116 /** |
115 * Indicates that Android proxy settings are correctly configured (version 4.1
.2+ 4.2.2+). | 117 * Indicates that Android proxy settings are correctly configured (version 4.1
.2+ 4.2.2+). |
116 */ | 118 */ |
117 private boolean proxyManualyConfigured = false; | 119 private boolean proxyManualyConfigured = false; |
118 | 120 |
119 private String iptables = null; | 121 private String iptables = null; |
120 | 122 |
121 @SuppressLint("NewApi") | 123 @SuppressLint("NewApi") |
122 @Override | 124 @Override |
123 public void onCreate() | 125 public void onCreate() |
124 { | 126 { |
125 super.onCreate(); | 127 super.onCreate(); |
126 | 128 |
127 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) | 129 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) |
128 { | 130 { |
129 // Proxy is running in separate thread, it's just some resolution request
during initialization. | 131 // Proxy is running in separate thread, it's just some resolution request
during initialization. |
130 // Not worth spawning a separate thread for this. | 132 // Not worth spawning a separate thread for this. |
131 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().per
mitNetwork().build(); | 133 final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder
().permitNetwork().build(); |
132 StrictMode.setThreadPolicy(policy); | 134 StrictMode.setThreadPolicy(policy); |
133 } | 135 } |
134 | 136 |
135 // Get port for local proxy | 137 // Get port for local proxy |
136 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this
); | 138 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreference
s(this); |
137 Resources resources = getResources(); | 139 final Resources resources = getResources(); |
138 | 140 |
139 // Try to read user proxy settings | 141 // Try to read user proxy settings |
140 String proxyHost = null; | 142 String proxyHost = null; |
141 String proxyPort = null; | 143 String proxyPort = null; |
142 String proxyExcl = null; | 144 String proxyExcl = null; |
143 String proxyUser = null; | 145 String proxyUser = null; |
144 String proxyPass = null; | 146 String proxyPass = null; |
145 | 147 |
146 if (NATIVE_PROXY_SUPPORTED) | 148 if (NATIVE_PROXY_SUPPORTED) |
147 { | 149 { |
148 // Read system settings | 150 // Read system settings |
149 proxyHost = System.getProperty("http.proxyHost"); | 151 proxyHost = System.getProperty("http.proxyHost"); |
150 proxyPort = System.getProperty("http.proxyPort"); | 152 proxyPort = System.getProperty("http.proxyPort"); |
151 proxyExcl = System.getProperty("http.nonProxyHosts"); | 153 proxyExcl = System.getProperty("http.nonProxyHosts"); |
152 | 154 |
153 Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")"); | 155 Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")"); |
154 // not used but left for future reference | 156 // not used but left for future reference |
155 String[] px = ProxySettings.getUserProxy(getApplicationContext()); | 157 final String[] px = ProxySettings.getUserProxy(getApplicationContext()); |
156 if (px != null) | 158 if (px != null) |
157 Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")"); | 159 Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")"); |
158 } | 160 } |
159 else | 161 else |
160 { | 162 { |
161 // Read application settings | 163 // Read application settings |
162 proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null); | 164 proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null); |
163 proxyPort = prefs.getString(getString(R.string.pref_proxyport), null); | 165 proxyPort = prefs.getString(getString(R.string.pref_proxyport), null); |
164 proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null); | 166 proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null); |
165 proxyPass = prefs.getString(getString(R.string.pref_proxypass), null); | 167 proxyPass = prefs.getString(getString(R.string.pref_proxypass), null); |
166 } | 168 } |
167 | 169 |
168 // Check for root privileges and try to install transparent proxy | 170 // Check for root privileges and try to install transparent proxy |
169 if (RootTools.isAccessGiven()) | 171 if (RootTools.isAccessGiven()) |
170 { | 172 { |
171 try | 173 try |
172 { | 174 { |
173 initIptables(); | 175 initIptables(); |
174 | 176 |
175 StringBuffer cmd = new StringBuffer(); | 177 final StringBuffer cmd = new StringBuffer(); |
176 int uid = getPackageManager().getPackageInfo(getPackageName(), 0).applic
ationInfo.uid; | 178 final int uid = getPackageManager().getPackageInfo(getPackageName(), 0).
applicationInfo.uid; |
177 cmd.append(iptables); | 179 cmd.append(iptables); |
178 cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid))); | 180 cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid))); |
179 String rules = cmd.toString(); | 181 final String rules = cmd.toString(); |
180 RootTools.sendShell(rules, DEFAULT_TIMEOUT); | 182 RootTools.sendShell(rules, DEFAULT_TIMEOUT); |
181 transparent = true; | 183 transparent = true; |
182 } | 184 } |
183 catch (FileNotFoundException e) | 185 catch (final FileNotFoundException e) |
184 { | 186 { |
185 // ignore - this is "normal" case | 187 // ignore - this is "normal" case |
186 } | 188 } |
187 catch (NameNotFoundException e) | 189 catch (final NameNotFoundException e) |
188 { | 190 { |
189 Log.e(TAG, "Failed to initialize iptables", e); | 191 Log.e(TAG, "Failed to initialize iptables", e); |
190 } | 192 } |
191 catch (IOException e) | 193 catch (final IOException e) |
192 { | 194 { |
193 Log.e(TAG, "Failed to initialize iptables", e); | 195 Log.e(TAG, "Failed to initialize iptables", e); |
194 } | 196 } |
195 catch (RootToolsException e) | 197 catch (final RootToolsException e) |
196 { | 198 { |
197 Log.e(TAG, "Failed to initialize iptables", e); | 199 Log.e(TAG, "Failed to initialize iptables", e); |
198 } | 200 } |
199 catch (TimeoutException e) | 201 catch (final TimeoutException e) |
200 { | 202 { |
201 Log.e(TAG, "Failed to initialize iptables", e); | 203 Log.e(TAG, "Failed to initialize iptables", e); |
202 } | 204 } |
203 } | 205 } |
204 | 206 |
205 if (!transparent) | 207 if (!transparent) |
206 { | 208 { |
207 // Try to set native proxy | 209 // Try to set native proxy |
208 nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicatio
nContext(), LOCALHOST, port, ""); | 210 nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicatio
nContext(), LOCALHOST, port, ""); |
209 | 211 |
210 if (NATIVE_PROXY_SUPPORTED) | 212 if (NATIVE_PROXY_SUPPORTED) |
211 { | 213 { |
212 registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManage
r.CONNECTIVITY_ACTION)); | 214 registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManage
r.CONNECTIVITY_ACTION)); |
213 registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE
_ACTION)); | 215 registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE
_ACTION)); |
214 } | 216 } |
215 } | 217 } |
216 | 218 |
217 // Save current native proxy situation. The service is always started on the
first run so | 219 // 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 | 220 // we will always have a correct value from the box |
219 SharedPreferences.Editor editor = prefs.edit(); | 221 final SharedPreferences.Editor editor = prefs.edit(); |
220 editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent
|| nativeProxyAutoConfigured); | 222 editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent
|| nativeProxyAutoConfigured); |
221 editor.commit(); | 223 editor.commit(); |
222 | 224 |
223 registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROX
Y_FAILED)); | 225 registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROX
Y_FAILED)); |
224 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT
ERING_CHANGE)); | 226 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT
ERING_CHANGE)); |
225 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT
ER_MATCHES)); | 227 registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILT
ER_MATCHES)); |
226 | 228 |
227 // Start proxy | 229 // Start proxy |
228 if (proxy == null) | 230 if (proxy == null) |
229 { | 231 { |
230 // Select available port and bind to it, use previously selected port by d
efault | 232 // 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); | 233 portVariants[0] = prefs.getInt(getString(R.string.pref_lastport), -1); |
232 ServerSocket listen = null; | 234 ServerSocket listen = null; |
233 String msg = null; | 235 String msg = null; |
234 for (int p : portVariants) | 236 for (final int p : portVariants) |
235 { | 237 { |
236 if (p < 0) | 238 if (p < 0) |
237 continue; | 239 continue; |
238 try | 240 try |
239 { | 241 { |
240 // Fix for #232, bind proxy socket to loopback only | 242 // Fix for #232, bind proxy socket to loopback only |
241 listen = new ServerSocket(p, 1024, InetAddress.getByName(LOCALHOST)); | 243 listen = new ServerSocket(p, 1024, InetAddress.getByName(LOCALHOST)); |
242 port = p; | 244 port = p; |
243 break; | 245 break; |
244 } | 246 } |
245 catch (IOException e) | 247 catch (final IOException e) |
246 { | 248 { |
247 Log.e(TAG, null, e); | 249 Log.e(TAG, null, e); |
248 msg = e.getMessage(); | 250 msg = e.getMessage(); |
249 } | 251 } |
250 } | 252 } |
251 if (listen == null) | 253 if (listen == null) |
252 { | 254 { |
253 sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg)); | 255 sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg)); |
254 return; | 256 return; |
255 } | 257 } |
(...skipping 26 matching lines...) Expand all Loading... |
282 proxy.logLevel = Server.LOG_DIAGNOSTIC; | 284 proxy.logLevel = Server.LOG_DIAGNOSTIC; |
283 proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfig
uration); | 285 proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfig
uration); |
284 proxy.start(); | 286 proxy.start(); |
285 } | 287 } |
286 | 288 |
287 if (transparent) | 289 if (transparent) |
288 { | 290 { |
289 // Redirect traffic via iptables | 291 // Redirect traffic via iptables |
290 try | 292 try |
291 { | 293 { |
292 StringBuffer cmd = new StringBuffer(); | 294 final StringBuffer cmd = new StringBuffer(); |
293 cmd.append(iptables); | 295 cmd.append(iptables); |
294 cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port))); | 296 cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port))); |
295 String rules = cmd.toString(); | 297 final String rules = cmd.toString(); |
296 RootTools.sendShell(rules, DEFAULT_TIMEOUT); | 298 RootTools.sendShell(rules, DEFAULT_TIMEOUT); |
297 } | 299 } |
298 catch (FileNotFoundException e) | 300 catch (final FileNotFoundException e) |
299 { | 301 { |
300 // ignore - this is "normal" case | 302 // ignore - this is "normal" case |
301 } | 303 } |
302 catch (IOException e) | 304 catch (final IOException e) |
303 { | 305 { |
304 Log.e(TAG, "Failed to initialize iptables", e); | 306 Log.e(TAG, "Failed to initialize iptables", e); |
305 } | 307 } |
306 catch (RootToolsException e) | 308 catch (final RootToolsException e) |
307 { | 309 { |
308 Log.e(TAG, "Failed to initialize iptables", e); | 310 Log.e(TAG, "Failed to initialize iptables", e); |
309 } | 311 } |
310 catch (TimeoutException e) | 312 catch (final TimeoutException e) |
311 { | 313 { |
312 Log.e(TAG, "Failed to initialize iptables", e); | 314 Log.e(TAG, "Failed to initialize iptables", e); |
313 } | 315 } |
314 } | 316 } |
315 | 317 |
316 prefs.registerOnSharedPreferenceChangeListener(this); | 318 prefs.registerOnSharedPreferenceChangeListener(this); |
317 | 319 |
318 // Lock service | 320 // Lock service |
319 hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.get
Boolean(R.bool.def_hideicon)); | 321 hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.get
Boolean(R.bool.def_hideicon)); |
320 startForeground(ONGOING_NOTIFICATION_ID, getNotification()); | 322 startForeground(ONGOING_NOTIFICATION_ID, getNotification()); |
321 | 323 |
322 // If automatic setting of proxy was blocked, check if user has set it manua
lly | 324 // If automatic setting of proxy was blocked, check if user has set it manua
lly |
323 boolean manual = isManual(); | 325 final boolean manual = isManual(); |
324 if (manual && NATIVE_PROXY_SUPPORTED) | 326 if (manual && NATIVE_PROXY_SUPPORTED) |
325 { | 327 { |
326 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemS
ervice(Context.CONNECTIVITY_SERVICE); | 328 final ConnectivityManager connectivityManager = (ConnectivityManager) getS
ystemService(Context.CONNECTIVITY_SERVICE); |
327 updateNoTrafficCheck(connectivityManager); | 329 updateNoTrafficCheck(connectivityManager); |
328 } | 330 } |
329 | 331 |
330 sendStateChangedBroadcast(); | 332 sendStateChangedBroadcast(); |
331 Log.i(TAG, "Service started"); | 333 Log.i(TAG, "Service started"); |
332 } | 334 } |
333 | 335 |
334 @Override | 336 @Override |
335 public int onStartCommand(Intent intent, int flags, int startId) | 337 public int onStartCommand(final Intent intent, final int flags, final int star
tId) |
336 { | 338 { |
337 return START_STICKY; | 339 return START_STICKY; |
338 } | 340 } |
339 | 341 |
340 @Override | 342 @Override |
341 public void onDestroy() | 343 public void onDestroy() |
342 { | 344 { |
343 super.onDestroy(); | 345 super.onDestroy(); |
344 | 346 |
345 stopNoTrafficCheck(); | 347 stopNoTrafficCheck(); |
346 | 348 |
347 unregisterReceiver(filterReceiver); | 349 unregisterReceiver(filterReceiver); |
348 unregisterReceiver(proxyReceiver); | 350 unregisterReceiver(proxyReceiver); |
349 | 351 |
350 // Stop IP redirecting | 352 // Stop IP redirecting |
351 if (transparent) | 353 if (transparent) |
352 { | 354 { |
353 new Thread() | 355 new Thread() |
354 { | 356 { |
355 @Override | 357 @Override |
356 public void run() | 358 public void run() |
357 { | 359 { |
358 try | 360 try |
359 { | 361 { |
360 RootTools.sendShell(iptables + " -t nat -F OUTPUT", DEFAULT_TIMEOUT)
; | 362 RootTools.sendShell(iptables + " -t nat -F OUTPUT", DEFAULT_TIMEOUT)
; |
361 } | 363 } |
362 catch (Exception e) | 364 catch (final Exception e) |
363 { | 365 { |
364 Log.e(TAG, "Failed to clear iptables", e); | 366 Log.e(TAG, "Failed to clear iptables", e); |
365 } | 367 } |
366 } | 368 } |
367 }.start(); | 369 }.start(); |
368 } | 370 } |
369 | 371 |
370 if (!transparent && NATIVE_PROXY_SUPPORTED) | 372 if (!transparent && NATIVE_PROXY_SUPPORTED) |
371 unregisterReceiver(connectionReceiver); | 373 unregisterReceiver(connectionReceiver); |
372 | 374 |
373 // Clear native proxy | 375 // Clear native proxy |
374 if (nativeProxyAutoConfigured) | 376 if (nativeProxyAutoConfigured) |
375 { | 377 { |
376 clearConnectionProxy(); | 378 clearConnectionProxy(); |
377 } | 379 } |
378 | 380 |
379 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", false)
); | 381 sendBroadcast(new Intent(BROADCAST_STATE_CHANGED).putExtra("enabled", false)
); |
380 | 382 |
381 // Stop proxy server | 383 // Stop proxy server |
382 if (proxy != null) | 384 if (proxy != null) |
383 proxy.close(); | 385 proxy.close(); |
384 | 386 |
385 // Release service lock | 387 // Release service lock |
386 stopForeground(true); | 388 stopForeground(true); |
387 | 389 |
388 Log.i(TAG, "Service stopped"); | 390 Log.i(TAG, "Service stopped"); |
389 } | 391 } |
390 | 392 |
391 /** | 393 /** |
392 * Restores system proxy settings via native call on Android 3.1+ devices | 394 * Restores system proxy settings via native call on Android 3.1+ devices usin
g Java reflection. |
393 * using Java reflection. | |
394 */ | 395 */ |
395 private void clearConnectionProxy() | 396 private void clearConnectionProxy() |
396 { | 397 { |
397 String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost"); | 398 final String proxyHost = proxyConfiguration.getProperty("adblock.proxyHost")
; |
398 String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort"); | 399 final String proxyPort = proxyConfiguration.getProperty("adblock.proxyPort")
; |
399 String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl"); | 400 final String proxyExcl = proxyConfiguration.getProperty("adblock.proxyExcl")
; |
400 int port = 0; | 401 int port = 0; |
401 try | 402 try |
402 { | 403 { |
403 if (proxyHost != null) | 404 if (proxyHost != null) |
404 port = Integer.valueOf(proxyPort); | 405 port = Integer.valueOf(proxyPort); |
405 } | 406 } |
406 catch (NumberFormatException e) | 407 catch (final NumberFormatException e) |
407 { | 408 { |
408 Log.e(TAG, "Bad port setting", e); | 409 Log.e(TAG, "Bad port setting", e); |
409 } | 410 } |
410 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p
roxyExcl); | 411 ProxySettings.setConnectionProxy(getApplicationContext(), proxyHost, port, p
roxyExcl); |
411 } | 412 } |
412 | 413 |
413 /** | 414 /** |
414 * Sets user proxy settings in proxy service properties. | 415 * Sets user proxy settings in proxy service properties. |
415 */ | 416 */ |
416 private void configureUserProxy(Properties config, String proxyHost, String pr
oxyPort, String proxyExcl, String proxyUser, String proxyPass) | 417 private void configureUserProxy(final Properties config, final String proxyHos
t, final String proxyPort, final String proxyExcl, final String proxyUser, final
String proxyPass) |
417 { | 418 { |
418 // Clean previous settings | 419 // Clean previous settings |
419 config.remove("adblock.proxyHost"); | 420 config.remove("adblock.proxyHost"); |
420 config.remove("adblock.proxyPort"); | 421 config.remove("adblock.proxyPort"); |
421 config.remove("adblock.auth"); | 422 config.remove("adblock.auth"); |
422 config.remove("adblock.proxyExcl"); | 423 config.remove("adblock.proxyExcl"); |
423 if (!transparent) | 424 if (!transparent) |
424 { | 425 { |
425 config.remove("https.proxyHost"); | 426 config.remove("https.proxyHost"); |
426 config.remove("https.proxyPort"); | 427 config.remove("https.proxyPort"); |
(...skipping 11 matching lines...) Expand all Loading... |
438 // proxy points to ourselves | 439 // proxy points to ourselves |
439 // proxy port is null, 0 or not a number | 440 // proxy port is null, 0 or not a number |
440 // proxy is 127.0.0.1:8080 | 441 // proxy is 127.0.0.1:8080 |
441 if (proxyPort == null) | 442 if (proxyPort == null) |
442 return; | 443 return; |
443 int p = 0; | 444 int p = 0; |
444 try | 445 try |
445 { | 446 { |
446 p = Integer.valueOf(proxyPort); | 447 p = Integer.valueOf(proxyPort); |
447 } | 448 } |
448 catch (NumberFormatException e) | 449 catch (final NumberFormatException e) |
449 { | 450 { |
450 return; | 451 return; |
451 } | 452 } |
452 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080)) | 453 if (p == 0 || isLocalHost(proxyHost) && (p == port || p == 8080)) |
453 { | 454 { |
454 if (nativeProxyAutoConfigured) | 455 if (nativeProxyAutoConfigured) |
455 passProxySettings(null, null, null); | 456 passProxySettings(null, null, null); |
456 return; | 457 return; |
457 } | 458 } |
458 | 459 |
459 config.put("adblock.proxyHost", proxyHost); | 460 config.put("adblock.proxyHost", proxyHost); |
460 config.put("adblock.proxyPort", proxyPort); | 461 config.put("adblock.proxyPort", proxyPort); |
461 if (!transparent) | 462 if (!transparent) |
462 { | 463 { |
463 config.put("https.proxyHost", proxyHost); | 464 config.put("https.proxyHost", proxyHost); |
464 config.put("https.proxyPort", proxyPort); | 465 config.put("https.proxyPort", proxyPort); |
465 } | 466 } |
466 | 467 |
467 // TODO Not implemented in our proxy but needed to restore settings | 468 // TODO Not implemented in our proxy but needed to restore settings |
468 if (proxyExcl != null) | 469 if (proxyExcl != null) |
469 config.put("adblock.proxyExcl", proxyExcl); | 470 config.put("adblock.proxyExcl", proxyExcl); |
470 | 471 |
471 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e
quals(proxyPass)) | 472 if (proxyUser != null && !"".equals(proxyUser) && proxyPass != null && !"".e
quals(proxyPass)) |
472 { | 473 { |
473 // Base64 encode user:password | 474 // Base64 encode user:password |
474 String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + ":" + p
roxyPass)); | 475 final String proxyAuth = "Basic " + new String(Base64.encode(proxyUser + "
:" + proxyPass)); |
475 config.put("adblock.auth", proxyAuth); | 476 config.put("adblock.auth", proxyAuth); |
476 if (!transparent) | 477 if (!transparent) |
477 config.put("https.auth", proxyAuth); | 478 config.put("https.auth", proxyAuth); |
478 } | 479 } |
479 } | 480 } |
480 | 481 |
481 private void passProxySettings(String proxyHost, String proxyPort, String prox
yExcl) | 482 private void passProxySettings(final String proxyHost, final String proxyPort,
final String proxyExcl) |
482 { | 483 { |
483 try | 484 try |
484 { | 485 { |
485 CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExceptionHa
ndler(); | 486 final CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExcep
tionHandler(); |
486 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl); | 487 handler.saveProxySettings(proxyHost, proxyPort, proxyExcl); |
487 } | 488 } |
488 catch (ClassCastException e) | 489 catch (final ClassCastException e) |
489 { | 490 { |
490 // ignore - default handler in use | 491 // ignore - default handler in use |
491 } | 492 } |
492 } | 493 } |
493 | 494 |
494 @Override | 495 @Override |
495 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Str
ing key) | 496 public void onSharedPreferenceChanged(final SharedPreferences sharedPreference
s, final String key) |
496 { | 497 { |
497 if (!NATIVE_PROXY_SUPPORTED) | 498 if (!NATIVE_PROXY_SUPPORTED) |
498 { | 499 { |
499 String ketHost = getString(R.string.pref_proxyhost); | 500 final String ketHost = getString(R.string.pref_proxyhost); |
500 String keyPort = getString(R.string.pref_proxyport); | 501 final String keyPort = getString(R.string.pref_proxyport); |
501 String keyUser = getString(R.string.pref_proxyuser); | 502 final String keyUser = getString(R.string.pref_proxyuser); |
502 String keyPass = getString(R.string.pref_proxypass); | 503 final String keyPass = getString(R.string.pref_proxypass); |
503 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k
ey.equals(keyPass)) | 504 if (key.equals(ketHost) || key.equals(keyPort) || key.equals(keyUser) || k
ey.equals(keyPass)) |
504 { | 505 { |
505 String proxyHost = sharedPreferences.getString(ketHost, null); | 506 final String proxyHost = sharedPreferences.getString(ketHost, null); |
506 String proxyPort = sharedPreferences.getString(keyPort, null); | 507 final String proxyPort = sharedPreferences.getString(keyPort, null); |
507 String proxyUser = sharedPreferences.getString(keyUser, null); | 508 final String proxyUser = sharedPreferences.getString(keyUser, null); |
508 String proxyPass = sharedPreferences.getString(keyPass, null); | 509 final String proxyPass = sharedPreferences.getString(keyPass, null); |
509 if (proxy != null) | 510 if (proxy != null) |
510 { | 511 { |
511 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro
xyUser, proxyPass); | 512 configureUserProxy(proxyConfiguration, proxyHost, proxyPort, null, pro
xyUser, proxyPass); |
512 proxy.restart(proxyConfiguration.getProperty("handler")); | 513 proxy.restart(proxyConfiguration.getProperty("handler")); |
513 } | 514 } |
514 } | 515 } |
515 } | 516 } |
516 } | 517 } |
517 | 518 |
518 public boolean isTransparent() | 519 public boolean isTransparent() |
(...skipping 18 matching lines...) Expand all Loading... |
537 * Checks whether traffic check is pending | 538 * Checks whether traffic check is pending |
538 */ | 539 */ |
539 public boolean noTraffic() | 540 public boolean noTraffic() |
540 { | 541 { |
541 return notrafficHandler != null; | 542 return notrafficHandler != null; |
542 } | 543 } |
543 | 544 |
544 /** | 545 /** |
545 * Checks if specified host is local. | 546 * Checks if specified host is local. |
546 */ | 547 */ |
547 private static final boolean isLocalHost(String host) | 548 private static final boolean isLocalHost(final String host) |
548 { | 549 { |
549 if (host == null) | 550 if (host == null) |
550 return false; | 551 return false; |
551 | 552 |
552 try | 553 try |
553 { | 554 { |
554 if (host.equalsIgnoreCase("localhost")) | 555 if (host.equalsIgnoreCase("localhost")) |
555 return true; | 556 return true; |
556 | 557 |
557 String className = "android.net.NetworkUtils"; | 558 final String className = "android.net.NetworkUtils"; |
558 Class<?> c = Class.forName(className); | 559 final Class<?> c = Class.forName(className); |
559 /* | 560 /* |
560 * InetAddress address = NetworkUtils.numericToInetAddress(host); | 561 * InetAddress address = NetworkUtils.numericToInetAddress(host); |
561 */ | 562 */ |
562 Method method = c.getMethod("numericToInetAddress", String.class); | 563 final Method method = c.getMethod("numericToInetAddress", String.class); |
563 InetAddress address = (InetAddress) method.invoke(null, host); | 564 final InetAddress address = (InetAddress) method.invoke(null, host); |
564 | 565 |
565 if (address.isLoopbackAddress()) | 566 if (address.isLoopbackAddress()) |
566 return true; | 567 return true; |
567 } | 568 } |
568 catch (Exception e) | 569 catch (final Exception e) |
569 { | 570 { |
570 Log.w(TAG, null, e); | 571 Log.w(TAG, null, e); |
571 } | 572 } |
572 return false; | 573 return false; |
573 } | 574 } |
574 | 575 |
575 /** | 576 /** |
576 * Initializes iptables executable. | 577 * Initializes iptables executable. |
577 * | 578 * |
578 * @throws FileNotFoundException | 579 * @throws FileNotFoundException |
579 * If iptables initialization failed due to provided reasons. | 580 * If iptables initialization failed due to provided reasons. |
580 */ | 581 */ |
581 private void initIptables() throws IOException, RootToolsException, TimeoutExc
eption, FileNotFoundException | 582 private void initIptables() throws IOException, RootToolsException, TimeoutExc
eption, FileNotFoundException |
582 { | 583 { |
583 if (!RootTools.isAccessGiven()) | 584 if (!RootTools.isAccessGiven()) |
584 throw new FileNotFoundException("No root access"); | 585 throw new FileNotFoundException("No root access"); |
585 | 586 |
586 File ipt = getFileStreamPath("iptables"); | 587 final File ipt = getFileStreamPath("iptables"); |
587 | 588 |
588 if (!ipt.exists()) | 589 if (!ipt.exists()) |
589 { | 590 { |
590 Log.e(TAG, "No iptables excutable found"); | 591 Log.e(TAG, "No iptables excutable found"); |
591 throw new FileNotFoundException("No iptables executable"); | 592 throw new FileNotFoundException("No iptables executable"); |
592 } | 593 } |
593 | 594 |
594 String path = ipt.getAbsolutePath(); | 595 final String path = ipt.getAbsolutePath(); |
595 | 596 |
596 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT); | 597 RootTools.sendShell("chmod 700 " + path, DEFAULT_TIMEOUT); |
597 | 598 |
598 boolean compatible = false; | 599 boolean compatible = false; |
599 boolean version = false; | 600 boolean version = false; |
600 | 601 |
601 String command = path + " --version\n" + path + " -L -t nat -n\n"; | 602 final String command = path + " --version\n" + path + " -L -t nat -n\n"; |
602 | 603 |
603 List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT); | 604 final List<String> result = RootTools.sendShell(command, DEFAULT_TIMEOUT); |
604 for (String line : result) | 605 for (final String line : result) |
605 { | 606 { |
606 if (line.contains("OUTPUT")) | 607 if (line.contains("OUTPUT")) |
607 compatible = true; | 608 compatible = true; |
608 if (line.contains("v1.4.")) | 609 if (line.contains("v1.4.")) |
609 version = true; | 610 version = true; |
610 } | 611 } |
611 | 612 |
612 if (!compatible || !version) | 613 if (!compatible || !version) |
613 { | 614 { |
614 Log.e(TAG, "Incompatible iptables excutable"); | 615 Log.e(TAG, "Incompatible iptables excutable"); |
615 throw new FileNotFoundException("Incompatible iptables excutable"); | 616 throw new FileNotFoundException("Incompatible iptables excutable"); |
616 } | 617 } |
617 | 618 |
618 iptables = path; | 619 iptables = path; |
619 } | 620 } |
620 | 621 |
621 public List<String> getIptablesOutput() | 622 public List<String> getIptablesOutput() |
622 { | 623 { |
623 if (iptables == null) | 624 if (iptables == null) |
624 return null; | 625 return null; |
625 | 626 |
626 String command = iptables + " -L -t nat -n\n"; | 627 final String command = iptables + " -L -t nat -n\n"; |
627 try | 628 try |
628 { | 629 { |
629 return RootTools.sendShell(command, DEFAULT_TIMEOUT); | 630 return RootTools.sendShell(command, DEFAULT_TIMEOUT); |
630 } | 631 } |
631 catch (Exception e) | 632 catch (final Exception e) |
632 { | 633 { |
633 Log.e(TAG, "Failed to get iptables configuration", e); | 634 Log.e(TAG, "Failed to get iptables configuration", e); |
634 return null; | 635 return null; |
635 } | 636 } |
636 } | 637 } |
637 | 638 |
638 /** | 639 /** |
639 * Raises or removes no traffic notification based on current link proxy | 640 * Raises or removes no traffic notification based on current link proxy setti
ngs |
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 ab
out possible |
768 * about possible configuration problems. | 768 * 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 setti
ngs accordingly. |
838 * settings accordingly. | |
839 */ | 839 */ |
840 private BroadcastReceiver connectionReceiver = new BroadcastReceiver() | 840 private final BroadcastReceiver connectionReceiver = new BroadcastReceiver() |
841 { | 841 { |
842 @Override | 842 @Override |
843 public void onReceive(Context ctx, Intent intent) | 843 public void onReceive(final Context ctx, final Intent intent) |
844 { | 844 { |
845 String action = intent.getAction(); | 845 final String action = intent.getAction(); |
846 Log.i(TAG, "Action: " + action); | 846 Log.i(TAG, "Action: " + action); |
847 // Connectivity change | 847 // Connectivity change |
848 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) | 848 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) |
849 { | 849 { |
850 ConnectivityManager connectivityManager = (ConnectivityManager) getSyste
mService(Context.CONNECTIVITY_SERVICE); | 850 final ConnectivityManager connectivityManager = (ConnectivityManager) ge
tSystemService(Context.CONNECTIVITY_SERVICE); |
851 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc
ast() instead? | 851 // TODO Should we use ConnectivityManagerCompat.getNetworkInfoFromBroadc
ast() instead? |
852 NetworkInfo info = connectivityManager.getActiveNetworkInfo(); | 852 final NetworkInfo info = connectivityManager.getActiveNetworkInfo(); |
853 if (info == null) | 853 if (info == null) |
854 return; | 854 return; |
855 String typeName = info.getTypeName(); | 855 final String typeName = info.getTypeName(); |
856 String subtypeName = info.getSubtypeName(); | 856 final String subtypeName = info.getSubtypeName(); |
857 boolean available = info.isAvailable(); | 857 final boolean available = info.isAvailable(); |
858 | 858 |
859 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + "
, available: " + available); | 859 Log.i(TAG, "Network Type: " + typeName + ", subtype: " + subtypeName + "
, available: " + available); |
860 if (info.getType() == ConnectivityManager.TYPE_WIFI) | 860 if (info.getType() == ConnectivityManager.TYPE_WIFI) |
861 { | 861 { |
862 if (nativeProxyAutoConfigured) | 862 if (nativeProxyAutoConfigured) |
863 { | 863 { |
864 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST,
port, ""); | 864 ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST,
port, ""); |
865 } | 865 } |
866 else | 866 else |
867 { | 867 { |
868 updateNoTrafficCheck(connectivityManager); | 868 updateNoTrafficCheck(connectivityManager); |
869 } | 869 } |
870 } | 870 } |
871 } | 871 } |
872 // Proxy change | 872 // Proxy change |
873 else if (Proxy.PROXY_CHANGE_ACTION.equals(action)) | 873 else if (Proxy.PROXY_CHANGE_ACTION.equals(action)) |
874 { | 874 { |
875 Object pp = intent.getParcelableExtra("proxy"); | 875 final Object pp = intent.getParcelableExtra("proxy"); |
876 try | 876 try |
877 { | 877 { |
878 String[] userProxy = ProxySettings.getUserProxy(pp); | 878 final String[] userProxy = ProxySettings.getUserProxy(pp); |
879 if (nativeProxyAutoConfigured) | 879 if (nativeProxyAutoConfigured) |
880 { | 880 { |
881 if (userProxy != null && Integer.valueOf(userProxy[1]) != port) | 881 if (userProxy != null && Integer.valueOf(userProxy[1]) != port) |
882 { | 882 { |
883 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP
roxy[1] + "(" + userProxy[2] + ")"); | 883 Log.i(TAG, "User has set new proxy: " + userProxy[0] + ":" + userP
roxy[1] + "(" + userProxy[2] + ")"); |
884 if (proxy != null) | 884 if (proxy != null) |
885 { | 885 { |
886 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1
], userProxy[2], null, null); | 886 configureUserProxy(proxyConfiguration, userProxy[0], userProxy[1
], userProxy[2], null, null); |
887 proxy.restart(proxyConfiguration.getProperty("handler")); | 887 proxy.restart(proxyConfiguration.getProperty("handler")); |
888 } | 888 } |
889 } | 889 } |
890 } | 890 } |
891 else | 891 else |
892 { | 892 { |
893 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1
] + "(" + userProxy[2] + ")"); | 893 Log.i(TAG, "User has set proxy: " + userProxy[0] + ":" + userProxy[1
] + "(" + userProxy[2] + ")"); |
894 updateNoTrafficCheck(userProxy); | 894 updateNoTrafficCheck(userProxy); |
895 } | 895 } |
896 } | 896 } |
897 catch (Exception e) | 897 catch (final Exception e) |
898 { | 898 { |
899 // This should not happen | 899 // This should not happen |
900 Log.e(TAG, null, e); | 900 Log.e(TAG, null, e); |
901 } | 901 } |
902 } | 902 } |
903 } | 903 } |
904 }; | 904 }; |
905 | 905 |
906 final class ProxyServer extends Server | 906 final class ProxyServer extends Server |
907 { | 907 { |
908 @Override | 908 @Override |
909 public void close() | 909 public void close() |
910 { | 910 { |
911 try | 911 try |
912 { | 912 { |
913 listen.close(); | 913 listen.close(); |
914 this.interrupt(); | 914 this.interrupt(); |
915 this.join(); | 915 this.join(); |
916 } | 916 } |
917 catch (Exception e) | 917 catch (final Exception e) |
918 { | 918 { |
919 // ignore - it always happens | 919 // ignore - it always happens |
920 } | 920 } |
921 log(LOG_WARNING, null, "server stopped"); | 921 log(LOG_WARNING, null, "server stopped"); |
922 } | 922 } |
923 | 923 |
924 @Override | 924 @Override |
925 public void log(int level, Object obj, String message) | 925 public void log(final int level, final Object obj, final String message) |
926 { | 926 { |
927 if (level <= logLevel) | 927 if (level <= logLevel) |
928 { | 928 { |
929 Log.println(7 - level, obj != null ? obj.toString() : TAG, message); | 929 Log.println(7 - level, obj != null ? obj.toString() : TAG, message); |
930 } | 930 } |
931 } | 931 } |
932 } | 932 } |
933 } | 933 } |
OLD | NEW |