Debian Codegraph @

interop/android/lib/src/main/java/com/pywebview/PyWebViewClient.java

raw
1 package com.pywebview;
2
3 import android.graphics.Bitmap;
4 import android.net.http.SslError;
5 import android.os.Build;
6 import android.os.Handler;
7 import android.os.Looper;
8 import android.webkit.SslErrorHandler;
9 import android.webkit.WebResourceRequest;
10 import android.webkit.WebResourceResponse;
11 import android.webkit.WebView;
12 import android.webkit.WebViewClient;
13 import android.util.Log;
14
15 import java.io.InputStream;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.ArrayList;
19 import java.util.List;
20 import org.json.JSONObject;
21
22 public class PyWebViewClient extends WebViewClient {
23 private volatile EventCallbackWrapper callback;
24 private boolean ignoreSslErrors = false;
25 private volatile WebViewRequestInterceptor requestInterceptor;
26 private Handler mainHandler;
27 private volatile boolean isDestroyed = false;
28
29 public PyWebViewClient() {
30 super();
31 // Initialize handler for main thread to avoid PyJNIus threading issues
32 mainHandler = new Handler(Looper.getMainLooper());
33 }
34
35 public void setCallback(EventCallbackWrapper callback, boolean ignoreSslErrors) {
36 this.callback = callback;
37 this.ignoreSslErrors = ignoreSslErrors;
38 }
39
40 public void setRequestInterceptor(WebViewRequestInterceptor interceptor) {
41 this.requestInterceptor = interceptor;
42 }
43
44 public void destroy() {
45 isDestroyed = true;
46 callback = null;
47 requestInterceptor = null;
48 }
49
50 /**
51 * Safely execute callback on main thread to avoid PyJNIus threading crashes.
52 * PyJNIus has issues with concurrent access from multiple threads.
53 */
54 private void safeCallback(String event, String data) {
55 if (isDestroyed) {
56 Log.d("python", "Callback skipped - client destroyed: " + event);
57 return;
58 }
59
60 EventCallbackWrapper currentCallback = callback;
61 if (currentCallback == null) {
62 Log.d("python", "Callback skipped - no callback set: " + event);
63 return;
64 }
65
66 if (Looper.myLooper() == Looper.getMainLooper()) {
67 // Already on main thread, execute directly
68 try {
69 currentCallback.callback(event, data);
70 } catch (Exception e) {
71 Log.e("python", "Error in callback: " + event, e);
72 // If we get a JNI error, clear the callback to prevent further crashes
73 if (isJniError(e)) {
74 Log.w("python", "JNI error detected, clearing callback to prevent crashes");
75 callback = null;
76 }
77 }
78 } else {
79 // Post to main thread
80 mainHandler.post(() -> {
81 if (isDestroyed) {
82 return;
83 }
84 EventCallbackWrapper cb = callback;
85 if (cb == null) {
86 return;
87 }
88 try {
89 cb.callback(event, data);
90 } catch (Exception e) {
91 Log.e("python", "Error in callback: " + event, e);
92 // If we get a JNI error, clear the callback to prevent further crashes
93 if (isJniError(e)) {
94 Log.w("python", "JNI error detected, clearing callback to prevent crashes");
95 callback = null;
96 }
97 }
98 });
99 }
100 }
101
102 /**
103 * Safely execute request interceptor calls on main thread
104 */
105 private String safeOnRequest(String url, String method, String headersJson) {
106 if (isDestroyed) {
107 return null;
108 }
109
110 WebViewRequestInterceptor currentInterceptor = requestInterceptor;
111 if (currentInterceptor == null) return null;
112
113 if (Looper.myLooper() == Looper.getMainLooper()) {
114 try {
115 return currentInterceptor.onRequest(url, method, headersJson);
116 } catch (Exception e) {
117 Log.e("python", "Error in onRequest", e);
118 // If we get a JNI error, clear the interceptor to prevent further crashes
119 if (isJniError(e)) {
120 Log.w("python", "JNI error detected, clearing request interceptor to prevent crashes");
121 requestInterceptor = null;
122 }
123 return null;
124 }
125 } else {
126 // For request interceptor, we need synchronous execution, so we use a blocking approach
127 final String[] result = new String[1];
128 final Object lock = new Object();
129
130 mainHandler.post(() -> {
131 synchronized (lock) {
132 if (isDestroyed) {
133 result[0] = null;
134 lock.notify();
135 return;
136 }
137 WebViewRequestInterceptor interceptor = requestInterceptor;
138 if (interceptor == null) {
139 result[0] = null;
140 lock.notify();
141 return;
142 }
143 try {
144 result[0] = interceptor.onRequest(url, method, headersJson);
145 } catch (Exception e) {
146 Log.e("python", "Error in onRequest", e);
147 // If we get a JNI error, clear the interceptor to prevent further crashes
148 if (isJniError(e)) {
149 Log.w("python", "JNI error detected, clearing request interceptor to prevent crashes");
150 requestInterceptor = null;
151 }
152 result[0] = null;
153 }
154 lock.notify();
155 }
156 });
157
158 synchronized (lock) {
159 try {
160 lock.wait(5000); // 5 second timeout
161 } catch (InterruptedException e) {
162 Log.e("python", "Interrupted while waiting for onRequest", e);
163 Thread.currentThread().interrupt();
164 }
165 }
166
167 return result[0];
168 }
169 }
170
171 /**
172 * Safely execute response interceptor calls on main thread
173 */
174 private void safeOnResponse(String url, int statusCode, String headersJson) {
175 if (isDestroyed) {
176 return;
177 }
178
179 WebViewRequestInterceptor currentInterceptor = requestInterceptor;
180 if (currentInterceptor == null) return;
181
182 if (Looper.myLooper() == Looper.getMainLooper()) {
183 try {
184 currentInterceptor.onResponse(url, statusCode, headersJson);
185 } catch (Exception e) {
186 Log.e("python", "Error in onResponse", e);
187 // If we get a JNI error, clear the interceptor to prevent further crashes
188 if (isJniError(e)) {
189 Log.w("python", "JNI error detected, clearing request interceptor to prevent crashes");
190 requestInterceptor = null;
191 }
192 }
193 } else {
194 mainHandler.post(() -> {
195 if (isDestroyed) {
196 return;
197 }
198 WebViewRequestInterceptor interceptor = requestInterceptor;
199 if (interceptor == null) {
200 return;
201 }
202 try {
203 interceptor.onResponse(url, statusCode, headersJson);
204 } catch (Exception e) {
205 Log.e("python", "Error in onResponse", e);
206 // If we get a JNI error, clear the interceptor to prevent further crashes
207 if (isJniError(e)) {
208 Log.w("python", "JNI error detected, clearing request interceptor to prevent crashes");
209 requestInterceptor = null;
210 }
211 }
212 });
213 }
214 }
215
216 /**
217 * Check if an exception is related to JNI errors
218 */
219 private boolean isJniError(Exception e) {
220 String message = e.getMessage();
221 return message != null && (
222 message.contains("JNI") ||
223 message.contains("global reference") ||
224 message.contains("stale reference") ||
225 message.contains("invalid") ||
226 e instanceof IllegalStateException ||
227 e instanceof IllegalArgumentException
228 );
229 }
230
231 @Override
232 public void onPageStarted(WebView view, String url, Bitmap favicon) {
233 super.onPageStarted(view, url, favicon);
234 safeCallback("onPageStarted", url);
235 }
236
237 @Override
238 public void onPageFinished(WebView view, String url) {
239 super.onPageFinished(view, url);
240 safeCallback("onPageFinished", url);
241 }
242
243 @Override
244 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
245 String errorMsg = "SSL Error for URL: " + error.getUrl() + " - ";
246 switch (error.getPrimaryError()) {
247 case SslError.SSL_UNTRUSTED:
248 errorMsg += "Certificate authority is not trusted";
249 break;
250 case SslError.SSL_EXPIRED:
251 errorMsg += "Certificate has expired";
252 break;
253 case SslError.SSL_IDMISMATCH:
254 errorMsg += "Certificate hostname mismatch";
255 break;
256 case SslError.SSL_NOTYETVALID:
257 errorMsg += "Certificate is not yet valid";
258 break;
259 case SslError.SSL_DATE_INVALID:
260 errorMsg += "Certificate date is invalid";
261 break;
262 case SslError.SSL_INVALID:
263 errorMsg += "Generic certificate error";
264 break;
265 default:
266 errorMsg += "Unknown SSL error: " + error.getPrimaryError();
267 }
268
269 if (this.ignoreSslErrors) {
270 Log.d("python", errorMsg + " (proceeding due to ignoreSslErrors=true)");
271 handler.proceed();
272 } else {
273 Log.e("python", errorMsg + " (cancelling - ignoreSslErrors=false)");
274 handler.cancel();
275 }
276 }
277
278 @Override
279 public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
280 String url = request.getUrl().toString();
281 String method = request.getMethod();
282
283 // Collect original request headers
284 Map<String, String> headers = new HashMap<>();
285 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && request.getRequestHeaders() != null) {
286 headers.putAll(request.getRequestHeaders());
287 }
288
289 try {
290 String headersJson = new JSONObject(headers).toString();
291 String finalHeaders = headersJson;
292
293 // If we have an interceptor, let it modify the headers
294 if (requestInterceptor != null) {
295 String newHeaders = safeOnRequest(url, method, headersJson);
296 if (newHeaders != null) {
297 finalHeaders = newHeaders;
298 }
299 }
300
301 // Check if this is a cleartext HTTP request to localhost that might be blocked
302 if (url.startsWith("http://") && (url.contains("127.0.0.1") || url.contains("localhost"))) {
303 Log.w("python", "Skipping custom request for localhost HTTP URL to avoid Network Security Policy issues: " + url);
304 // Let the WebView handle this request normally
305 return super.shouldInterceptRequest(view, request);
306 }
307
308 // Use custom request to ensure we get response headers
309 return performCustomRequest(url, method, finalHeaders);
310
311 } catch (Exception e) {
312 Log.e("python", "Error processing request", e);
313
314 if (requestInterceptor != null) {
315 notifyInterceptorOfError(url, e);
316 }
317 return super.shouldInterceptRequest(view, request);
318 }
319 }
320
321
322 private void processCookies(String url, Map<String, String> responseHeaders) {
323 // Process cookies from response headers without making a new connection
324 try {
325 // Look for Set-Cookie headers (there can be multiple)
326 List<String> setCookieHeaders = new ArrayList<>();
327
328 for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
329 if ("Set-Cookie".equalsIgnoreCase(entry.getKey())) {
330 setCookieHeaders.add(entry.getValue());
331 }
332 }
333
334 // Convert setCookieHeaders to JSON and pass to callback
335 if (!setCookieHeaders.isEmpty()) {
336 try {
337 JSONObject cookieData = new JSONObject();
338 cookieData.put("url", url);
339 org.json.JSONArray cookieArray = new org.json.JSONArray();
340 for (String cookieHeader : setCookieHeaders) {
341 // Strip "Set-Cookie:" prefix if present
342 String cleanCookie = cookieHeader.replaceFirst("^Set-Cookie:\\s*", "");
343 cookieArray.put(cleanCookie);
344 }
345 cookieData.put("cookies", cookieArray);
346 safeCallback("onCookiesReceived", cookieData.toString());
347 } catch (Exception jsonEx) {
348 Log.e("python", "Error creating JSON for cookies", jsonEx);
349 }
350 }
351
352 } catch (Exception e) {
353 Log.e("python", "Error processing cookies", e);
354 }
355 }
356
357 private WebResourceResponse performCustomRequest(String url, String method, String headersJson) throws Exception {
358 // Skip custom requests for certain protocols that can't be handled externally
359 if (url.startsWith("data:") || url.startsWith("file:") || url.startsWith("android_asset:") || url.startsWith("android_res:")) {
360 Log.d("python", "Skipping custom request for protocol: " + url);
361 throw new Exception("Protocol not supported for custom requests");
362 }
363
364 JSONObject headersObj = new JSONObject(headersJson);
365
366 // Create and configure connection
367 java.net.URL urlObj = new java.net.URL(url);
368 java.net.HttpURLConnection connection = (java.net.HttpURLConnection) urlObj.openConnection();
369
370 // Handle SSL for HTTPS connections with self-signed certificates
371 if (connection instanceof javax.net.ssl.HttpsURLConnection && ignoreSslErrors) {
372 javax.net.ssl.HttpsURLConnection httpsConnection = (javax.net.ssl.HttpsURLConnection) connection;
373
374 try {
375 // Create a trust manager that accepts all certificates
376 javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
377 new javax.net.ssl.X509TrustManager() {
378 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
379 return new java.security.cert.X509Certificate[0];
380 }
381 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
382 // Accept all client certificates
383 }
384 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
385 // Accept all server certificates
386 }
387 }
388 };
389
390 // Initialize SSL context with trust-all manager
391 javax.net.ssl.SSLContext sslContext = null;
392 try {
393 sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
394 } catch (Exception e) {
395 try {
396 sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
397 } catch (Exception e2) {
398 sslContext = javax.net.ssl.SSLContext.getInstance("TLSv1");
399 }
400 }
401 sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
402
403 // Apply SSL configuration to HTTPS connection
404 httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
405
406 // Disable hostname verification for self-signed certificates
407 httpsConnection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
408 public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
409 return true; // Accept all hostnames
410 }
411 });
412
413 } catch (Exception sslEx) {
414 Log.e("python", "Failed to configure SSL context for self-signed cert: " + sslEx.getMessage(), sslEx);
415 // Continue anyway - the connection might still work with default SSL settings
416 }
417 }
418
419 connection.setRequestMethod(method);
420
421 // Set headers
422 java.util.Iterator<String> keys = headersObj.keys();
423 while (keys.hasNext()) {
424 String key = keys.next();
425 connection.setRequestProperty(key, headersObj.getString(key));
426 }
427
428 // Connect with SSL error handling
429 try {
430 connection.connect();
431 } catch (javax.net.ssl.SSLHandshakeException sslEx) {
432 Log.e("python", "SSL handshake failed for URL: " + url + " - " + sslEx.getMessage());
433 if (ignoreSslErrors) {
434 Log.w("python", "SSL error occurred despite ignoreSslErrors=true. Check SSL configuration.");
435 }
436 throw sslEx;
437 }
438
439 // Process response
440 String contentType = connection.getContentType();
441 String mimeType = contentType;
442 String encoding = connection.getContentEncoding();
443
444 // Parse content type
445 if (contentType != null && contentType.contains(";")) {
446 mimeType = contentType.split(";")[0].trim();
447 if (encoding == null && contentType.toLowerCase().contains("charset=")) {
448 for (String part : contentType.split(";")) {
449 if (part.toLowerCase().contains("charset=")) {
450 encoding = part.split("=")[1].trim();
451 break;
452 }
453 }
454 }
455 }
456
457 // Get response data with error handling
458 InputStream inputStream;
459 int statusCode;
460 String reasonPhrase;
461
462 try {
463 statusCode = connection.getResponseCode();
464 reasonPhrase = connection.getResponseMessage();
465
466 if (statusCode >= 200 && statusCode < 300) {
467 inputStream = connection.getInputStream();
468 } else {
469 // For error responses, try to get error stream
470 inputStream = connection.getErrorStream();
471 if (inputStream == null) {
472 inputStream = connection.getInputStream();
473 }
474 }
475 } catch (javax.net.ssl.SSLHandshakeException sslEx) {
476 Log.e("python", "SSL handshake failed while reading response from: " + url);
477 if (ignoreSslErrors) {
478 Log.w("python", "SSL error occurred despite ignoreSslErrors=true. Check SSL configuration.");
479 }
480 throw sslEx;
481 }
482
483 // Collect response headers
484 Map<String, String> responseHeaders = new HashMap<>();
485 for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
486 if (entry.getKey() != null && !entry.getValue().isEmpty()) {
487 responseHeaders.put(entry.getKey(), entry.getValue().get(0));
488 }
489 }
490
491 // Notify interceptor
492 safeOnResponse(url, statusCode, new JSONObject(responseHeaders).toString());
493
494 // Process cookies from response headers
495 processCookies(url, responseHeaders);
496
497 // Return appropriate response based on API level
498 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
499 return new WebResourceResponse(mimeType, encoding, statusCode, reasonPhrase, responseHeaders, inputStream);
500 } else {
501 return new WebResourceResponse(mimeType, encoding, inputStream);
502 }
503 }
504
505 private void notifyInterceptorOfError(String url, Exception e) {
506 if (isDestroyed) {
507 return;
508 }
509
510 try {
511 JSONObject errorInfo = new JSONObject();
512 errorInfo.put("error", e.getMessage());
513 safeOnResponse(url, 0, errorInfo.toString());
514 } catch (Exception jsonEx) {
515 Log.e("python", "Error creating JSON for error response", jsonEx);
516 }
517 }
518
519 @Override
520 public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
521 super.onReceivedHttpError(view, request, errorResponse);
522
523 if (isDestroyed) {
524 return;
525 }
526
527 WebViewRequestInterceptor currentInterceptor = requestInterceptor;
528 if (currentInterceptor != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
529 String url = request.getUrl().toString();
530 int statusCode = errorResponse.getStatusCode();
531
532 Map<String, String> headers = new HashMap<>();
533 if (errorResponse.getResponseHeaders() != null) {
534 headers.putAll(errorResponse.getResponseHeaders());
535 }
536
537 JSONObject headersJson = new JSONObject(headers);
538 String headersJsonString = headersJson.toString();
539 safeOnResponse(url, statusCode, headersJsonString);
540 }
541
542 try {
543 JSONObject data = new JSONObject();
544 data.put("url", request.getUrl().toString());
545 data.put("statusCode", errorResponse.getStatusCode());
546 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && errorResponse.getResponseHeaders() != null) {
547 JSONObject headers = new JSONObject();
548 for (Map.Entry<String, String> entry : errorResponse.getResponseHeaders().entrySet()) {
549 headers.put(entry.getKey(), entry.getValue());
550 }
551 data.put("headers", headers);
552 }
553
554 safeCallback("onReceivedHttpError", data.toString());
555 } catch (Exception e) {
556 Log.e("python", "Error creating JSON", e);
557 }
558 }
559 }