Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

872 lines
31 KiB

  1. ;;; simple-httpd.el --- pure elisp HTTP server
  2. ;; This is free and unencumbered software released into the public domain.
  3. ;; Author: Christopher Wellons <wellons@nullprogram.com>
  4. ;; URL: https://github.com/skeeto/emacs-http-server
  5. ;; Package-Version: 1.5.1
  6. ;; Package-Commit: a5eb49a6567e33586fba15dd649d63ca6e964314
  7. ;; Version: 1.5.1
  8. ;; Package-Requires: ((cl-lib "0.3"))
  9. ;;; Commentary:
  10. ;; Use `httpd-start' to start the web server. Files are served from
  11. ;; `httpd-root' on port `httpd-port' using `httpd-ip-family' at host
  12. ;; `httpd-host'. While the root can be changed at any time, the server
  13. ;; needs to be restarted in order for a port change to take effect.
  14. ;; Everything is performed by servlets, including serving
  15. ;; files. Servlets are enabled by setting `httpd-servlets' to true
  16. ;; (default). Servlets are four-parameter functions that begin with
  17. ;; "httpd/" where the trailing component specifies the initial path on
  18. ;; the server. For example, the function `httpd/hello-world' will be
  19. ;; called for the request "/hello-world" and "/hello-world/foo".
  20. ;; The default servlet `httpd/' is the one that serves files from
  21. ;; `httpd-root' and can be turned off through redefinition or setting
  22. ;; `httpd-serve-files' to nil. It is used even when `httpd-servlets'
  23. ;; is nil.
  24. ;; The four parameters for a servlet are process, URI path, GET/POST
  25. ;; arguments (alist), and the full request object (header
  26. ;; alist). These are ordered by general importance so that some can be
  27. ;; ignored. Two macros are provided to help with writing servlets.
  28. ;; * `with-httpd-buffer' -- Creates a temporary buffer that is
  29. ;; automatically served to the client at the end of the body.
  30. ;; Additionally, `standard-output' is set to this output
  31. ;; buffer. For example, this servlet says hello,
  32. ;; (defun httpd/hello-world (proc path &rest args)
  33. ;; (with-httpd-buffer proc "text/plain"
  34. ;; (insert "hello, " (file-name-nondirectory path))))
  35. ;; This servlet be viewed at http://localhost:8080/hello-world/Emacs
  36. ;; * `defservlet' -- Similar to the above macro but totally hides the
  37. ;; process object from the servlet itself. The above servlet can be
  38. ;; re-written identically like so,
  39. ;; (defservlet hello-world text/plain (path)
  40. ;; (insert "hello, " (file-name-nondirectory path)))
  41. ;; Note that `defservlet' automatically sets `httpd-current-proc'. See
  42. ;; below.
  43. ;; The "function parameters" part can be left empty or contain up to
  44. ;; three parameters corresponding to the final three servlet
  45. ;; parameters. For example, a servlet that shows *scratch* and doesn't
  46. ;; need parameters,
  47. ;; (defservlet scratch text/plain ()
  48. ;; (insert-buffer-substring (get-buffer-create "*scratch*")))
  49. ;; A higher level macro `defservlet*' wraps this lower-level
  50. ;; `defservlet' macro, automatically binding variables to components
  51. ;; of the request. For example, this binds parts of the request path
  52. ;; and one query parameter. Request components not provided by the
  53. ;; client are bound to nil.
  54. ;; (defservlet* packages/:package/:version text/plain (verbose)
  55. ;; (insert (format "%s\n%s\n" package version))
  56. ;; (princ (get-description package version))
  57. ;; (when verbose
  58. ;; (insert (format "%S" (get-dependencies package version)))))
  59. ;; It would be accessed like so,
  60. ;; http://example.com/packages/foobar/1.0?verbose=1
  61. ;; Some support functions are available for servlets for more
  62. ;; customized responses.
  63. ;; * `httpd-send-file' -- serve a file with proper caching
  64. ;; * `httpd-redirect' -- redirect the browser to another url
  65. ;; * `httpd-send-header' -- send custom headers
  66. ;; * `httpd-error' -- report an error to the client
  67. ;; * `httpd-log' -- log an object to *httpd*
  68. ;; Some of these functions require a process object, which isn't
  69. ;; passed to `defservlet' servlets. Use t in place of the process
  70. ;; argument to use `httpd-current-proc' (like `standard-output').
  71. ;; If you just need to serve static from some location under some
  72. ;; route on the server, use `httpd-def-file-servlet'. It expands into
  73. ;; a `defservlet' that serves files.
  74. ;;; History:
  75. ;; Version 1.5.1: improvements
  76. ;; * Add `httpd-running-p'
  77. ;; * Properly handle "Connection: close" and HTTP/1.0
  78. ;; Version 1.5.0: improvements
  79. ;; * Drastically improved performance for large requests
  80. ;; * More HTTP status codes
  81. ;; Version 1.4.6: fixes
  82. ;; * Added httpd-serve-directory
  83. ;; * Fix some encoding issues
  84. ;; Version 1.4.5: fixes
  85. ;; * Update to cl-lib from cl
  86. ;; Version 1.4.4: features
  87. ;; * Common Lisp &key-like defservlet* argument support
  88. ;; * Fix up some defservlet* usage warnings.
  89. ;; Version 1.4.3: features
  90. ;; * Add `httpd-discard-buffer'
  91. ;; * Add `httpd-def-file-servlet'
  92. ;; * Be more careful about not sending extra headers
  93. ;; Version 1.4.2: features, fixes
  94. ;; * `defservlet*' macro
  95. ;; Version 1.4.1: small bug fixes, one feature
  96. ;; * All mime-type parameters now accept string designators
  97. ;; * Documentation update
  98. ;; Version 1.4.0: features, API change, and fixes
  99. ;; * Removed httpd-send-buffer; httpd-send-header now does this implicitly
  100. ;; * httpd-send-header now accepts keywords instead
  101. ;; * Fix httpd-clean-path in Windows
  102. ;; * Fix a content-length bug
  103. ;; * defservlet fontification
  104. ;; Version 1.3.1: features and fixes
  105. ;; * Set `standard-output' in `with-httpd-buffer'
  106. ;; Version 1.3.0: security fix
  107. ;; * Fix path expansion security issue
  108. ;; * Fix coding system (don't default)
  109. ;; Version 1.2.4: fixes
  110. ;; * Handle large POSTs
  111. ;; * Fix date strings
  112. ;;; Code:
  113. (require 'cl-lib)
  114. (require 'pp)
  115. (require 'url-util)
  116. (defgroup simple-httpd nil
  117. "A simple web server."
  118. :group 'comm)
  119. (defcustom httpd-ip-family 'ipv4
  120. "Web server IP family used by `make-network-process'."
  121. :group 'simple-httpd
  122. :type 'symbol)
  123. (defcustom httpd-host nil
  124. "Web server host name used by `make-network-process'."
  125. :group 'simple-httpd
  126. :type '(choice (const nil) (const local) string))
  127. (defcustom httpd-port 8080
  128. "Web server port."
  129. :group 'simple-httpd
  130. :type 'integer)
  131. (defcustom httpd-root "~/public_html"
  132. "Web server file root."
  133. :group 'simple-httpd
  134. :type 'directory)
  135. (defcustom httpd-serve-files t
  136. "Enable serving files from `httpd-root'."
  137. :group 'simple-httpd
  138. :type 'boolean)
  139. (defcustom httpd-listings t
  140. "If true, serve directory listings."
  141. :group 'simple-httpd
  142. :type 'boolean)
  143. (defcustom httpd-servlets t
  144. "Enable servlets."
  145. :group 'simple-httpd
  146. :type 'boolean)
  147. (defcustom httpd-start-hook nil
  148. "Hook to run when the server has started."
  149. :group 'simple-httpd
  150. :type 'hook)
  151. (defcustom httpd-stop-hook nil
  152. "Hook to run when the server has stopped."
  153. :group 'simple-httpd
  154. :type 'hook)
  155. (defvar httpd-server-name (format "simple-httpd (Emacs %s)" emacs-version)
  156. "String to use in the Server header.")
  157. (defvar httpd-mime-types
  158. '(("png" . "image/png")
  159. ("gif" . "image/gif")
  160. ("jpg" . "image/jpeg")
  161. ("jpeg" . "image/jpeg")
  162. ("tif" . "image/tif")
  163. ("tiff" . "image/tiff")
  164. ("ico" . "image/x-icon")
  165. ("svg" . "image/svg+xml")
  166. ("css" . "text/css")
  167. ("htm" . "text/html")
  168. ("html" . "text/html")
  169. ("xml" . "text/xml")
  170. ("rss" . "text/xml")
  171. ("atom" . "text/xml")
  172. ("txt" . "text/plain")
  173. ("el" . "text/plain")
  174. ("js" . "text/javascript")
  175. ("md" . "text/x-markdown")
  176. ("gz" . "application/octet-stream")
  177. ("ps" . "application/postscript")
  178. ("eps" . "application/postscript")
  179. ("pdf" . "application/pdf")
  180. ("tar" . "application/x-tar")
  181. ("zip" . "application/zip")
  182. ("mp3" . "audio/mpeg")
  183. ("wav" . "audio/x-wav")
  184. ("flac" . "audio/flac")
  185. ("spx" . "audio/ogg")
  186. ("oga" . "audio/ogg")
  187. ("ogg" . "audio/ogg")
  188. ("ogv" . "video/ogg")
  189. ("mp4" . "video/mp4")
  190. ("mkv" . "video/x-matroska")
  191. ("webm" . "video/webm"))
  192. "MIME types for headers.")
  193. (defvar httpd-indexes
  194. '("index.html"
  195. "index.htm"
  196. "index.xml")
  197. "File served by default when accessing a directory.")
  198. (defvar httpd-status-codes
  199. '((100 . "Continue")
  200. (101 . "Switching Protocols")
  201. (102 . "Processing")
  202. (200 . "OK")
  203. (201 . "Created")
  204. (202 . "Accepted")
  205. (203 . "Non-authoritative Information")
  206. (204 . "No Content")
  207. (205 . "Reset Content")
  208. (206 . "Partial Content")
  209. (207 . "Multi-Status")
  210. (208 . "Already Reported")
  211. (226 . "IM Used")
  212. (300 . "Multiple Choices")
  213. (301 . "Moved Permanently")
  214. (302 . "Found")
  215. (303 . "See Other")
  216. (304 . "Not Modified")
  217. (305 . "Use Proxy")
  218. (307 . "Temporary Redirect")
  219. (308 . "Permanent Redirect")
  220. (400 . "Bad Request")
  221. (401 . "Unauthorized")
  222. (402 . "Payment Required")
  223. (403 . "Forbidden")
  224. (404 . "Not Found")
  225. (405 . "Method Not Allowed")
  226. (406 . "Not Acceptable")
  227. (407 . "Proxy Authentication Required")
  228. (408 . "Request Timeout")
  229. (409 . "Conflict")
  230. (410 . "Gone")
  231. (411 . "Length Required")
  232. (412 . "Precondition Failed")
  233. (413 . "Payload Too Large")
  234. (414 . "Request-URI Too Long")
  235. (415 . "Unsupported Media Type")
  236. (416 . "Requested Range Not Satisfiable")
  237. (417 . "Expectation Failed")
  238. (418 . "I'm a teapot")
  239. (421 . "Misdirected Request")
  240. (422 . "Unprocessable Entity")
  241. (423 . "Locked")
  242. (424 . "Failed Dependency")
  243. (426 . "Upgrade Required")
  244. (428 . "Precondition Required")
  245. (429 . "Too Many Requests")
  246. (431 . "Request Header Fields Too Large")
  247. (444 . "Connection Closed Without Response")
  248. (451 . "Unavailable For Legal Reasons")
  249. (499 . "Client Closed Request")
  250. (500 . "Internal Server Error")
  251. (501 . "Not Implemented")
  252. (502 . "Bad Gateway")
  253. (503 . "Service Unavailable")
  254. (504 . "Gateway Timeout")
  255. (505 . "HTTP Version Not Supported")
  256. (506 . "Variant Also Negotiates")
  257. (507 . "Insufficient Storage")
  258. (508 . "Loop Detected")
  259. (510 . "Not Extended")
  260. (511 . "Network Authentication Required")
  261. (599 . "Network Connect Timeout Error"))
  262. "HTTP status codes.")
  263. (defvar httpd-html
  264. '((403 . "<!DOCTYPE html>
  265. <html><head>
  266. <title>403 Forbidden</title>
  267. </head><body>
  268. <h1>Forbidden</h1>
  269. <p>The requested URL is forbidden.</p>
  270. <pre>%s</pre>
  271. </body></html>")
  272. (404 . "<!DOCTYPE html>
  273. <html><head>
  274. <title>404 Not Found</title>
  275. </head><body>
  276. <h1>Not Found</h1>
  277. <p>The requested URL was not found on this server.</p>
  278. <pre>%s</pre>
  279. </body></html>")
  280. (500 . "<!DOCTYPE html>
  281. <html><head>
  282. <title>500 Internal Error</title>
  283. </head><body>
  284. <h1>500 Internal Error</h1>
  285. <p>Internal error when handling this request.</p>
  286. <pre>%s</pre>
  287. </body></html>"))
  288. "HTML for various errors.")
  289. ;; User interface
  290. ;;;###autoload
  291. (defun httpd-start ()
  292. "Start the web server process. If the server is already
  293. running, this will restart the server. There is only one server
  294. instance per Emacs instance."
  295. (interactive)
  296. (httpd-stop)
  297. (httpd-log `(start ,(current-time-string)))
  298. (make-network-process
  299. :name "httpd"
  300. :service httpd-port
  301. :server t
  302. :host httpd-host
  303. :family httpd-ip-family
  304. :filter 'httpd--filter
  305. :filter-multibyte nil
  306. :coding 'binary
  307. :log 'httpd--log)
  308. (run-hooks 'httpd-start-hook))
  309. ;;;###autoload
  310. (defun httpd-stop ()
  311. "Stop the web server if it is currently running, otherwise do nothing."
  312. (interactive)
  313. (when (process-status "httpd")
  314. (delete-process "httpd")
  315. (httpd-log `(stop ,(current-time-string)))
  316. (run-hooks 'httpd-stop-hook)))
  317. ;;;###autoload
  318. (defun httpd-running-p ()
  319. "Return non-nil if the simple-httpd server is running."
  320. (not (null (process-status "httpd"))))
  321. ;;;###autoload
  322. (defun httpd-serve-directory (directory)
  323. "Start the web server with given `directory' as `httpd-root'."
  324. (interactive "DServe directory: \n")
  325. (setf httpd-root directory)
  326. (httpd-start)
  327. (message "Started simple-httpd on %s:%d, serving: %s"
  328. (cl-case httpd-host
  329. ((nil) "0.0.0.0")
  330. ((local) "localhost")
  331. (otherwise httpd-host)) httpd-port directory))
  332. (defun httpd-batch-start ()
  333. "Never returns, holding the server open indefinitely for batch mode.
  334. Logs are redirected to stdout. To use, invoke Emacs like this:
  335. emacs -Q -batch -l simple-httpd.elc -f httpd-batch-start"
  336. (if (not noninteractive)
  337. (error "Only use `httpd-batch-start' in batch mode!")
  338. (httpd-start)
  339. (defalias 'httpd-log 'pp)
  340. (while t (sleep-for 60))))
  341. ;; Utility
  342. (defun httpd-date-string (&optional date)
  343. "Return an HTTP date string (RFC 1123)."
  344. (format-time-string "%a, %e %b %Y %T GMT" date t))
  345. (defun httpd-etag (file)
  346. "Compute the ETag for FILE."
  347. (concat "\"" (substring (sha1 (prin1-to-string (file-attributes file))) -16)
  348. "\""))
  349. (defun httpd--stringify (designator)
  350. "Turn a string designator into a string."
  351. (let ((string (format "%s" designator)))
  352. (if (keywordp designator)
  353. (substring string 1)
  354. string)))
  355. ;; Networking code
  356. (defun httpd--connection-close-p (request)
  357. "Return non-nil if the client requested \"connection: close\"."
  358. (or (equal '("close") (cdr (assoc "Connection" request)))
  359. (equal '("HTTP/1.0") (cddr (assoc "GET" request)))))
  360. (defun httpd--filter (proc chunk)
  361. "Runs each time client makes a request."
  362. (with-current-buffer (process-get proc :request-buffer)
  363. (setf (point) (point-max))
  364. (insert chunk)
  365. (let ((request (process-get proc :request)))
  366. (unless request
  367. (when (setf request (httpd-parse))
  368. (delete-region (point-min) (point))
  369. (process-put proc :request request)))
  370. (when request
  371. (let ((content-length (cadr (assoc "Content-Length" request))))
  372. (when (or (null content-length)
  373. (= (buffer-size) (string-to-number content-length)))
  374. (let* ((content (buffer-string))
  375. (uri (cl-cadar request))
  376. (parsed-uri (httpd-parse-uri (concat uri)))
  377. (uri-path (nth 0 parsed-uri))
  378. (uri-query (append (nth 1 parsed-uri)
  379. (httpd-parse-args content)))
  380. (servlet (httpd-get-servlet uri-path)))
  381. (erase-buffer)
  382. (process-put proc :request nil)
  383. (setf request (nreverse (cons (list "Content" content)
  384. (nreverse request))))
  385. (httpd-log `(request (date ,(httpd-date-string))
  386. (address ,(car (process-contact proc)))
  387. (get ,uri-path)
  388. ,(cons 'headers request)))
  389. (if (null servlet)
  390. (httpd--error-safe proc 404)
  391. (condition-case error-case
  392. (funcall servlet proc uri-path uri-query request)
  393. (error (httpd--error-safe proc 500 error-case))))
  394. (when (httpd--connection-close-p request)
  395. (process-send-eof proc)))))))))
  396. (defun httpd--log (server proc message)
  397. "Runs each time a new client connects."
  398. (with-current-buffer (generate-new-buffer " *httpd-client*")
  399. (set-buffer-multibyte nil)
  400. (process-put proc :request-buffer (current-buffer)))
  401. (set-process-sentinel proc #'httpd--sentinel)
  402. (httpd-log (list 'connection (car (process-contact proc)))))
  403. (defun httpd--sentinel (proc message)
  404. "Runs when a client closes the connection."
  405. (unless (string-match-p "^open " message)
  406. (let ((buffer (process-get proc :request-buffer)))
  407. (when buffer
  408. (kill-buffer buffer)))))
  409. ;; Logging
  410. (defun httpd-log (item)
  411. "Pretty print a lisp object to the log."
  412. (with-current-buffer (get-buffer-create "*httpd*")
  413. (setf buffer-read-only nil)
  414. (let ((follow (= (point) (point-max))))
  415. (save-excursion
  416. (goto-char (point-max))
  417. (pp item (current-buffer)))
  418. (if follow (goto-char (point-max))))
  419. (setf truncate-lines t
  420. buffer-read-only t)
  421. (set-buffer-modified-p nil)))
  422. ;; Servlets
  423. (defvar httpd-current-proc nil
  424. "The process object currently in use.")
  425. (defvar httpd--header-sent nil
  426. "Buffer-local variable indicating if the header has been sent.")
  427. (make-variable-buffer-local 'httpd--header-sent)
  428. (defun httpd-resolve-proc (proc)
  429. "Return the correct process to use. This handles `httpd-current-proc'."
  430. (if (eq t proc) httpd-current-proc proc))
  431. (defmacro with-httpd-buffer (proc mime &rest body)
  432. "Create a temporary buffer, set it as the current buffer, and,
  433. at the end of body, automatically serve it to an HTTP client with
  434. an HTTP header indicating the specified MIME type. Additionally,
  435. `standard-output' is set to this output buffer and
  436. `httpd-current-proc' is set to PROC."
  437. (declare (indent defun))
  438. (let ((proc-sym (make-symbol "--proc--")))
  439. `(let ((,proc-sym ,proc))
  440. (with-temp-buffer
  441. (setf major-mode 'httpd-buffer)
  442. (let ((standard-output (current-buffer))
  443. (httpd-current-proc ,proc-sym))
  444. ,@body)
  445. (unless httpd--header-sent
  446. (httpd-send-header ,proc-sym ,mime 200))))))
  447. (defun httpd-discard-buffer ()
  448. "Don't respond using current server buffer (`with-httpd-buffer').
  449. Returns a process for future response."
  450. (when (eq major-mode 'httpd-buffer) (setf httpd--header-sent t))
  451. httpd-current-proc)
  452. (defmacro defservlet (name mime path-query-request &rest body)
  453. "Defines a simple httpd servelet. The servlet runs in a
  454. temporary buffer which is automatically served to the client
  455. along with a header.
  456. A servlet that serves the contents of *scratch*,
  457. (defservlet scratch text/plain ()
  458. (insert-buffer-substring (get-buffer-create \"*scratch*\")))
  459. A servlet that says hello,
  460. (defservlet hello-world text/plain (path)
  461. (insert \"hello, \" (file-name-nondirectory path))))"
  462. (declare (indent defun))
  463. (let ((proc-sym (make-symbol "proc"))
  464. (fname (intern (concat "httpd/" (symbol-name name)))))
  465. `(defun ,fname (,proc-sym ,@path-query-request &rest ,(cl-gensym))
  466. (with-httpd-buffer ,proc-sym ,(httpd--stringify mime)
  467. ,@body))))
  468. (defun httpd-parse-endpoint (symbol)
  469. "Parse an endpoint definition template for use with `defservlet*'."
  470. (cl-loop for item in (split-string (symbol-name symbol) "/")
  471. for n upfrom 0
  472. when (and (> (length item) 0) (eql (aref item 0) ?:))
  473. collect (cons (intern (substring item 1)) n) into vars
  474. else collect item into path
  475. finally
  476. (cl-return
  477. (cl-values (intern (mapconcat #'identity path "/")) vars))))
  478. (defvar httpd-path nil
  479. "Anaphoric variable for `defservlet*'.")
  480. (defvar httpd-query nil
  481. "Anaphoric variable for `defservlet*'.")
  482. (defvar httpd-request nil
  483. "Anaphoric variable for `defservlet*'.")
  484. (defvar httpd-split-path nil
  485. "Anaphoric variable for `defservlet*'.")
  486. (defmacro defservlet* (endpoint mime args &rest body)
  487. "Like `defservlet', but automatically bind variables/arguments
  488. to the request. Trailing components of the ENDPOINT can be bound
  489. by prefixing these components with a colon, acting like a template.
  490. (defservlet* packages/:package/:version text/plain (verbose)
  491. (insert (format \"%s\\n%s\\n\" package version))
  492. (princ (get-description package version))
  493. (when verbose
  494. (insert (format \"%S\" (get-dependencies package version)))))
  495. When accessed from this URL,
  496. http://example.com/packages/foobar/1.0?verbose=1
  497. the variables package, version, and verbose will be bound to the
  498. associated components of the URL. Components not provided are
  499. bound to nil. The query arguments can use the Common Lisp &key
  500. form (variable default provided-p).
  501. (defservlet* greeting/:name text/plain ((greeting \"hi\" greeting-p))
  502. (princ (format \"%s, %s (provided: %s)\" greeting name greeting-p)))
  503. The original path, query, and request can be accessed by the
  504. anaphoric special variables `httpd-path', `httpd-query', and
  505. `httpd-request'."
  506. (declare (indent defun))
  507. (let ((path-lexical (cl-gensym))
  508. (query-lexical (cl-gensym))
  509. (request-lexical (cl-gensym)))
  510. (cl-multiple-value-bind (path vars) (httpd-parse-endpoint endpoint)
  511. `(defservlet ,path ,mime (,path-lexical ,query-lexical ,request-lexical)
  512. (let ((httpd-path ,path-lexical)
  513. (httpd-query ,query-lexical)
  514. (httpd-request ,request-lexical)
  515. (httpd-split-path (split-string
  516. (substring ,path-lexical 1) "/")))
  517. (let ,(cl-loop for (var . pos) in vars
  518. for extract =
  519. `(httpd-unhex (nth ,pos httpd-split-path))
  520. collect (list var extract))
  521. (let ,(cl-loop for arg in args
  522. for has-default = (listp arg)
  523. for has-default-p = (and has-default
  524. (= 3 (length arg)))
  525. for arg-name = (symbol-name
  526. (if has-default (cl-first arg) arg))
  527. when has-default collect
  528. (list (cl-first arg)
  529. `(let ((value (assoc ,arg-name httpd-query)))
  530. (if value
  531. (cl-second value)
  532. ,(cl-second arg))))
  533. else collect
  534. (list arg `(cl-second
  535. (assoc ,arg-name httpd-query)))
  536. when has-default-p collect
  537. (list (cl-third arg)
  538. `(not (null (assoc ,arg-name httpd-query)))))
  539. ,@body)))))))
  540. (font-lock-add-keywords
  541. 'emacs-lisp-mode
  542. '(("(\\<\\(defservlet\\*?\\)\\> +\\([^ ()]+\\) +\\([^ ()]+\\)"
  543. (1 'font-lock-keyword-face)
  544. (2 'font-lock-function-name-face)
  545. (3 'font-lock-type-face))))
  546. (defmacro httpd-def-file-servlet (name root)
  547. "Defines a servlet that serves files from ROOT under the route NAME.
  548. (httpd-def-file-servlet my/www \"/var/www/\")
  549. Automatically handles redirects and uses `httpd-serve-root' to
  550. actually serve up files."
  551. (let* ((short-root (directory-file-name (symbol-name name)))
  552. (path-root (concat short-root "/"))
  553. (chop (length path-root)))
  554. `(defservlet ,name nil (uri-path query request)
  555. (setf httpd--header-sent t) ; Don't actually use this temp buffer
  556. (if (= (length uri-path) ,chop)
  557. (httpd-redirect t ,path-root)
  558. (let ((path (substring uri-path ,chop)))
  559. (httpd-serve-root t ,root path request))))))
  560. ;; Request parsing
  561. (defun httpd--normalize-header (header)
  562. "Destructively capitalize the components of HEADER."
  563. (mapconcat #'capitalize (split-string header "-") "-"))
  564. (defun httpd-parse ()
  565. "Parse HTTP header in current buffer into association list.
  566. Leaves the point at the start of the request content. Returns nil
  567. if it failed to parse a complete HTTP header."
  568. (setf (point) (point-min))
  569. (when (looking-at "\\([^ ]+\\) +\\([^ ]+\\) +\\([^\r]+\\)\r\n")
  570. (let ((method (match-string 1))
  571. (path (decode-coding-string (match-string 2) 'iso-8859-1))
  572. (version (match-string 3))
  573. (headers ()))
  574. (setf (point) (match-end 0))
  575. (while (looking-at "\\([-!#-'*+.0-9A-Z^_`a-z|~]+\\): *\\([^\r]+\\)\r\n")
  576. (setf (point) (match-end 0))
  577. (let ((name (match-string 1))
  578. (value (match-string 2)))
  579. (push (list (httpd--normalize-header name)
  580. (decode-coding-string value 'iso-8859-1)) headers)))
  581. (when (looking-at "\r\n")
  582. (setf (point) (match-end 0))
  583. (cons (list method path version) (nreverse headers))))))
  584. (defun httpd-unhex (str)
  585. "Fully decode the URL encoding in STR (including +'s)."
  586. (when str
  587. (let ((nonplussed (replace-regexp-in-string (regexp-quote "+") " " str)))
  588. (decode-coding-string (url-unhex-string nonplussed t) 'utf-8))))
  589. (defun httpd-parse-args (argstr)
  590. "Parse a string containing URL encoded arguments."
  591. (unless (zerop (length argstr))
  592. (mapcar (lambda (str)
  593. (mapcar 'httpd-unhex (split-string str "=")))
  594. (split-string argstr "&"))))
  595. (defun httpd-parse-uri (uri)
  596. "Split a URI into its components.
  597. The first element of the return value is the script path, the
  598. second element is an alist of variable/value pairs, and the third
  599. element is the fragment."
  600. (let ((p1 (string-match (regexp-quote "?") uri))
  601. (p2 (string-match (regexp-quote "#") uri))
  602. retval)
  603. (push (if p2 (httpd-unhex (substring uri (1+ p2)))) retval)
  604. (push (if p1 (httpd-parse-args (substring uri (1+ p1) p2))) retval)
  605. (push (substring uri 0 (or p1 p2)) retval)))
  606. ;; Path handling
  607. (defun httpd-status (path)
  608. "Determine status code for PATH."
  609. (cond
  610. ((not (file-exists-p path)) 404)
  611. ((not (file-readable-p path)) 403)
  612. ((and (file-directory-p path) (not httpd-listings)) 403)
  613. (200)))
  614. (defun httpd-clean-path (path)
  615. "Clean dangerous .. from PATH and remove the leading slash."
  616. (let* ((sep (if (member system-type '(windows-nt ms-dos)) "[/\\]" "/"))
  617. (split (delete ".." (split-string path sep)))
  618. (unsplit (mapconcat 'identity (delete "" split) "/")))
  619. (concat "./" unsplit)))
  620. (defun httpd-gen-path (path &optional root)
  621. "Translate GET to secure path in ROOT (`httpd-root')."
  622. (let ((clean (expand-file-name (httpd-clean-path path) (or root httpd-root))))
  623. (if (file-directory-p clean)
  624. (let* ((dir (file-name-as-directory clean))
  625. (indexes (cl-mapcar (apply-partially 'concat dir) httpd-indexes))
  626. (existing (cl-remove-if-not 'file-exists-p indexes)))
  627. (or (car existing) dir))
  628. clean)))
  629. (defun httpd-get-servlet (uri-path)
  630. "Determine the servlet to be executed for URI-PATH."
  631. (if (not httpd-servlets)
  632. 'httpd/
  633. (cl-labels ((cat (x)
  634. (concat "httpd/" (mapconcat 'identity (reverse x) "/"))))
  635. (let ((parts (cdr (split-string (directory-file-name uri-path) "/"))))
  636. (or
  637. (cl-find-if 'fboundp (mapcar 'intern-soft
  638. (cl-maplist #'cat (reverse parts))))
  639. 'httpd/)))))
  640. (defun httpd-serve-root (proc root uri-path &optional request)
  641. "Securely serve a file from ROOT from under PATH."
  642. (let* ((path (httpd-gen-path uri-path root))
  643. (status (httpd-status path)))
  644. (cond
  645. ((not (= status 200)) (httpd-error proc status))
  646. ((file-directory-p path) (httpd-send-directory proc path uri-path))
  647. (t (httpd-send-file proc path request)))))
  648. (defun httpd/ (proc uri-path query request)
  649. "Default root servlet which serves files when httpd-serve-files is T."
  650. (if (and httpd-serve-files httpd-root)
  651. (httpd-serve-root proc httpd-root uri-path request)
  652. (httpd-error proc 403)))
  653. (defun httpd-get-mime (ext)
  654. "Fetch MIME type given the file extention."
  655. (or (and ext (cdr (assoc (downcase ext) httpd-mime-types)))
  656. "application/octet-stream"))
  657. ;; Data sending functions
  658. (defun httpd-send-header (proc mime status &rest header-keys)
  659. "Send an HTTP header with given MIME type and STATUS, followed
  660. by the current buffer. If PROC is T use the `httpd-current-proc'
  661. as the process.
  662. Extra headers can be sent by supplying them like keywords, i.e.
  663. (httpd-send-header t \"text/plain\" 200 :X-Powered-By \"simple-httpd\")"
  664. (let ((status-str (cdr (assq status httpd-status-codes)))
  665. (headers `(("Server" . ,httpd-server-name)
  666. ("Date" . ,(httpd-date-string))
  667. ("Connection" . "keep-alive")
  668. ("Content-Type" . ,(httpd--stringify mime))
  669. ("Content-Length" . ,(httpd--buffer-size)))))
  670. (unless httpd--header-sent
  671. (setf httpd--header-sent t)
  672. (with-temp-buffer
  673. (insert (format "HTTP/1.1 %d %s\r\n" status status-str))
  674. (cl-loop for (header value) on header-keys by #'cddr
  675. for header-name = (substring (symbol-name header) 1)
  676. for value-name = (format "%s" value)
  677. collect (cons header-name value-name) into extras
  678. finally (setf headers (nconc headers extras)))
  679. (dolist (header headers)
  680. (insert (format "%s: %s\r\n" (car header) (cdr header))))
  681. (insert "\r\n")
  682. (process-send-region (httpd-resolve-proc proc)
  683. (point-min) (point-max)))
  684. (process-send-region (httpd-resolve-proc proc)
  685. (point-min) (point-max)))))
  686. (defun httpd-redirect (proc path &optional code)
  687. "Redirect the client to PATH (default 301). If PROC is T use
  688. the `httpd-current-proc' as the process."
  689. (httpd-log (list 'redirect path))
  690. (httpd-discard-buffer)
  691. (with-temp-buffer
  692. (httpd-send-header proc "text/plain" (or code 301) :Location path)))
  693. (defun httpd-send-file (proc path &optional req)
  694. "Serve file to the given client. If PROC is T use the
  695. `httpd-current-proc' as the process."
  696. (httpd-discard-buffer)
  697. (let ((req-etag (cadr (assoc "If-None-Match" req)))
  698. (etag (httpd-etag path))
  699. (mtime (httpd-date-string (nth 4 (file-attributes path)))))
  700. (if (equal req-etag etag)
  701. (with-temp-buffer
  702. (httpd-log `(file ,path not-modified))
  703. (httpd-send-header proc "text/plain" 304))
  704. (httpd-log `(file ,path))
  705. (with-temp-buffer
  706. (set-buffer-multibyte nil)
  707. (insert-file-contents path)
  708. (httpd-send-header proc (httpd-get-mime (file-name-extension path))
  709. 200 :Last-Modified mtime :ETag etag)))))
  710. (defun httpd-send-directory (proc path uri-path)
  711. "Serve a file listing to the client. If PROC is T use the
  712. `httpd-current-proc' as the process."
  713. (httpd-discard-buffer)
  714. (let ((title (concat "Directory listing for "
  715. (url-insert-entities-in-string uri-path))))
  716. (if (equal "/" (substring uri-path -1))
  717. (with-temp-buffer
  718. (httpd-log `(directory ,path))
  719. (set-buffer-multibyte nil)
  720. (insert "<!DOCTYPE html>\n")
  721. (insert "<html>\n<head><title>" title "</title></head>\n")
  722. (insert "<body>\n<h2>" title "</h2>\n<hr/>\n<ul>")
  723. (dolist (file (directory-files path))
  724. (unless (eq ?. (aref file 0))
  725. (let* ((full (expand-file-name file path))
  726. (tail (if (file-directory-p full) "/" ""))
  727. (f (url-insert-entities-in-string file))
  728. (l (url-hexify-string file)))
  729. (insert (format "<li><a href=\"%s%s\">%s%s</a></li>\n"
  730. l tail f tail)))))
  731. (insert "</ul>\n<hr/>\n</body>\n</html>")
  732. (httpd-send-header proc "text/html" 200))
  733. (httpd-redirect proc (concat uri-path "/")))))
  734. (defun httpd--buffer-size (&optional buffer)
  735. "Get the buffer size in bytes."
  736. (let ((orig enable-multibyte-characters)
  737. (size 0))
  738. (with-current-buffer (or buffer (current-buffer))
  739. (set-buffer-multibyte nil)
  740. (setf size (buffer-size))
  741. (if orig (set-buffer-multibyte orig)))
  742. size))
  743. (defun httpd-error (proc status &optional info)
  744. "Send an error page appropriate for STATUS to the client,
  745. optionally inserting object INFO into page. If PROC is T use the
  746. `httpd-current-proc' as the process."
  747. (httpd-discard-buffer)
  748. (httpd-log `(error ,status ,info))
  749. (with-temp-buffer
  750. (let ((html (or (cdr (assq status httpd-html)) ""))
  751. (erro (url-insert-entities-in-string (format "error: %s" info))))
  752. (insert (format html (if info erro ""))))
  753. (httpd-send-header proc "text/html" status)))
  754. (defun httpd--error-safe (&rest args)
  755. "Call httpd-error and report failures to *httpd*."
  756. (condition-case error-case
  757. (apply #'httpd-error args)
  758. (error (httpd-log `(hard-error ,error-case)))))
  759. (provide 'simple-httpd)
  760. ;;; simple-httpd.el ends here