use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use bytes::Bytes;
use serde_json::{Value as Json, json};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq)]
pub struct PdfOptions {
pub paper_mm: (f64, f64),
pub landscape: bool,
pub print_background: bool,
pub margin_mm: [f64; 4],
pub header: Option<String>,
pub footer: Option<String>,
pub allow: Vec<String>,
pub timeout: Duration,
}
impl PdfOptions {
pub fn a4() -> Self {
Self {
paper_mm: (210.0, 297.0),
landscape: false,
print_background: true,
margin_mm: [10.0; 4],
header: None,
footer: None,
allow: Vec::new(),
timeout: Duration::from_secs(30),
}
}
pub fn letter() -> Self {
Self {
paper_mm: (215.9, 279.4),
..Self::a4()
}
}
pub fn landscape(mut self) -> Self {
self.landscape = true;
self
}
pub fn margins(mut self, top: f64, right: f64, bottom: f64, left: f64) -> Self {
self.margin_mm = [top, right, bottom, left];
self
}
pub fn header(mut self, html: impl Into<String>) -> Self {
self.header = Some(html.into());
self
}
pub fn footer(mut self, html: impl Into<String>) -> Self {
self.footer = Some(html.into());
self
}
pub fn allow(mut self, prefix: impl Into<String>) -> Self {
self.allow.push(prefix.into());
self
}
}
impl Default for PdfOptions {
fn default() -> Self {
Self::a4()
}
}
type Pending<'a> = Pin<Box<dyn Future<Output = Result<Bytes>> + Send + 'a>>;
pub trait PdfRenderer: Send + Sync {
fn render<'a>(&'a self, html: &'a str, options: &'a PdfOptions) -> Pending<'a>;
}
pub async fn render(html: &str, options: &PdfOptions) -> Result<Bytes> {
if let Some(rendered) = record_in_test(html, options) {
return Ok(rendered);
}
let chrome = Chrome::find().ok_or_else(|| {
Error::internal(
"no Chrome to print PDFs with: install Chrome or Chromium, or set CHROME_PATH",
)
})?;
chrome.render(html, options).await
}
pub async fn render_template(
template: impl crate::view::Template,
options: &PdfOptions,
) -> Result<Bytes> {
render(&template.render().to_html(), options).await
}
pub fn data_url(content_type: &str, bytes: &[u8]) -> String {
format!("data:{content_type};base64,{}", STANDARD.encode(bytes))
}
#[derive(Debug, Clone)]
pub struct Chrome {
executable: PathBuf,
}
impl Chrome {
pub fn new(executable: impl Into<PathBuf>) -> Self {
Self {
executable: executable.into(),
}
}
pub fn find() -> Option<Self> {
if let Some(path) = std::env::var_os("CHROME_PATH").filter(|p| !p.is_empty()) {
return Some(Self::new(path));
}
const PLACES: &[&str] = &[
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
"/usr/bin/google-chrome",
"/usr/bin/google-chrome-stable",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
];
if let Some(place) = PLACES.iter().find(|p| Path::new(p).exists()) {
return Some(Self::new(place));
}
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path)
.flat_map(|dir| {
[
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser",
]
.map(|name| dir.join(name))
})
.find(|candidate| candidate.is_file())
.map(Self::new)
}
async fn print(&self, html: &str, options: &PdfOptions) -> Result<Bytes> {
let profile =
std::env::temp_dir().join(format!("glacier-chrome-{}", &crate::random::token()[..16]));
let mut child = tokio::process::Command::new(&self.executable)
.args([
"--headless=new",
"--disable-gpu",
"--no-first-run",
"--no-default-browser-check",
"--disable-extensions",
"--disable-background-networking",
"--disable-sync",
"--disable-default-apps",
"--mute-audio",
"--hide-scrollbars",
"--remote-debugging-port=0",
"--remote-debugging-address=127.0.0.1",
])
.arg(format!("--user-data-dir={}", profile.display()))
.arg("about:blank")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|err| {
Error::internal(format!(
"couldn't start {}: {err}",
self.executable.display()
))
})?;
let result = async {
let stderr = child
.stderr
.take()
.ok_or_else(|| Error::internal("Chrome's stderr"))?;
let url = devtools_url(stderr).await?;
let mut session = Session::connect(&url).await?;
session.print(html, options).await
};
let result = tokio::time::timeout(options.timeout, result)
.await
.unwrap_or_else(|_| {
Err(Error::internal(format!(
"printing a PDF took over {:?}",
options.timeout
)))
});
let _ = child.kill().await;
let _ = tokio::fs::remove_dir_all(&profile).await;
result
}
}
impl PdfRenderer for Chrome {
fn render<'a>(&'a self, html: &'a str, options: &'a PdfOptions) -> Pending<'a> {
Box::pin(self.print(html, options))
}
}
async fn devtools_url(stderr: tokio::process::ChildStderr) -> Result<String> {
let mut lines = BufReader::new(stderr).lines();
let mut seen = Vec::new();
while let Some(line) = lines
.next_line()
.await
.map_err(|err| Error::internal(format!("reading Chrome's output: {err}")))?
{
if let Some(url) = line.strip_prefix("DevTools listening on ") {
tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} });
return Ok(url.trim().to_owned());
}
seen.push(line);
}
Err(Error::internal(format!(
"Chrome exited before it was ready: {}",
seen.join("\n")
)))
}
struct Session {
socket: WebSocket,
next_id: u64,
session_id: Option<String>,
allow: Vec<String>,
loaded: bool,
}
impl Session {
async fn connect(url: &str) -> Result<Self> {
Ok(Self {
socket: WebSocket::connect(url).await?,
next_id: 0,
session_id: None,
allow: Vec::new(),
loaded: false,
})
}
async fn print(&mut self, html: &str, options: &PdfOptions) -> Result<Bytes> {
self.allow = options.allow.clone();
let target = self
.call("Target.createTarget", json!({"url": "about:blank"}))
.await?;
let target_id = target["targetId"].as_str().unwrap_or_default().to_owned();
let attached = self
.call(
"Target.attachToTarget",
json!({"targetId": target_id, "flatten": true}),
)
.await?;
self.session_id = attached["sessionId"].as_str().map(str::to_owned);
self.call("Page.enable", json!({})).await?;
self.call(
"Emulation.setScriptExecutionDisabled",
json!({"value": true}),
)
.await?;
self.call("Fetch.enable", json!({"patterns": [{"urlPattern": "*"}]}))
.await?;
let tree = self.call("Page.getFrameTree", json!({})).await?;
let frame_id = tree["frameTree"]["frame"]["id"]
.as_str()
.unwrap_or_default()
.to_owned();
self.loaded = false;
self.call(
"Page.setDocumentContent",
json!({"frameId": frame_id, "html": html}),
)
.await?;
let _ = tokio::time::timeout(Duration::from_secs(5), self.until_loaded()).await;
let inch = |mm: f64| mm / 25.4;
let (width, height) = options.paper_mm;
let [top, right, bottom, left] = options.margin_mm;
let headed = options.header.is_some() || options.footer.is_some();
let printed = self
.call(
"Page.printToPDF",
json!({
"landscape": options.landscape,
"printBackground": options.print_background,
"paperWidth": inch(width),
"paperHeight": inch(height),
"marginTop": inch(top),
"marginRight": inch(right),
"marginBottom": inch(bottom),
"marginLeft": inch(left),
"displayHeaderFooter": headed,
"headerTemplate": options.header.clone().unwrap_or_else(|| "<span></span>".into()),
"footerTemplate": options.footer.clone().unwrap_or_else(|| "<span></span>".into()),
"preferCSSPageSize": false,
}),
)
.await?;
let data = printed["data"].as_str().unwrap_or_default();
let bytes = STANDARD
.decode(data)
.map_err(|err| Error::internal(format!("Chrome's PDF wasn't base64: {err}")))?;
let _ = self.send("Browser.close", json!({}), false).await;
Ok(bytes.into())
}
async fn until_loaded(&mut self) -> Result<()> {
while !self.loaded {
let message = self.next_message().await?;
self.handle_event(&message).await?;
}
Ok(())
}
async fn next_message(&mut self) -> Result<Json> {
serde_json::from_str(&self.socket.read().await?)
.map_err(|err| Error::internal(format!("Chrome sent bad JSON: {err}")))
}
async fn handle_event(&mut self, message: &Json) -> Result<()> {
match message["method"].as_str() {
Some("Fetch.requestPaused") => self.decide(&message["params"]).await,
Some("Page.loadEventFired") => {
self.loaded = true;
Ok(())
}
_ => Ok(()),
}
}
async fn call(&mut self, method: &str, params: Json) -> Result<Json> {
let id = self.send(method, params, true).await?;
loop {
let message = self.next_message().await?;
if message["id"].as_u64() == Some(id) {
if let Some(error) = message.get("error") {
return Err(Error::internal(format!("Chrome: {method}: {error}")));
}
return Ok(message["result"].clone());
}
self.handle_event(&message).await?;
}
}
async fn send(&mut self, method: &str, params: Json, in_page: bool) -> Result<u64> {
self.next_id += 1;
let mut message = json!({"id": self.next_id, "method": method, "params": params});
if in_page && let Some(session) = &self.session_id {
message["sessionId"] = session.clone().into();
}
self.socket.send(&message.to_string()).await?;
Ok(self.next_id)
}
async fn decide(&mut self, request: &Json) -> Result<()> {
let id = request["requestId"].clone();
let url = request["request"]["url"].as_str().unwrap_or_default();
let allowed = url.starts_with("data:") || self.allow.iter().any(|p| url.starts_with(p));
if allowed {
self.send("Fetch.continueRequest", json!({"requestId": id}), true)
.await?;
} else {
tracing::debug!(target: "glacier", "PDF: refused a request for {url}");
self.send(
"Fetch.failRequest",
json!({"requestId": id, "errorReason": "BlockedByClient"}),
true,
)
.await?;
}
Ok(())
}
}
struct WebSocket {
stream: BufReader<TcpStream>,
}
impl WebSocket {
async fn connect(url: &str) -> Result<Self> {
let rest = url
.strip_prefix("ws://")
.ok_or_else(|| Error::internal(format!("not a ws:// address: {url}")))?;
let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
let stream = TcpStream::connect(host)
.await
.map_err(|err| Error::internal(format!("connecting to Chrome: {err}")))?;
let mut stream = BufReader::new(stream);
let key = STANDARD.encode(random::<16>());
let request = format!(
"GET /{path} HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\n\
Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n\
Sec-WebSocket-Version: 13\r\n\r\n"
);
stream
.get_mut()
.write_all(request.as_bytes())
.await
.map_err(io)?;
let mut status = String::new();
stream.read_line(&mut status).await.map_err(io)?;
if !status.contains(" 101 ") {
return Err(Error::internal(format!(
"Chrome refused the DevTools connection: {}",
status.trim()
)));
}
loop {
let mut line = String::new();
if stream.read_line(&mut line).await.map_err(io)? == 0 || line == "\r\n" {
break;
}
}
Ok(Self { stream })
}
async fn send(&mut self, text: &str) -> Result<()> {
self.frame(0x1, text.as_bytes()).await
}
async fn frame(&mut self, opcode: u8, payload: &[u8]) -> Result<()> {
let mut frame = vec![0x80 | opcode];
let len = payload.len();
if len < 126 {
frame.push(0x80 | len as u8);
} else if let Ok(len) = u16::try_from(len) {
frame.push(0x80 | 126);
frame.extend_from_slice(&len.to_be_bytes());
} else {
frame.push(0x80 | 127);
frame.extend_from_slice(&(len as u64).to_be_bytes());
}
let mask = random::<4>();
frame.extend_from_slice(&mask);
frame.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
self.stream.get_mut().write_all(&frame).await.map_err(io)
}
async fn read(&mut self) -> Result<String> {
let mut message = Vec::new();
loop {
let mut head = [0u8; 2];
self.stream.read_exact(&mut head).await.map_err(io)?;
let fin = head[0] & 0x80 != 0;
let opcode = head[0] & 0x0f;
let masked = head[1] & 0x80 != 0;
let len = match head[1] & 0x7f {
126 => {
let mut n = [0u8; 2];
self.stream.read_exact(&mut n).await.map_err(io)?;
u64::from(u16::from_be_bytes(n))
}
127 => {
let mut n = [0u8; 8];
self.stream.read_exact(&mut n).await.map_err(io)?;
u64::from_be_bytes(n)
}
n => u64::from(n),
};
let mut mask = [0u8; 4];
if masked {
self.stream.read_exact(&mut mask).await.map_err(io)?;
}
let len = usize::try_from(len)
.map_err(|_| Error::internal("a DevTools message too large to read"))?;
let mut payload = vec![0u8; len];
self.stream.read_exact(&mut payload).await.map_err(io)?;
if masked {
for (i, b) in payload.iter_mut().enumerate() {
*b ^= mask[i % 4];
}
}
match opcode {
0x0 | 0x1 => {
message.extend_from_slice(&payload);
if fin {
return String::from_utf8(message).map_err(|_| {
Error::internal("Chrome sent a message that wasn't UTF-8")
});
}
}
0x8 => return Err(Error::internal("Chrome closed the DevTools connection")),
0x9 => self.frame(0xA, &payload).await?,
_ => {}
}
}
}
}
fn random<const N: usize>() -> [u8; N] {
let mut bytes = [0u8; N];
getrandom::fill(&mut bytes).expect("the OS random number generator failed");
bytes
}
fn io(err: std::io::Error) -> Error {
Error::internal(format!("talking to Chrome: {err}"))
}
pub const PLACEHOLDER: &[u8] = b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n\
2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n\
3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]>>endobj\n\
trailer<</Root 1 0 R>>\n%%EOF\n";
#[derive(Debug, Clone)]
pub struct Rendered {
pub html: String,
pub options: PdfOptions,
}
tokio::task_local! {
static RENDERED: Arc<Mutex<Vec<Rendered>>>;
}
fn record_in_test(html: &str, options: &PdfOptions) -> Option<Bytes> {
RENDERED
.try_with(|rendered| {
rendered
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Rendered {
html: html.to_owned(),
options: options.clone(),
});
Bytes::from_static(PLACEHOLDER)
})
.ok()
}
#[doc(hidden)]
pub async fn with_test_recorder<F: Future>(fut: F) -> F::Output {
RENDERED.scope(Arc::default(), fut).await
}
pub(crate) fn rendered() -> Vec<Rendered> {
RENDERED
.try_with(|rendered| rendered.lock().unwrap_or_else(|e| e.into_inner()).clone())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_test_records_what_it_prints() {
with_test_recorder(async {
let pdf = render("<h1>Receipt</h1>", &PdfOptions::a4().landscape())
.await
.unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let rendered = rendered();
assert_eq!(rendered.len(), 1);
assert_eq!(rendered[0].html, "<h1>Receipt</h1>");
assert!(rendered[0].options.landscape);
})
.await;
}
#[test]
fn data_urls_inline_bytes() {
assert_eq!(
data_url("image/gif", b"GIF8"),
"data:image/gif;base64,R0lGOA=="
);
}
#[test]
fn options_read_like_puppeteer_s() {
let options = PdfOptions::letter()
.margins(20.0, 10.0, 20.0, 10.0)
.footer("<span class=\"pageNumber\"></span>")
.allow("https://assets.example.com/");
assert_eq!(options.paper_mm, (215.9, 279.4));
assert_eq!(options.margin_mm, [20.0, 10.0, 20.0, 10.0]);
assert!(options.print_background);
assert_eq!(options.allow, ["https://assets.example.com/"]);
}
}