ltk_webkit/wpe/
downloads.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// SPDX-License-Identifier: LGPL-2.1-only
// Copyright (C) 2026 Liberux Labs, S. L. <info@liberux.net>

//! Process-wide download tracking. Every [`crate::WebView`] shares one
//! `WebKitNetworkSession`, so downloads are reported through one
//! queue the host drains with [`poll_downloads`] from its main thread.

use std::ffi::{ c_char, CStr, CString, OsStr };
use std::os::unix::ffi::OsStrExt;
use std::path::{ Path, PathBuf };
use std::sync::{ Mutex, Once };

use glib_sys::*;
use gobject_sys::*;
use wpe_webkit_sys::*;

use crate::types::{ DownloadEvent, DownloadId };

struct Live
{
	id:       DownloadId,
	/// `*mut WebKitDownload`, ref'd; stored as an address so the registry is `Send`.
	download: usize,
	reported: f64,
	failed:   bool,
}

struct Registry
{
	next_id: DownloadId,
	dir:     Option<PathBuf>,
	live:    Vec<Live>,
	events:  Vec<DownloadEvent>,
}

static REGISTRY: Mutex<Registry> = Mutex::new( Registry { next_id: 1, dir: None, live: Vec::new(), events: Vec::new() } );

const PROGRESS_STEP: f64 = 0.01;

/// Directory new downloads are saved to. Defaults to `$XDG_DOWNLOAD_DIR`,
/// then the download directory of `user-dirs.dirs`, then `~/Downloads`.
pub fn set_download_dir( dir: impl Into<PathBuf> )
{
	if let Ok( mut r ) = REGISTRY.lock() { r.dir = Some( dir.into() ); }
}

/// Drain the download events produced since the previous call, including a
/// `Progress` event for every live download that advanced.
pub fn poll_downloads() -> Vec<DownloadEvent>
{
	let Ok( mut r ) = REGISTRY.lock() else { return Vec::new() };
	let mut events  = std::mem::take( &mut r.events );
	for live in r.live.iter_mut()
	{
		// SAFETY: the registry holds a ref on every live download.
		let fraction = unsafe { webkit_download_get_estimated_progress( live.download as *mut WebKitDownload ) };
		if fraction - live.reported >= PROGRESS_STEP
		{
			live.reported = fraction;
			events.push( DownloadEvent::Progress { id: live.id, fraction } );
		}
	}
	events
}

pub fn cancel_download( id: DownloadId )
{
	let download = REGISTRY.lock().ok()
		.and_then( |r| r.live.iter().find( |l| l.id == id ).map( |l| l.download ) );
	// The lock is released first: cancelling emits `failed` synchronously.
	if let Some( download ) = download
	{
		unsafe { webkit_download_cancel( download as *mut WebKitDownload ); }
	}
}

/// Start tracking the downloads of `webview`'s network session. Idempotent.
pub( crate ) unsafe fn track( webview: *mut WebKitWebView )
{
	static ONCE: Once = Once::new();
	ONCE.call_once( ||
	{
		// SAFETY: the session outlives the process' views; handlers are
		// cast from their documented signal signatures.
		unsafe
		{
			let session = webkit_web_view_get_network_session( webview );
			if session.is_null() { return; }
			connect( session as *mut GObject, b"download-started\0", on_started as *const () );
		}
	} );
}

unsafe fn connect( instance: *mut GObject, signal: &[ u8 ], handler: *const () )
{
	// SAFETY: `handler` is an `extern "C"` function matching `signal`.
	unsafe
	{
		let callback = std::mem::transmute::<*const (), unsafe extern "C" fn()>( handler );
		g_signal_connect_data( instance, signal.as_ptr() as *const c_char, Some( callback ), std::ptr::null_mut(), None, 0 );
	}
}

unsafe extern "C" fn on_started( _session: *mut WebKitNetworkSession, download: *mut WebKitDownload, _data: gpointer )
{
	if download.is_null() { return; }
	// SAFETY: `download` is live for the duration of the signal; the ref
	// taken here is released in `on_finished`.
	unsafe
	{
		g_object_ref( download as *mut GObject );
		connect( download as *mut GObject, b"decide-destination\0", on_decide_destination as *const () );
		connect( download as *mut GObject, b"failed\0",             on_failed as *const () );
		connect( download as *mut GObject, b"finished\0",           on_finished as *const () );
	}
	if let Ok( mut r ) = REGISTRY.lock()
	{
		let id     = r.next_id;
		r.next_id += 1;
		r.live.push( Live { id, download: download as usize, reported: 0.0, failed: false } );
	}
}

unsafe extern "C" fn on_decide_destination( download: *mut WebKitDownload, suggested: *const c_char, _data: gpointer ) -> gboolean
{
	let name = if suggested.is_null()
	{
		String::new()
	} else {
		// SAFETY: WebKit passes a NUL-terminated suggested filename.
		unsafe { CStr::from_ptr( suggested ) }.to_string_lossy().into_owned()
	};
	let dir  = REGISTRY.lock().ok().and_then( |r| r.dir.clone() ).unwrap_or_else( default_dir );
	let _    = std::fs::create_dir_all( &dir );
	let path = unique_path( &dir, &sanitize( &name ) );
	let Ok( path_c ) = CString::new( path.to_string_lossy().as_bytes() ) else { return 0 };
	// SAFETY: `download` is live for the duration of the signal.
	let uri = unsafe
	{
		webkit_download_set_destination( download, path_c.as_ptr() );
		let request = webkit_download_get_request( download );
		if request.is_null() { String::new() } else { lossy( webkit_uri_request_get_uri( request ) ) }
	};
	if let Ok( mut r ) = REGISTRY.lock()
	{
		let id = r.live.iter().find( |l| l.download == download as usize ).map( |l| l.id );
		if let Some( id ) = id
		{
			r.events.push( DownloadEvent::Started { id, uri, path } );
		}
	}
	1
}

unsafe extern "C" fn on_failed( download: *mut WebKitDownload, _error: *mut GError, _data: gpointer )
{
	let Ok( mut r ) = REGISTRY.lock() else { return };
	let failed = r.live.iter_mut().find( |l| l.download == download as usize ).map( |l|
	{
		l.failed = true;
		l.id
	} );
	if let Some( id ) = failed
	{
		r.events.push( DownloadEvent::Failed { id } );
	}
}

/// `finished` always closes a download, after `failed` when there was one.
unsafe extern "C" fn on_finished( download: *mut WebKitDownload, _data: gpointer )
{
	let removed = REGISTRY.lock().ok().and_then( |mut r|
	{
		let pos  = r.live.iter().position( |l| l.download == download as usize )?;
		let live = r.live.remove( pos );
		if !live.failed
		{
			r.events.push( DownloadEvent::Finished { id: live.id } );
		}
		Some( () )
	} );
	if removed.is_some()
	{
		// SAFETY: balances the ref taken in `on_started`.
		unsafe { g_object_unref( download as *mut GObject ); }
	}
}

unsafe fn lossy( s: *const c_char ) -> String
{
	if s.is_null() { return String::new(); }
	// SAFETY: the caller passes a NUL-terminated string.
	unsafe { CStr::from_ptr( s ) }.to_string_lossy().into_owned()
}

fn default_dir() -> PathBuf
{
	if let Some( dir ) = std::env::var_os( "XDG_DOWNLOAD_DIR" ) { return PathBuf::from( dir ); }
	// SAFETY: GLib owns the returned string, which is NUL-terminated or null.
	let special = unsafe { g_get_user_special_dir( G_USER_DIRECTORY_DOWNLOAD ) };
	if !special.is_null()
	{
		// SAFETY: checked non-null above.
		let bytes = unsafe { CStr::from_ptr( special ) }.to_bytes();
		return PathBuf::from( OsStr::from_bytes( bytes ) );
	}
	let home = std::env::var_os( "HOME" ).map( PathBuf::from ).unwrap_or_else( || PathBuf::from( "/tmp" ) );
	home.join( "Downloads" )
}

/// Strip path separators so a hostile suggested name cannot leave the
/// download directory.
fn sanitize( name: &str ) -> String
{
	let clean: String = name.chars().map( |c| if c == '/' || c == '\0' { '_' } else { c } ).collect();
	let clean = clean.trim_start_matches( '.' ).trim();
	if clean.is_empty() { "download".to_string() } else { clean.to_string() }
}

fn unique_path( dir: &Path, name: &str ) -> PathBuf
{
	let first = dir.join( name );
	if !first.exists() { return first; }
	let ( stem, ext ) = match name.rsplit_once( '.' )
	{
		Some( ( stem, ext ) ) if !stem.is_empty() => ( stem, format!( ".{ext}" ) ),
		_                                         => ( name, String::new() ),
	};
	( 1u32.. )
		.map( |n| dir.join( format!( "{stem} ({n}){ext}" ) ) )
		.find( |p| !p.exists() )
		.unwrap_or( first )
}

#[ cfg( test ) ]
mod tests
{
	use super::*;

	#[ test ]
	fn sanitize_strips_separators_and_leading_dots()
	{
		assert_eq!( sanitize( "../../etc/passwd" ), "_.._etc_passwd" );
		assert_eq!( sanitize( ".bashrc" ), "bashrc" );
		assert_eq!( sanitize( "" ), "download" );
	}

	#[ test ]
	fn unique_path_keeps_a_free_name()
	{
		let dir = std::env::temp_dir().join( "ltk-webkit-unique-path-test" );
		assert_eq!( unique_path( &dir, "a.txt" ), dir.join( "a.txt" ) );
	}
}