url-util.el 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. ;;; url-util.el --- Miscellaneous helper routines for URL library
  2. ;; Copyright (C) 1996-1999, 2001, 2004-2012 Free Software Foundation, Inc.
  3. ;; Author: Bill Perry <wmperry@gnu.org>
  4. ;; Keywords: comm, data, processes
  5. ;; This file is part of GNU Emacs.
  6. ;;
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;;; Code:
  19. (require 'url-parse)
  20. (require 'url-vars)
  21. (eval-when-compile (require 'cl))
  22. (autoload 'timezone-parse-date "timezone")
  23. (autoload 'timezone-make-date-arpa-standard "timezone")
  24. (autoload 'mail-header-extract "mailheader")
  25. (defvar url-parse-args-syntax-table
  26. (copy-syntax-table emacs-lisp-mode-syntax-table)
  27. "A syntax table for parsing sgml attributes.")
  28. (modify-syntax-entry ?' "\"" url-parse-args-syntax-table)
  29. (modify-syntax-entry ?` "\"" url-parse-args-syntax-table)
  30. (modify-syntax-entry ?{ "(" url-parse-args-syntax-table)
  31. (modify-syntax-entry ?} ")" url-parse-args-syntax-table)
  32. ;;;###autoload
  33. (defcustom url-debug nil
  34. "What types of debug messages from the URL library to show.
  35. Debug messages are logged to the *URL-DEBUG* buffer.
  36. If t, all messages will be logged.
  37. If a number, all messages will be logged, as well shown via `message'.
  38. If a list, it is a list of the types of messages to be logged."
  39. :type '(choice (const :tag "none" nil)
  40. (const :tag "all" t)
  41. (checklist :tag "custom"
  42. (const :tag "HTTP" :value http)
  43. (const :tag "DAV" :value dav)
  44. (const :tag "General" :value retrieval)
  45. (const :tag "Filename handlers" :value handlers)
  46. (symbol :tag "Other")))
  47. :group 'url-hairy)
  48. ;;;###autoload
  49. (defun url-debug (tag &rest args)
  50. (if quit-flag
  51. (error "Interrupted!"))
  52. (if (or (eq url-debug t)
  53. (numberp url-debug)
  54. (and (listp url-debug) (memq tag url-debug)))
  55. (with-current-buffer (get-buffer-create "*URL-DEBUG*")
  56. (goto-char (point-max))
  57. (insert (symbol-name tag) " -> " (apply 'format args) "\n")
  58. (if (numberp url-debug)
  59. (apply 'message args)))))
  60. ;;;###autoload
  61. (defun url-parse-args (str &optional nodowncase)
  62. ;; Return an assoc list of attribute/value pairs from an RFC822-type string
  63. (let (
  64. name ; From name=
  65. value ; its value
  66. results ; Assoc list of results
  67. name-pos ; Start of XXXX= position
  68. val-pos ; Start of value position
  69. st
  70. nd
  71. )
  72. (save-excursion
  73. (save-restriction
  74. (set-buffer (get-buffer-create " *urlparse-temp*"))
  75. (set-syntax-table url-parse-args-syntax-table)
  76. (erase-buffer)
  77. (insert str)
  78. (setq st (point-min)
  79. nd (point-max))
  80. (set-syntax-table url-parse-args-syntax-table)
  81. (narrow-to-region st nd)
  82. (goto-char (point-min))
  83. (while (not (eobp))
  84. (skip-chars-forward "; \n\t")
  85. (setq name-pos (point))
  86. (skip-chars-forward "^ \n\t=;")
  87. (if (not nodowncase)
  88. (downcase-region name-pos (point)))
  89. (setq name (buffer-substring name-pos (point)))
  90. (skip-chars-forward " \t\n")
  91. (if (/= (or (char-after (point)) 0) ?=) ; There is no value
  92. (setq value nil)
  93. (skip-chars-forward " \t\n=")
  94. (setq val-pos (point)
  95. value
  96. (cond
  97. ((or (= (or (char-after val-pos) 0) ?\")
  98. (= (or (char-after val-pos) 0) ?'))
  99. (buffer-substring (1+ val-pos)
  100. (condition-case ()
  101. (prog2
  102. (forward-sexp 1)
  103. (1- (point))
  104. (skip-chars-forward "\""))
  105. (error
  106. (skip-chars-forward "^ \t\n")
  107. (point)))))
  108. (t
  109. (buffer-substring val-pos
  110. (progn
  111. (skip-chars-forward "^;")
  112. (skip-chars-backward " \t")
  113. (point)))))))
  114. (setq results (cons (cons name value) results))
  115. (skip-chars-forward "; \n\t"))
  116. results))))
  117. ;;;###autoload
  118. (defun url-insert-entities-in-string (string)
  119. "Convert HTML markup-start characters to entity references in STRING.
  120. Also replaces the \" character, so that the result may be safely used as
  121. an attribute value in a tag. Returns a new string with the result of the
  122. conversion. Replaces these characters as follows:
  123. & ==> &amp;
  124. < ==> &lt;
  125. > ==> &gt;
  126. \" ==> &quot;"
  127. (if (string-match "[&<>\"]" string)
  128. (with-current-buffer (get-buffer-create " *entity*")
  129. (erase-buffer)
  130. (buffer-disable-undo (current-buffer))
  131. (insert string)
  132. (goto-char (point-min))
  133. (while (progn
  134. (skip-chars-forward "^&<>\"")
  135. (not (eobp)))
  136. (insert (cdr (assq (char-after (point))
  137. '((?\" . "&quot;")
  138. (?& . "&amp;")
  139. (?< . "&lt;")
  140. (?> . "&gt;")))))
  141. (delete-char 1))
  142. (buffer-string))
  143. string))
  144. ;;;###autoload
  145. (defun url-normalize-url (url)
  146. "Return a 'normalized' version of URL.
  147. Strips out default port numbers, etc."
  148. (let (type data retval)
  149. (setq data (url-generic-parse-url url)
  150. type (url-type data))
  151. (if (member type '("www" "about" "mailto" "info"))
  152. (setq retval url)
  153. ;; FIXME all this does, and all this function seems to do in
  154. ;; most cases, is remove any trailing "#anchor" part of a url.
  155. (setf (url-target data) nil)
  156. (setq retval (url-recreate-url data)))
  157. retval))
  158. ;;;###autoload
  159. (defun url-lazy-message (&rest args)
  160. "Just like `message', but is a no-op if called more than once a second.
  161. Will not do anything if `url-show-status' is nil."
  162. (if (or (and url-current-object
  163. (url-silent url-current-object))
  164. (null url-show-status)
  165. (active-minibuffer-window)
  166. (= url-lazy-message-time
  167. (setq url-lazy-message-time (nth 1 (current-time)))))
  168. nil
  169. (apply 'message args)))
  170. ;;;###autoload
  171. (defun url-get-normalized-date (&optional specified-time)
  172. "Return a 'real' date string that most HTTP servers can understand."
  173. (let ((system-time-locale "C"))
  174. (format-time-string "%a, %d %b %Y %T GMT"
  175. (or specified-time (current-time)) t)))
  176. ;;;###autoload
  177. (defun url-eat-trailing-space (x)
  178. "Remove spaces/tabs at the end of a string."
  179. (let ((y (1- (length x)))
  180. (skip-chars (list ? ?\t ?\n)))
  181. (while (and (>= y 0) (memq (aref x y) skip-chars))
  182. (setq y (1- y)))
  183. (substring x 0 (1+ y))))
  184. ;;;###autoload
  185. (defun url-strip-leading-spaces (x)
  186. "Remove spaces at the front of a string."
  187. (let ((y (1- (length x)))
  188. (z 0)
  189. (skip-chars (list ? ?\t ?\n)))
  190. (while (and (<= z y) (memq (aref x z) skip-chars))
  191. (setq z (1+ z)))
  192. (substring x z nil)))
  193. ;;;###autoload
  194. (defun url-pretty-length (n)
  195. (cond
  196. ((< n 1024)
  197. (format "%d bytes" n))
  198. ((< n (* 1024 1024))
  199. (format "%dk" (/ n 1024.0)))
  200. (t
  201. (format "%2.2fM" (/ n (* 1024 1024.0))))))
  202. ;;;###autoload
  203. (defun url-display-percentage (fmt perc &rest args)
  204. (when (and url-show-status
  205. (or (null url-current-object)
  206. (not (url-silent url-current-object))))
  207. (if (null fmt)
  208. (if (fboundp 'clear-progress-display)
  209. (clear-progress-display))
  210. (if (and (fboundp 'progress-display) perc)
  211. (apply 'progress-display fmt perc args)
  212. (apply 'message fmt args)))))
  213. ;;;###autoload
  214. (defun url-percentage (x y)
  215. (if (fboundp 'float)
  216. (round (* 100 (/ x (float y))))
  217. (/ (* x 100) y)))
  218. ;;;###autoload
  219. (defalias 'url-basepath 'url-file-directory)
  220. ;;;###autoload
  221. (defun url-file-directory (file)
  222. "Return the directory part of FILE, for a URL."
  223. (cond
  224. ((null file) "")
  225. ((string-match "\\?" file)
  226. (file-name-directory (substring file 0 (match-beginning 0))))
  227. (t (file-name-directory file))))
  228. ;;;###autoload
  229. (defun url-file-nondirectory (file)
  230. "Return the nondirectory part of FILE, for a URL."
  231. (cond
  232. ((null file) "")
  233. ((string-match "\\?" file)
  234. (file-name-nondirectory (substring file 0 (match-beginning 0))))
  235. (t (file-name-nondirectory file))))
  236. ;;;###autoload
  237. (defun url-parse-query-string (query &optional downcase allow-newlines)
  238. (let (retval pairs cur key val)
  239. (setq pairs (split-string query "&"))
  240. (while pairs
  241. (setq cur (car pairs)
  242. pairs (cdr pairs))
  243. (if (not (string-match "=" cur))
  244. nil ; Grace
  245. (setq key (url-unhex-string (substring cur 0 (match-beginning 0))
  246. allow-newlines))
  247. (setq val (url-unhex-string (substring cur (match-end 0) nil)
  248. allow-newlines))
  249. (if downcase
  250. (setq key (downcase key)))
  251. (setq cur (assoc key retval))
  252. (if cur
  253. (setcdr cur (cons val (cdr cur)))
  254. (setq retval (cons (list key val) retval)))))
  255. retval))
  256. (defun url-unhex (x)
  257. (if (> x ?9)
  258. (if (>= x ?a)
  259. (+ 10 (- x ?a))
  260. (+ 10 (- x ?A)))
  261. (- x ?0)))
  262. ;; Fixme: Is this definition better, and does it ever matter?
  263. ;; (defun url-unhex-string (str &optional allow-newlines)
  264. ;; "Remove %XX, embedded spaces, etc in a url.
  265. ;; If optional second argument ALLOW-NEWLINES is non-nil, then allow the
  266. ;; decoding of carriage returns and line feeds in the string, which is normally
  267. ;; forbidden in URL encoding."
  268. ;; (setq str (or str ""))
  269. ;; (setq str (replace-regexp-in-string "%[[:xdigit:]]\\{2\\}"
  270. ;; (lambda (match)
  271. ;; (string (string-to-number
  272. ;; (substring match 1) 16)))
  273. ;; str t t))
  274. ;; (if allow-newlines
  275. ;; (replace-regexp-in-string "[\n\r]" (lambda (match)
  276. ;; (format "%%%.2X" (aref match 0)))
  277. ;; str t t)
  278. ;; str))
  279. ;;;###autoload
  280. (defun url-unhex-string (str &optional allow-newlines)
  281. "Remove %XX embedded spaces, etc in a URL.
  282. If optional second argument ALLOW-NEWLINES is non-nil, then allow the
  283. decoding of carriage returns and line feeds in the string, which is normally
  284. forbidden in URL encoding."
  285. (setq str (or str ""))
  286. (let ((tmp "")
  287. (case-fold-search t))
  288. (while (string-match "%[0-9a-f][0-9a-f]" str)
  289. (let* ((start (match-beginning 0))
  290. (ch1 (url-unhex (elt str (+ start 1))))
  291. (code (+ (* 16 ch1)
  292. (url-unhex (elt str (+ start 2))))))
  293. (setq tmp (concat
  294. tmp (substring str 0 start)
  295. (cond
  296. (allow-newlines
  297. (byte-to-string code))
  298. ((or (= code ?\n) (= code ?\r))
  299. " ")
  300. (t (byte-to-string code))))
  301. str (substring str (match-end 0)))))
  302. (setq tmp (concat tmp str))
  303. tmp))
  304. (defconst url-unreserved-chars
  305. '(
  306. ?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z
  307. ?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z
  308. ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
  309. ?- ?_ ?. ?! ?~ ?* ?' ?\( ?\))
  310. "A list of characters that are _NOT_ reserved in the URL spec.
  311. This is taken from RFC 2396.")
  312. ;;;###autoload
  313. (defun url-hexify-string (string)
  314. "Return a new string that is STRING URI-encoded.
  315. First, STRING is converted to utf-8, if necessary. Then, for each
  316. character in the utf-8 string, those found in `url-unreserved-chars'
  317. are left as-is, all others are represented as a three-character
  318. string: \"%\" followed by two lowercase hex digits."
  319. ;; To go faster and avoid a lot of consing, we could do:
  320. ;;
  321. ;; (defconst url-hexify-table
  322. ;; (let ((map (make-vector 256 nil)))
  323. ;; (dotimes (byte 256) (aset map byte
  324. ;; (if (memq byte url-unreserved-chars)
  325. ;; (char-to-string byte)
  326. ;; (format "%%%02x" byte))))
  327. ;; map))
  328. ;;
  329. ;; (mapconcat (curry 'aref url-hexify-table) ...)
  330. (mapconcat (lambda (byte)
  331. (if (memq byte url-unreserved-chars)
  332. (char-to-string byte)
  333. (format "%%%02x" byte)))
  334. (if (multibyte-string-p string)
  335. (encode-coding-string string 'utf-8)
  336. string)
  337. ""))
  338. ;;;###autoload
  339. (defun url-file-extension (fname &optional x)
  340. "Return the filename extension of FNAME.
  341. If optional argument X is t, then return the basename
  342. of the file with the extension stripped off."
  343. (if (and fname
  344. (setq fname (url-file-nondirectory fname))
  345. (string-match "\\.[^./]+$" fname))
  346. (if x (substring fname 0 (match-beginning 0))
  347. (substring fname (match-beginning 0) nil))
  348. ;;
  349. ;; If fname has no extension, and x then return fname itself instead of
  350. ;; nothing. When caching it allows the correct .hdr file to be produced
  351. ;; for filenames without extension.
  352. ;;
  353. (if x
  354. fname
  355. "")))
  356. ;;;###autoload
  357. (defun url-truncate-url-for-viewing (url &optional width)
  358. "Return a shortened version of URL that is WIDTH characters wide or less.
  359. WIDTH defaults to the current frame width."
  360. (let* ((fr-width (or width (frame-width)))
  361. (str-width (length url))
  362. (fname nil)
  363. (modified 0)
  364. (urlobj nil))
  365. ;; The first thing that can go are the search strings
  366. (if (and (>= str-width fr-width)
  367. (string-match "?" url))
  368. (setq url (concat (substring url 0 (match-beginning 0)) "?...")
  369. str-width (length url)))
  370. (if (< str-width fr-width)
  371. nil ; Hey, we are done!
  372. (setq urlobj (url-generic-parse-url url)
  373. fname (url-filename urlobj)
  374. fr-width (- fr-width 4))
  375. (while (and (>= str-width fr-width)
  376. (string-match "/" fname))
  377. (setq fname (substring fname (match-end 0) nil)
  378. modified (1+ modified))
  379. (setf (url-filename urlobj) fname)
  380. (setq url (url-recreate-url urlobj)
  381. str-width (length url)))
  382. (if (> modified 1)
  383. (setq fname (concat "/.../" fname))
  384. (setq fname (concat "/" fname)))
  385. (setf (url-filename urlobj) fname)
  386. (setq url (url-recreate-url urlobj)))
  387. url))
  388. ;;;###autoload
  389. (defun url-view-url (&optional no-show)
  390. "View the current document's URL.
  391. Optional argument NO-SHOW means just return the URL, don't show it in
  392. the minibuffer.
  393. This uses `url-current-object', set locally to the buffer."
  394. (interactive)
  395. (if (not url-current-object)
  396. nil
  397. (if no-show
  398. (url-recreate-url url-current-object)
  399. (message "%s" (url-recreate-url url-current-object)))))
  400. (defvar url-get-url-filename-chars "-%.?@a-zA-Z0-9()_/:~=&"
  401. "Valid characters in a URL.")
  402. (defun url-get-url-at-point (&optional pt)
  403. "Get the URL closest to point, but don't change position.
  404. Has a preference for looking backward when not directly on a symbol."
  405. ;; Not at all perfect - point must be right in the name.
  406. (save-excursion
  407. (if pt (goto-char pt))
  408. (let (start url)
  409. (save-excursion
  410. ;; first see if you're just past a filename
  411. (if (not (eobp))
  412. (if (looking-at "[] \t\n[{}()]") ; whitespace or some parens
  413. (progn
  414. (skip-chars-backward " \n\t\r({[]})")
  415. (if (not (bobp))
  416. (backward-char 1)))))
  417. (if (and (char-after (point))
  418. (string-match (concat "[" url-get-url-filename-chars "]")
  419. (char-to-string (char-after (point)))))
  420. (progn
  421. (skip-chars-backward url-get-url-filename-chars)
  422. (setq start (point))
  423. (skip-chars-forward url-get-url-filename-chars))
  424. (setq start (point)))
  425. (setq url (buffer-substring-no-properties start (point))))
  426. (if (and url (string-match "^(.*)\\.?$" url))
  427. (setq url (match-string 1 url)))
  428. (if (and url (string-match "^URL:" url))
  429. (setq url (substring url 4 nil)))
  430. (if (and url (string-match "\\.$" url))
  431. (setq url (substring url 0 -1)))
  432. (if (and url (string-match "^www\\." url))
  433. (setq url (concat "http://" url)))
  434. (if (and url (not (string-match url-nonrelative-link url)))
  435. (setq url nil))
  436. url)))
  437. (defun url-generate-unique-filename (&optional fmt)
  438. "Generate a unique filename in `url-temporary-directory'."
  439. ;; This variable is obsolete, but so is this function.
  440. (let ((tempdir (with-no-warnings url-temporary-directory)))
  441. (if (not fmt)
  442. (let ((base (format "url-tmp.%d" (user-real-uid)))
  443. (fname "")
  444. (x 0))
  445. (setq fname (format "%s%d" base x))
  446. (while (file-exists-p
  447. (expand-file-name fname tempdir))
  448. (setq x (1+ x)
  449. fname (concat base (int-to-string x))))
  450. (expand-file-name fname tempdir))
  451. (let ((base (concat "url" (int-to-string (user-real-uid))))
  452. (fname "")
  453. (x 0))
  454. (setq fname (format fmt (concat base (int-to-string x))))
  455. (while (file-exists-p
  456. (expand-file-name fname tempdir))
  457. (setq x (1+ x)
  458. fname (format fmt (concat base (int-to-string x)))))
  459. (expand-file-name fname tempdir)))))
  460. (make-obsolete 'url-generate-unique-filename 'make-temp-file "23.1")
  461. (defun url-extract-mime-headers ()
  462. "Set `url-current-mime-headers' in current buffer."
  463. (save-excursion
  464. (goto-char (point-min))
  465. (unless url-current-mime-headers
  466. (set (make-local-variable 'url-current-mime-headers)
  467. (mail-header-extract)))))
  468. (defun url-make-private-file (file)
  469. "Make FILE only readable and writable by the current user.
  470. Creates FILE and its parent directories if they do not exist."
  471. (let ((dir (file-name-directory file)))
  472. (when dir
  473. ;; For historical reasons.
  474. (make-directory dir t)))
  475. ;; Based on doc-view-make-safe-dir.
  476. (condition-case nil
  477. (let ((umask (default-file-modes)))
  478. (unwind-protect
  479. (progn
  480. (set-default-file-modes #o0600)
  481. (with-temp-buffer
  482. (write-region (point-min) (point-max)
  483. file nil 'silent nil 'excl)))
  484. (set-default-file-modes umask)))
  485. (file-already-exists
  486. (if (file-symlink-p file)
  487. (error "Danger: `%s' is a symbolic link" file))
  488. (set-file-modes file #o0600))))
  489. (provide 'url-util)
  490. ;;; url-util.el ends here