author | wenzelm |
Sun, 02 Jul 2023 19:05:59 +0200 | |
changeset 78243 | 0e221a8128e4 |
parent 76356 | 92e9fa289056 |
child 78768 | 280a228dc2f1 |
permissions | -rw-r--r-- |
65077 | 1 |
/* Title: Pure/General/http.scala |
63823 | 2 |
Author: Makarius |
3 |
||
73438 | 4 |
HTTP client and server support. |
63823 | 5 |
*/ |
6 |
||
7 |
package isabelle |
|
8 |
||
9 |
||
73417 | 10 |
import java.io.{File => JFile} |
75104 | 11 |
import java.nio.file.Files |
75107 | 12 |
import java.net.{InetSocketAddress, URI, URL, HttpURLConnection} |
63823 | 13 |
import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer} |
14 |
||
15 |
||
75393 | 16 |
object HTTP { |
73416
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
17 |
/** content **/ |
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
18 |
|
75393 | 19 |
object Content { |
75106 | 20 |
val mime_type_bytes: String = "application/octet-stream" |
21 |
val mime_type_text: String = "text/plain; charset=utf-8" |
|
22 |
val mime_type_html: String = "text/html; charset=utf-8" |
|
73417 | 23 |
|
75106 | 24 |
val default_mime_type: String = mime_type_bytes |
76356 | 25 |
val default_encoding: String = UTF8.charset.name |
75106 | 26 |
|
27 |
def apply( |
|
28 |
bytes: Bytes, |
|
29 |
file_name: String = "", |
|
30 |
mime_type: String = default_mime_type, |
|
31 |
encoding: String = default_encoding, |
|
32 |
elapsed_time: Time = Time.zero): Content = |
|
33 |
new Content(bytes, file_name, mime_type, encoding, elapsed_time) |
|
73416
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
34 |
|
75393 | 35 |
def read(file: JFile): Content = { |
75106 | 36 |
val bytes = Bytes.read(file) |
37 |
val file_name = file.getName |
|
38 |
val mime_type = Option(Files.probeContentType(file.toPath)).getOrElse(default_mime_type) |
|
39 |
apply(bytes, file_name = file_name, mime_type = mime_type) |
|
40 |
} |
|
41 |
||
42 |
def read(path: Path): Content = read(path.file) |
|
43 |
} |
|
44 |
||
45 |
class Content private( |
|
46 |
val bytes: Bytes, |
|
47 |
val file_name: String, |
|
48 |
val mime_type: String, |
|
49 |
val encoding: String, |
|
75393 | 50 |
val elapsed_time: Time |
51 |
) { |
|
73440 | 52 |
def text: String = new String(bytes.array, encoding) |
74945 | 53 |
def json: JSON.T = JSON.parse(text) |
73416
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
54 |
} |
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
55 |
|
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
56 |
|
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
57 |
|
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
58 |
/** client **/ |
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
59 |
|
73417 | 60 |
val NEWLINE: String = "\r\n" |
61 |
||
75393 | 62 |
object Client { |
73439 | 63 |
val default_timeout: Time = Time.seconds(180) |
73422 | 64 |
|
75393 | 65 |
def open_connection( |
66 |
url: URL, |
|
73422 | 67 |
timeout: Time = default_timeout, |
75393 | 68 |
user_agent: String = "" |
69 |
): HttpURLConnection = { |
|
73421 | 70 |
url.openConnection match { |
71 |
case connection: HttpURLConnection => |
|
78243 | 72 |
if (0 < timeout.ms && timeout.ms <= Int.MaxValue) { |
73422 | 73 |
val ms = timeout.ms.toInt |
74 |
connection.setConnectTimeout(ms) |
|
75 |
connection.setReadTimeout(ms) |
|
76 |
} |
|
73421 | 77 |
proper_string(user_agent).foreach(s => connection.setRequestProperty("User-Agent", s)) |
78 |
connection |
|
79 |
case _ => error("Bad URL (not HTTP): " + quote(url.toString)) |
|
80 |
} |
|
81 |
} |
|
73417 | 82 |
|
75393 | 83 |
def get_content(connection: HttpURLConnection): Content = { |
73417 | 84 |
val Charset = """.*\bcharset="?([\S^"]+)"?.*""".r |
73429
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
85 |
|
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
86 |
val start = Time.now() |
75394 | 87 |
using(connection.getInputStream) { stream => |
73417 | 88 |
val bytes = Bytes.read_stream(stream, hint = connection.getContentLength) |
73429
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
89 |
val stop = Time.now() |
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
90 |
|
73417 | 91 |
val file_name = Url.file_name(connection.getURL) |
75106 | 92 |
val mime_type = Option(connection.getContentType).getOrElse(Content.default_mime_type) |
73417 | 93 |
val encoding = |
94 |
(connection.getContentEncoding, mime_type) match { |
|
95 |
case (enc, _) if enc != null => enc |
|
96 |
case (_, Charset(enc)) => enc |
|
75106 | 97 |
case _ => Content.default_encoding |
73417 | 98 |
} |
73429
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
99 |
Content(bytes, file_name = file_name, mime_type = mime_type, |
8970081c6500
elapsed time to download content (and for the server to provide content);
wenzelm
parents:
73425
diff
changeset
|
100 |
encoding = encoding, elapsed_time = stop - start) |
75394 | 101 |
} |
73417 | 102 |
} |
103 |
||
73422 | 104 |
def get(url: URL, timeout: Time = default_timeout, user_agent: String = ""): Content = |
105 |
get_content(open_connection(url, timeout = timeout, user_agent = user_agent)) |
|
73417 | 106 |
|
75393 | 107 |
def post( |
108 |
url: URL, |
|
109 |
parameters: List[(String, Any)], |
|
73422 | 110 |
timeout: Time = default_timeout, |
75393 | 111 |
user_agent: String = "" |
112 |
): Content = { |
|
73422 | 113 |
val connection = open_connection(url, timeout = timeout, user_agent = user_agent) |
73421 | 114 |
connection.setRequestMethod("POST") |
115 |
connection.setDoOutput(true) |
|
73417 | 116 |
|
74094 | 117 |
val boundary = UUID.random().toString |
73421 | 118 |
connection.setRequestProperty( |
119 |
"Content-Type", "multipart/form-data; boundary=" + quote(boundary)) |
|
73417 | 120 |
|
75394 | 121 |
using(connection.getOutputStream) { out => |
73421 | 122 |
def output(s: String): Unit = out.write(UTF8.bytes(s)) |
123 |
def output_newline(n: Int = 1): Unit = (1 to n).foreach(_ => output(NEWLINE)) |
|
124 |
def output_boundary(end: Boolean = false): Unit = |
|
125 |
output("--" + boundary + (if (end) "--" else "") + NEWLINE) |
|
126 |
def output_name(name: String): Unit = |
|
127 |
output("Content-Disposition: form-data; name=" + quote(name)) |
|
75393 | 128 |
def output_value(value: Any): Unit = { |
73421 | 129 |
output_newline(2) |
130 |
output(value.toString) |
|
131 |
} |
|
75393 | 132 |
def output_content(content: Content): Unit = { |
73421 | 133 |
proper_string(content.file_name).foreach(s => output("; filename=" + quote(s))) |
134 |
output_newline() |
|
135 |
proper_string(content.mime_type).foreach(s => output("Content-Type: " + s)) |
|
136 |
output_newline(2) |
|
137 |
content.bytes.write_stream(out) |
|
138 |
} |
|
73417 | 139 |
|
73421 | 140 |
output_newline(2) |
73417 | 141 |
|
73421 | 142 |
for { (name, value) <- parameters } { |
143 |
output_boundary() |
|
144 |
output_name(name) |
|
145 |
value match { |
|
146 |
case content: Content => output_content(content) |
|
75106 | 147 |
case file: JFile => output_content(Content.read(file)) |
148 |
case path: Path => output_content(Content.read(path)) |
|
73421 | 149 |
case _ => output_value(value) |
150 |
} |
|
151 |
output_newline() |
|
152 |
} |
|
153 |
output_boundary(end = true) |
|
154 |
out.flush() |
|
75394 | 155 |
} |
73417 | 156 |
|
73421 | 157 |
get_content(connection) |
73416
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
158 |
} |
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
159 |
} |
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
160 |
|
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
161 |
|
08aa4c1ed579
clarified signature: more explicit HTTP operations;
wenzelm
parents:
73413
diff
changeset
|
162 |
|
65081 | 163 |
/** server **/ |
164 |
||
75107 | 165 |
/* request */ |
166 |
||
75108 | 167 |
def url_path(names: String*): String = |
168 |
names.iterator.flatMap(a => if (a.isEmpty) None else Some("/" + a)).mkString |
|
169 |
||
170 |
class Request private[HTTP]( |
|
75146 | 171 |
val server_name: String, |
172 |
val service_name: String, |
|
75108 | 173 |
val uri: URI, |
75393 | 174 |
val input: Bytes |
175 |
) { |
|
75146 | 176 |
def home: String = url_path(server_name, service_name) |
75107 | 177 |
def root: String = home + "/" |
178 |
def query: String = home + "?" |
|
179 |
||
75109 | 180 |
def toplevel: Boolean = uri_name == home || uri_name == root |
181 |
||
182 |
val uri_name: String = uri.toString |
|
75107 | 183 |
|
184 |
def uri_path: Option[Path] = |
|
185 |
for { |
|
75111 | 186 |
s <- Option(uri.getPath).flatMap(Library.try_unprefix(root, _)) |
187 |
if Path.is_wellformed(s) |
|
188 |
p = Path.explode(s) if p.all_basic |
|
75107 | 189 |
} yield p |
190 |
||
75112 | 191 |
def decode_query: Option[String] = |
192 |
Library.try_unprefix(query, uri_name).map(Url.decode) |
|
193 |
||
75107 | 194 |
def decode_properties: Properties.T = |
195 |
space_explode('&', input.text).map( |
|
196 |
{ |
|
197 |
case Properties.Eq(a, b) => Url.decode(a) -> Url.decode(b) |
|
198 |
case s => error("Malformed key-value pair in HTTP/POST: " + quote(s)) |
|
199 |
}) |
|
200 |
} |
|
201 |
||
202 |
||
65078 | 203 |
/* response */ |
204 |
||
75393 | 205 |
object Response { |
65078 | 206 |
def apply( |
207 |
bytes: Bytes = Bytes.empty, |
|
75106 | 208 |
content_type: String = Content.mime_type_bytes): Response = |
65078 | 209 |
new Response(bytes, content_type) |
210 |
||
211 |
val empty: Response = apply() |
|
75106 | 212 |
def text(s: String): Response = apply(Bytes(s), Content.mime_type_text) |
213 |
def html(s: String): Response = apply(Bytes(s), Content.mime_type_html) |
|
75105
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
214 |
|
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
215 |
def content(content: Content): Response = apply(content.bytes, content.mime_type) |
75106 | 216 |
def read(file: JFile): Response = content(Content.read(file)) |
217 |
def read(path: Path): Response = content(Content.read(path)) |
|
65078 | 218 |
} |
219 |
||
75393 | 220 |
class Response private[HTTP](val output: Bytes, val content_type: String) { |
75107 | 221 |
override def toString: String = output.toString |
65078 | 222 |
|
75393 | 223 |
def write(http: HttpExchange, code: Int): Unit = { |
75107 | 224 |
http.getResponseHeaders.set("Content-Type", content_type) |
225 |
http.sendResponseHeaders(code, output.length.toLong) |
|
226 |
using(http.getResponseBody)(output.write_stream) |
|
65078 | 227 |
} |
228 |
} |
|
229 |
||
230 |
||
75107 | 231 |
/* service */ |
66207 | 232 |
|
75393 | 233 |
abstract class Service(val name: String, method: String = "GET") { |
75146 | 234 |
override def toString: String = name |
75113 | 235 |
|
236 |
def apply(request: Request): Option[Response] |
|
237 |
||
75146 | 238 |
def context(server_name: String): String = |
239 |
proper_string(url_path(server_name, name)).getOrElse("/") |
|
75113 | 240 |
|
75394 | 241 |
def handler(server_name: String): HttpHandler = { (http: HttpExchange) => |
75113 | 242 |
val uri = http.getRequestURI |
243 |
val input = using(http.getRequestBody)(Bytes.read_stream(_)) |
|
244 |
if (http.getRequestMethod == method) { |
|
75146 | 245 |
val request = new Request(server_name, name, uri, input) |
75113 | 246 |
Exn.capture(apply(request)) match { |
247 |
case Exn.Res(Some(response)) => |
|
248 |
response.write(http, 200) |
|
249 |
case Exn.Res(None) => |
|
250 |
Response.empty.write(http, 404) |
|
251 |
case Exn.Exn(ERROR(msg)) => |
|
252 |
Response.text(Output.error_message_text(msg)).write(http, 500) |
|
253 |
case Exn.Exn(exn) => throw exn |
|
75107 | 254 |
} |
75113 | 255 |
} |
256 |
else Response.empty.write(http, 400) |
|
75107 | 257 |
} |
73413 | 258 |
} |
66207 | 259 |
|
65077 | 260 |
|
261 |
/* server */ |
|
262 |
||
75393 | 263 |
class Server private[HTTP](val name: String, val http_server: HttpServer) { |
75107 | 264 |
def += (service: Service): Unit = |
75108 | 265 |
http_server.createContext(service.context(name), service.handler(name)) |
75107 | 266 |
def -= (service: Service): Unit = |
75108 | 267 |
http_server.removeContext(service.context(name)) |
65077 | 268 |
|
73439 | 269 |
def start(): Unit = http_server.start() |
73367 | 270 |
def stop(): Unit = http_server.stop(0) |
65077 | 271 |
|
272 |
def address: InetSocketAddress = http_server.getAddress |
|
75107 | 273 |
|
75108 | 274 |
def url: String = "http://" + address.getHostName + ":" + address.getPort + url_path(name) |
65077 | 275 |
override def toString: String = url |
276 |
} |
|
277 |
||
75107 | 278 |
def server( |
76270 | 279 |
port: Int = 0, |
75107 | 280 |
name: String = UUID.random().toString, |
75393 | 281 |
services: List[Service] = isabelle_services |
282 |
): Server = { |
|
76270 | 283 |
val http_server = HttpServer.create(new InetSocketAddress(isabelle.Server.localhost, port), 0) |
65077 | 284 |
http_server.setExecutor(null) |
65076 | 285 |
|
75107 | 286 |
val server = new Server(name, http_server) |
287 |
for (service <- services) server += service |
|
65077 | 288 |
server |
63823 | 289 |
} |
65079 | 290 |
|
291 |
||
65081 | 292 |
|
75107 | 293 |
/** Isabelle services **/ |
65081 | 294 |
|
75113 | 295 |
def isabelle_services: List[Service] = |
75145 | 296 |
List(Welcome_Service, Fonts_Service, PDFjs_Service, Docs_Service) |
65081 | 297 |
|
298 |
||
299 |
/* welcome */ |
|
300 |
||
75145 | 301 |
object Welcome_Service extends Welcome() |
302 |
||
75393 | 303 |
class Welcome(name: String = "") extends Service(name) { |
75113 | 304 |
def apply(request: Request): Option[Response] = |
305 |
if (request.toplevel) { |
|
306 |
Some(Response.text("Welcome to " + Isabelle_System.identification())) |
|
307 |
} |
|
308 |
else None |
|
309 |
} |
|
65081 | 310 |
|
311 |
||
312 |
/* fonts */ |
|
65079 | 313 |
|
75145 | 314 |
object Fonts_Service extends Fonts() |
315 |
||
75393 | 316 |
class Fonts(name: String = "fonts") extends Service(name) { |
75113 | 317 |
private lazy val html_fonts: List[Isabelle_Fonts.Entry] = |
318 |
Isabelle_Fonts.fonts(hidden = true) |
|
65079 | 319 |
|
75113 | 320 |
def apply(request: Request): Option[Response] = |
321 |
if (request.toplevel) { |
|
322 |
Some(Response.text(cat_lines(html_fonts.map(entry => entry.path.file_name)))) |
|
323 |
} |
|
324 |
else { |
|
325 |
request.uri_path.flatMap(path => |
|
326 |
html_fonts.collectFirst( |
|
327 |
{ case entry if path == entry.path.base => Response(entry.bytes) } |
|
328 |
)) |
|
329 |
} |
|
330 |
} |
|
75105
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
331 |
|
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
332 |
|
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
333 |
/* pdfjs */ |
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
334 |
|
75145 | 335 |
object PDFjs_Service extends PDFjs() |
336 |
||
75393 | 337 |
class PDFjs(name: String = "pdfjs") extends Service(name) { |
75113 | 338 |
def apply(request: Request): Option[Response] = |
75105
03115c9eea00
support for PDF.js: platform-independent PDF viewer;
wenzelm
parents:
75104
diff
changeset
|
339 |
for { |
75107 | 340 |
p <- request.uri_path |
75117 | 341 |
path = Path.explode("$ISABELLE_PDFJS_HOME") + p if path.is_file |
342 |
s = p.implode if s.startsWith("build/") || s.startsWith("web/") |
|
75113 | 343 |
} yield Response.read(path) |
344 |
} |
|
75119 | 345 |
|
346 |
||
347 |
/* docs */ |
|
348 |
||
75145 | 349 |
object Docs_Service extends Docs() |
350 |
||
75393 | 351 |
class Docs(name: String = "docs") extends PDFjs(name) { |
75119 | 352 |
private val doc_contents = isabelle.Doc.main_contents() |
353 |
||
75121 | 354 |
// example: .../docs/web/viewer.html?file=system.pdf |
75119 | 355 |
def doc_request(request: Request): Option[Response] = |
356 |
for { |
|
357 |
p <- request.uri_path if p.is_pdf |
|
75121 | 358 |
s = p.implode if s.startsWith("web/") |
75119 | 359 |
name = p.base.split_ext._1.implode |
360 |
doc <- doc_contents.docs.find(_.name == name) |
|
75120 | 361 |
} yield Response.read(doc.path) |
75119 | 362 |
|
363 |
override def apply(request: Request): Option[Response] = |
|
364 |
doc_request(request) orElse super.apply(request) |
|
365 |
} |
|
366 |
} |