|
| 1 | +// Copyright 2020-2024 Tauri Programme within The Commons Conservancy |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +use std::{ |
| 6 | + borrow::Cow, |
| 7 | + ffi::{c_char, c_void, CStr}, |
| 8 | + panic::AssertUnwindSafe, |
| 9 | + ptr::NonNull, |
| 10 | + slice, |
| 11 | +}; |
| 12 | + |
| 13 | +use http::{ |
| 14 | + header::{CONTENT_LENGTH, CONTENT_TYPE}, |
| 15 | + Request, Response as HttpResponse, StatusCode, Version, |
| 16 | +}; |
| 17 | +use objc2::{ |
| 18 | + rc::Retained, |
| 19 | + runtime::{AnyClass, AnyObject, ClassBuilder, ProtocolObject}, |
| 20 | + ClassType, |
| 21 | +}; |
| 22 | +use objc2_foundation::{ |
| 23 | + NSData, NSHTTPURLResponse, NSMutableDictionary, NSObject, NSObjectProtocol, NSString, NSURL, |
| 24 | + NSUUID, |
| 25 | +}; |
| 26 | +use objc2_web_kit::{WKURLSchemeHandler, WKURLSchemeTask}; |
| 27 | + |
| 28 | +use crate::{wkwebview::WEBVIEW_IDS, RequestAsyncResponder, WryWebView}; |
| 29 | + |
| 30 | +pub fn create(name: &str) -> &AnyClass { |
| 31 | + unsafe { |
| 32 | + let scheme_name = format!("{}URLSchemeHandler", name); |
| 33 | + let cls = ClassBuilder::new(&scheme_name, NSObject::class()); |
| 34 | + match cls { |
| 35 | + Some(mut cls) => { |
| 36 | + cls.add_ivar::<*mut c_void>("function"); |
| 37 | + cls.add_ivar::<*mut c_char>("webview_id"); |
| 38 | + cls.add_method( |
| 39 | + objc2::sel!(webView:startURLSchemeTask:), |
| 40 | + start_task as extern "C" fn(_, _, _, _), |
| 41 | + ); |
| 42 | + cls.add_method( |
| 43 | + objc2::sel!(webView:stopURLSchemeTask:), |
| 44 | + stop_task as extern "C" fn(_, _, _, _), |
| 45 | + ); |
| 46 | + cls.register() |
| 47 | + } |
| 48 | + None => AnyClass::get(&scheme_name).expect("Failed to get the class definition"), |
| 49 | + } |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// Task handler for custom protocol |
| 54 | +extern "C" fn start_task( |
| 55 | + this: &AnyObject, |
| 56 | + _sel: objc2::runtime::Sel, |
| 57 | + webview: &'static mut WryWebView, |
| 58 | + task: &'static ProtocolObject<dyn WKURLSchemeTask>, |
| 59 | +) { |
| 60 | + unsafe { |
| 61 | + #[cfg(feature = "tracing")] |
| 62 | + let span = tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty) |
| 63 | + .entered(); |
| 64 | + |
| 65 | + let task_key = task.hash(); // hash by task object address |
| 66 | + let task_uuid = webview.add_custom_task_key(task_key); |
| 67 | + |
| 68 | + let ivar = this.class().instance_variable("webview_id").unwrap(); |
| 69 | + let webview_id_ptr: *mut c_char = *ivar.load(this); |
| 70 | + let webview_id = CStr::from_ptr(webview_id_ptr) |
| 71 | + .to_str() |
| 72 | + .ok() |
| 73 | + .unwrap_or_default(); |
| 74 | + |
| 75 | + let ivar = this.class().instance_variable("function").unwrap(); |
| 76 | + let function: &*mut c_void = ivar.load(this); |
| 77 | + if !function.is_null() { |
| 78 | + let function = &mut *(*function |
| 79 | + as *mut Box<dyn Fn(crate::WebViewId, Request<Vec<u8>>, RequestAsyncResponder)>); |
| 80 | + |
| 81 | + // Get url request |
| 82 | + let request = task.request(); |
| 83 | + let url = request.URL().unwrap(); |
| 84 | + |
| 85 | + let uri = url.absoluteString().unwrap().to_string(); |
| 86 | + |
| 87 | + #[cfg(feature = "tracing")] |
| 88 | + span.record("uri", uri.clone()); |
| 89 | + |
| 90 | + // Get request method (GET, POST, PUT etc...) |
| 91 | + let method = request.HTTPMethod().unwrap().to_string(); |
| 92 | + |
| 93 | + // Prepare our HttpRequest |
| 94 | + let mut http_request = Request::builder().uri(uri).method(method.as_str()); |
| 95 | + |
| 96 | + // Get body |
| 97 | + let mut sent_form_body = Vec::new(); |
| 98 | + let body = request.HTTPBody(); |
| 99 | + let body_stream = request.HTTPBodyStream(); |
| 100 | + if let Some(body) = body { |
| 101 | + let length = body.length(); |
| 102 | + let data_bytes = body.bytes(); |
| 103 | + sent_form_body = slice::from_raw_parts(data_bytes.as_ptr(), length).to_vec(); |
| 104 | + } else if let Some(body_stream) = body_stream { |
| 105 | + body_stream.open(); |
| 106 | + |
| 107 | + while body_stream.hasBytesAvailable() { |
| 108 | + sent_form_body.reserve(128); |
| 109 | + let p = sent_form_body.as_mut_ptr().add(sent_form_body.len()); |
| 110 | + let read_length = sent_form_body.capacity() - sent_form_body.len(); |
| 111 | + let count = body_stream.read_maxLength(NonNull::new(p).unwrap(), read_length); |
| 112 | + sent_form_body.set_len(sent_form_body.len() + count as usize); |
| 113 | + } |
| 114 | + |
| 115 | + body_stream.close(); |
| 116 | + } |
| 117 | + |
| 118 | + // Extract all headers fields |
| 119 | + let all_headers = request.allHTTPHeaderFields(); |
| 120 | + |
| 121 | + // get all our headers values and inject them in our request |
| 122 | + if let Some(all_headers) = all_headers { |
| 123 | + for current_header in all_headers.allKeys().to_vec() { |
| 124 | + let header_value = all_headers.valueForKey(current_header).unwrap(); |
| 125 | + |
| 126 | + // inject the header into the request |
| 127 | + http_request = http_request.header(current_header.to_string(), header_value.to_string()); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + let respond_with_404 = || { |
| 132 | + let urlresponse = NSHTTPURLResponse::alloc(); |
| 133 | + let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields( |
| 134 | + urlresponse, |
| 135 | + &url, |
| 136 | + StatusCode::NOT_FOUND.as_u16().try_into().unwrap(), |
| 137 | + Some(&NSString::from_str( |
| 138 | + format!("{:#?}", Version::HTTP_11).as_str(), |
| 139 | + )), |
| 140 | + None, |
| 141 | + ) |
| 142 | + .unwrap(); |
| 143 | + task.didReceiveResponse(&response); |
| 144 | + // Finish |
| 145 | + task.didFinish(); |
| 146 | + }; |
| 147 | + |
| 148 | + // send response |
| 149 | + match http_request.body(sent_form_body) { |
| 150 | + Ok(final_request) => { |
| 151 | + let responder: Box<dyn FnOnce(HttpResponse<Cow<'static, [u8]>>)> = |
| 152 | + Box::new(move |sent_response| { |
| 153 | + fn check_webview_id_valid(webview_id: &str) -> crate::Result<()> { |
| 154 | + if !WEBVIEW_IDS.lock().unwrap().contains(webview_id) { |
| 155 | + return Err(crate::Error::CustomProtocolTaskInvalid); |
| 156 | + } |
| 157 | + Ok(()) |
| 158 | + } |
| 159 | + /// Task may not live longer than async custom protocol handler. |
| 160 | + /// |
| 161 | + /// There are roughly 2 ways to cause segfault: |
| 162 | + /// 1. Task has stopped. pointer of the task not valid anymore. |
| 163 | + /// 2. Task had stopped, but the pointer of the task has allocated to a new task. |
| 164 | + /// Outdated custom handler may call to the new task instance and cause segfault. |
| 165 | + fn check_task_is_valid( |
| 166 | + webview: &WryWebView, |
| 167 | + task_key: usize, |
| 168 | + current_uuid: Retained<NSUUID>, |
| 169 | + ) -> crate::Result<()> { |
| 170 | + let latest_task_uuid = webview.get_custom_task_uuid(task_key); |
| 171 | + if let Some(latest_uuid) = latest_task_uuid { |
| 172 | + if latest_uuid != current_uuid { |
| 173 | + return Err(crate::Error::CustomProtocolTaskInvalid); |
| 174 | + } |
| 175 | + } else { |
| 176 | + return Err(crate::Error::CustomProtocolTaskInvalid); |
| 177 | + } |
| 178 | + Ok(()) |
| 179 | + } |
| 180 | + |
| 181 | + unsafe fn response( |
| 182 | + // FIXME: though we give it a static lifetime, it's not guaranteed to be valid. |
| 183 | + task: &'static ProtocolObject<dyn WKURLSchemeTask>, |
| 184 | + // FIXME: though we give it a static lifetime, it's not guaranteed to be valid. |
| 185 | + webview: &'static mut WryWebView, |
| 186 | + task_key: usize, |
| 187 | + task_uuid: Retained<NSUUID>, |
| 188 | + webview_id: &str, |
| 189 | + url: Retained<NSURL>, |
| 190 | + sent_response: HttpResponse<Cow<'_, [u8]>>, |
| 191 | + ) -> crate::Result<()> { |
| 192 | + check_task_is_valid(&*webview, task_key, task_uuid.clone())?; |
| 193 | + |
| 194 | + let content = sent_response.body(); |
| 195 | + // default: application/octet-stream, but should be provided by the client |
| 196 | + let wanted_mime = sent_response.headers().get(CONTENT_TYPE); |
| 197 | + // default to 200 |
| 198 | + let wanted_status_code = sent_response.status().as_u16() as i32; |
| 199 | + // default to HTTP/1.1 |
| 200 | + let wanted_version = format!("{:#?}", sent_response.version()); |
| 201 | + |
| 202 | + let mut headers = NSMutableDictionary::new(); |
| 203 | + |
| 204 | + if let Some(mime) = wanted_mime { |
| 205 | + headers.insert_id( |
| 206 | + NSString::from_str(mime.to_str().unwrap()).as_ref(), |
| 207 | + NSString::from_str(CONTENT_TYPE.as_str()), |
| 208 | + ); |
| 209 | + } |
| 210 | + headers.insert_id( |
| 211 | + NSString::from_str(&content.len().to_string()).as_ref(), |
| 212 | + NSString::from_str(CONTENT_LENGTH.as_str()), |
| 213 | + ); |
| 214 | + |
| 215 | + // add headers |
| 216 | + for (name, value) in sent_response.headers().iter() { |
| 217 | + if let Ok(value) = value.to_str() { |
| 218 | + headers.insert_id( |
| 219 | + NSString::from_str(name.as_str()).as_ref(), |
| 220 | + NSString::from_str(value), |
| 221 | + ); |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + let urlresponse = NSHTTPURLResponse::alloc(); |
| 226 | + let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields( |
| 227 | + urlresponse, |
| 228 | + &url, |
| 229 | + wanted_status_code.try_into().unwrap(), |
| 230 | + Some(&NSString::from_str(&wanted_version)), |
| 231 | + Some(&headers), |
| 232 | + ) |
| 233 | + .unwrap(); |
| 234 | + |
| 235 | + check_webview_id_valid(webview_id)?; |
| 236 | + check_task_is_valid(&*webview, task_key, task_uuid.clone())?; |
| 237 | + |
| 238 | + objc2::exception::catch(AssertUnwindSafe(|| { |
| 239 | + task.didReceiveResponse(&response); |
| 240 | + })) |
| 241 | + .unwrap(); |
| 242 | + |
| 243 | + // Send data |
| 244 | + let bytes = content.as_ptr() as *mut c_void; |
| 245 | + let data = NSData::alloc(); |
| 246 | + // MIGRATE NOTE: we copied the content to the NSData because content will be freed |
| 247 | + // when out of scope but NSData will also free the content when it's done and cause doube free. |
| 248 | + let data = NSData::initWithBytes_length(data, bytes, content.len()); |
| 249 | + check_webview_id_valid(webview_id)?; |
| 250 | + check_task_is_valid(&*webview, task_key, task_uuid.clone())?; |
| 251 | + objc2::exception::catch(AssertUnwindSafe(|| { |
| 252 | + task.didReceiveData(&data); |
| 253 | + })) |
| 254 | + .unwrap(); |
| 255 | + |
| 256 | + // Finish |
| 257 | + check_webview_id_valid(webview_id)?; |
| 258 | + check_task_is_valid(&*webview, task_key, task_uuid.clone())?; |
| 259 | + objc2::exception::catch(AssertUnwindSafe(|| { |
| 260 | + task.didFinish(); |
| 261 | + })) |
| 262 | + .unwrap(); |
| 263 | + |
| 264 | + webview.remove_custom_task_key(task_key); |
| 265 | + Ok(()) |
| 266 | + } |
| 267 | + |
| 268 | + let _ = response( |
| 269 | + task, |
| 270 | + webview, |
| 271 | + task_key, |
| 272 | + task_uuid, |
| 273 | + webview_id, |
| 274 | + url.clone(), |
| 275 | + sent_response, |
| 276 | + ); |
| 277 | + }); |
| 278 | + |
| 279 | + #[cfg(feature = "tracing")] |
| 280 | + let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered(); |
| 281 | + function( |
| 282 | + webview_id, |
| 283 | + final_request, |
| 284 | + RequestAsyncResponder { responder }, |
| 285 | + ); |
| 286 | + } |
| 287 | + Err(_) => respond_with_404(), |
| 288 | + }; |
| 289 | + } else { |
| 290 | + #[cfg(feature = "tracing")] |
| 291 | + tracing::warn!( |
| 292 | + "Either WebView or WebContext instance is dropped! This handler shouldn't be called." |
| 293 | + ); |
| 294 | + } |
| 295 | + } |
| 296 | +} |
| 297 | +extern "C" fn stop_task( |
| 298 | + _this: &ProtocolObject<dyn WKURLSchemeHandler>, |
| 299 | + _sel: objc2::runtime::Sel, |
| 300 | + webview: &mut WryWebView, |
| 301 | + task: &ProtocolObject<dyn WKURLSchemeTask>, |
| 302 | +) { |
| 303 | + webview.remove_custom_task_key(task.hash()); |
| 304 | +} |
0 commit comments