1 ;;; url-util.el --- Miscellaneous helper routines for URL library
3 ;; Copyright (C) 1996-1999, 2001, 2004-2012 Free Software Foundation, Inc.
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Keywords: comm, data, processes
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 (autoload 'timezone-parse-date
"timezone")
30 (autoload 'timezone-make-date-arpa-standard
"timezone")
31 (autoload 'mail-header-extract
"mailheader")
33 (defvar url-parse-args-syntax-table
34 (copy-syntax-table emacs-lisp-mode-syntax-table
)
35 "A syntax table for parsing sgml attributes.")
37 (modify-syntax-entry ?
' "\"" url-parse-args-syntax-table
)
38 (modify-syntax-entry ?
` "\"" url-parse-args-syntax-table
)
39 (modify-syntax-entry ?
{ "(" url-parse-args-syntax-table
)
40 (modify-syntax-entry ?
} ")" url-parse-args-syntax-table
)
43 (defcustom url-debug nil
44 "What types of debug messages from the URL library to show.
45 Debug messages are logged to the *URL-DEBUG* buffer.
47 If t, all messages will be logged.
48 If a number, all messages will be logged, as well shown via `message'.
49 If a list, it is a list of the types of messages to be logged."
50 :type
'(choice (const :tag
"none" nil
)
52 (checklist :tag
"custom"
53 (const :tag
"HTTP" :value http
)
54 (const :tag
"DAV" :value dav
)
55 (const :tag
"General" :value retrieval
)
56 (const :tag
"Filename handlers" :value handlers
)
57 (symbol :tag
"Other")))
61 (defun url-debug (tag &rest args
)
63 (error "Interrupted!"))
64 (if (or (eq url-debug t
)
66 (and (listp url-debug
) (memq tag url-debug
)))
67 (with-current-buffer (get-buffer-create "*URL-DEBUG*")
68 (goto-char (point-max))
69 (insert (symbol-name tag
) " -> " (apply 'format args
) "\n")
70 (if (numberp url-debug
)
71 (apply 'message args
)))))
74 (defun url-parse-args (str &optional nodowncase
)
75 ;; Return an assoc list of attribute/value pairs from an RFC822-type string
79 results
; Assoc list of results
80 name-pos
; Start of XXXX= position
81 val-pos
; Start of value position
87 (set-buffer (get-buffer-create " *urlparse-temp*"))
88 (set-syntax-table url-parse-args-syntax-table
)
93 (set-syntax-table url-parse-args-syntax-table
)
94 (narrow-to-region st nd
)
95 (goto-char (point-min))
97 (skip-chars-forward "; \n\t")
98 (setq name-pos
(point))
99 (skip-chars-forward "^ \n\t=;")
101 (downcase-region name-pos
(point)))
102 (setq name
(buffer-substring name-pos
(point)))
103 (skip-chars-forward " \t\n")
104 (if (/= (or (char-after (point)) 0) ?
=) ; There is no value
106 (skip-chars-forward " \t\n=")
107 (setq val-pos
(point)
110 ((or (= (or (char-after val-pos
) 0) ?
\")
111 (= (or (char-after val-pos
) 0) ?
'))
112 (buffer-substring (1+ val-pos
)
117 (skip-chars-forward "\""))
119 (skip-chars-forward "^ \t\n")
122 (buffer-substring val-pos
124 (skip-chars-forward "^;")
125 (skip-chars-backward " \t")
127 (setq results
(cons (cons name value
) results
))
128 (skip-chars-forward "; \n\t"))
132 (defun url-insert-entities-in-string (string)
133 "Convert HTML markup-start characters to entity references in STRING.
134 Also replaces the \" character, so that the result may be safely used as
135 an attribute value in a tag. Returns a new string with the result of the
136 conversion. Replaces these characters as follows:
141 (if (string-match "[&<>\"]" string
)
142 (with-current-buffer (get-buffer-create " *entity*")
144 (buffer-disable-undo (current-buffer))
146 (goto-char (point-min))
148 (skip-chars-forward "^&<>\"")
150 (insert (cdr (assq (char-after (point))
160 (defun url-normalize-url (url)
161 "Return a 'normalized' version of URL.
162 Strips out default port numbers, etc."
163 (let (type data retval
)
164 (setq data
(url-generic-parse-url url
)
165 type
(url-type data
))
166 (if (member type
'("www" "about" "mailto" "info"))
168 ;; FIXME all this does, and all this function seems to do in
169 ;; most cases, is remove any trailing "#anchor" part of a url.
170 (setf (url-target data
) nil
)
171 (setq retval
(url-recreate-url data
)))
175 (defun url-lazy-message (&rest args
)
176 "Just like `message', but is a no-op if called more than once a second.
177 Will not do anything if `url-show-status' is nil."
178 (if (or (and url-current-object
179 (url-silent url-current-object
))
180 (null url-show-status
)
181 (active-minibuffer-window)
182 (= url-lazy-message-time
183 (setq url-lazy-message-time
(nth 1 (current-time)))))
185 (apply 'message args
)))
188 (defun url-get-normalized-date (&optional specified-time
)
189 "Return a 'real' date string that most HTTP servers can understand."
190 (let ((system-time-locale "C"))
191 (format-time-string "%a, %d %b %Y %T GMT"
192 (or specified-time
(current-time)) t
)))
195 (defun url-eat-trailing-space (x)
196 "Remove spaces/tabs at the end of a string."
197 (let ((y (1- (length x
)))
198 (skip-chars (list ? ?
\t ?
\n)))
199 (while (and (>= y
0) (memq (aref x y
) skip-chars
))
201 (substring x
0 (1+ y
))))
204 (defun url-strip-leading-spaces (x)
205 "Remove spaces at the front of a string."
206 (let ((y (1- (length x
)))
208 (skip-chars (list ? ?
\t ?
\n)))
209 (while (and (<= z y
) (memq (aref x z
) skip-chars
))
211 (substring x z nil
)))
214 (defun url-pretty-length (n)
217 (format "%d bytes" n
))
219 (format "%dk" (/ n
1024.0)))
221 (format "%2.2fM" (/ n
(* 1024 1024.0))))))
224 (defun url-display-percentage (fmt perc
&rest args
)
225 (when (and url-show-status
226 (or (null url-current-object
)
227 (not (url-silent url-current-object
))))
229 (if (fboundp 'clear-progress-display
)
230 (clear-progress-display))
231 (if (and (fboundp 'progress-display
) perc
)
232 (apply 'progress-display fmt perc args
)
233 (apply 'message fmt args
)))))
236 (defun url-percentage (x y
)
238 (round (* 100 (/ x
(float y
))))
242 (defalias 'url-basepath
'url-file-directory
)
245 (defun url-file-directory (file)
246 "Return the directory part of FILE, for a URL."
249 ((string-match "\\?" file
)
250 (file-name-directory (substring file
0 (match-beginning 0))))
251 (t (file-name-directory file
))))
254 (defun url-file-nondirectory (file)
255 "Return the nondirectory part of FILE, for a URL."
258 ((string-match "\\?" file
)
259 (file-name-nondirectory (substring file
0 (match-beginning 0))))
260 (t (file-name-nondirectory file
))))
263 (defun url-parse-query-string (query &optional downcase allow-newlines
)
264 (let (retval pairs cur key val
)
265 (setq pairs
(split-string query
"[;&]"))
267 (setq cur
(car pairs
)
269 (unless (string-match "=" cur
)
270 (setq cur
(concat cur
"=")))
272 (when (string-match "=" cur
)
273 (setq key
(url-unhex-string (substring cur
0 (match-beginning 0))
275 (setq val
(url-unhex-string (substring cur
(match-end 0) nil
)
278 (setq key
(downcase key
)))
279 (setq cur
(assoc key retval
))
281 (setcdr cur
(cons val
(cdr cur
)))
282 (setq retval
(cons (list key val
) retval
)))))
286 (defun url-build-query-string (query &optional semicolons keep-empty
)
287 "Build a query-string.
289 Given a QUERY in the form:
296 \(This is the same format as produced by `url-parse-query-string')
298 This will return a string
299 \"key1=val1&key2=val2&key3=val1&key3=val2&key4&key5\". Keys may
300 be strings or symbols; if they are symbols, the symbol name will
303 When SEMICOLONS is given, the separator will be \";\".
305 When KEEP-EMPTY is given, empty values will show as \"key=\"
306 instead of just \"key\" as in the example above."
310 (mapcar (lambda (sym)
311 (url-hexify-string (format "%s" sym
))) key-vals
)))
312 (mapconcat (lambda (val)
313 (let ((vprint (format "%s" val
))
314 (eprint (format "%s" (car escaped
))))
317 (and val
(not (zerop (length vprint
)))))
321 (or (cdr escaped
) '("")) (if semicolons
";" "&"))))
322 query
(if semicolons
";" "&")))
331 ;; Fixme: Is this definition better, and does it ever matter?
333 ;; (defun url-unhex-string (str &optional allow-newlines)
334 ;; "Remove %XX, embedded spaces, etc in a url.
335 ;; If optional second argument ALLOW-NEWLINES is non-nil, then allow the
336 ;; decoding of carriage returns and line feeds in the string, which is normally
337 ;; forbidden in URL encoding."
338 ;; (setq str (or str ""))
339 ;; (setq str (replace-regexp-in-string "%[[:xdigit:]]\\{2\\}"
341 ;; (string (string-to-number
342 ;; (substring match 1) 16)))
344 ;; (if allow-newlines
345 ;; (replace-regexp-in-string "[\n\r]" (lambda (match)
346 ;; (format "%%%.2X" (aref match 0)))
351 (defun url-unhex-string (str &optional allow-newlines
)
352 "Remove %XX embedded spaces, etc in a URL.
353 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
354 decoding of carriage returns and line feeds in the string, which is normally
355 forbidden in URL encoding."
356 (setq str
(or str
""))
358 (case-fold-search t
))
359 (while (string-match "%[0-9a-f][0-9a-f]" str
)
360 (let* ((start (match-beginning 0))
361 (ch1 (url-unhex (elt str
(+ start
1))))
363 (url-unhex (elt str
(+ start
2))))))
365 tmp
(substring str
0 start
)
368 (byte-to-string code
))
369 ((or (= code ?
\n) (= code ?
\r))
371 (t (byte-to-string code
))))
372 str
(substring str
(match-end 0)))))
375 (defconst url-unreserved-chars
376 '(?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
377 ?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
378 ?
0 ?
1 ?
2 ?
3 ?
4 ?
5 ?
6 ?
7 ?
8 ?
9
380 "List of characters that are unreserved in the URL spec.
381 This is taken from RFC 3986 (section 2.3).")
383 (defconst url-encoding-table
384 (let ((vec (make-vector 256 nil
)))
386 ;; RFC 3986 (Section 2.1): For consistency, URI producers and
387 ;; normalizers should use uppercase hexadecimal digits for all
388 ;; percent-encodings.
389 (aset vec byte
(format "%%%02X" byte
)))
391 "Vector translating bytes to URI-encoded %-sequences.")
393 (defun url--allowed-chars (char-list)
394 "Return an \"allowed character\" mask (a 256-slot vector).
395 The Nth element is non-nil if character N is in CHAR-LIST. The
396 result can be passed as the second arg to `url-hexify-string'."
397 (let ((vec (make-vector 256 nil
)))
398 (dolist (byte char-list
)
399 (ignore-errors (aset vec byte t
)))
403 (defun url-hexify-string (string &optional allowed-chars
)
404 "URI-encode STRING and return the result.
405 If STRING is multibyte, it is first converted to a utf-8 byte
406 string. Each byte corresponding to an allowed character is left
407 as-is, while all other bytes are converted to a three-character
408 string: \"%\" followed by two upper-case hex digits.
410 The allowed characters are specified by ALLOWED-CHARS. If this
411 argument is nil, the list `url-unreserved-chars' determines the
412 allowed characters. Otherwise, ALLOWED-CHARS should be a vector
413 whose Nth element is non-nil if character N is allowed."
414 (unless allowed-chars
415 (setq allowed-chars
(url--allowed-chars url-unreserved-chars
)))
416 (mapconcat (lambda (byte)
417 (if (aref allowed-chars byte
)
418 (char-to-string byte
)
419 (aref url-encoding-table byte
)))
420 (if (multibyte-string-p string
)
421 (encode-coding-string string
'utf-8
)
425 (defconst url-host-allowed-chars
426 ;; Allow % to avoid re-encoding %-encoded sequences.
427 (url--allowed-chars (append '(?% ?
! ?$ ?
& ?
' ?\
( ?\
) ?
* ?
+ ?
, ?\
; ?=)
428 url-unreserved-chars
))
429 "Allowed-character byte mask for the host segment of a URI.
430 These characters are specified in RFC 3986, Appendix A.")
432 (defconst url-path-allowed-chars
433 (let ((vec (copy-sequence url-host-allowed-chars
)))
438 "Allowed-character byte mask for the path segment of a URI.
439 These characters are specified in RFC 3986, Appendix A.")
441 (defconst url-query-allowed-chars
442 (let ((vec (copy-sequence url-path-allowed-chars
)))
445 "Allowed-character byte mask for the query segment of a URI.
446 These characters are specified in RFC 3986, Appendix A.")
449 (defun url-encode-url (url)
450 "Return a properly URI-encoded version of URL.
451 This function also performs URI normalization, e.g. converting
452 the scheme to lowercase if it is uppercase. Apart from
453 normalization, if URL is already URI-encoded, this function
454 should return it unchanged."
455 (if (multibyte-string-p url
)
456 (setq url
(encode-coding-string url
'utf-8
)))
457 (let* ((obj (url-generic-parse-url url
))
458 (user (url-user obj
))
459 (pass (url-password obj
))
460 (host (url-host obj
))
461 (path-and-query (url-path-and-query obj
))
462 (path (car path-and-query
))
463 (query (cdr path-and-query
))
464 (frag (url-target obj
)))
466 (setf (url-user obj
) (url-hexify-string user
)))
468 (setf (url-password obj
) (url-hexify-string pass
)))
469 ;; No special encoding for IPv6 literals.
471 (not (string-match "\\`\\[.*\\]\\'" host
))
473 (url-hexify-string host url-host-allowed-chars
)))
476 (setq path
(url-hexify-string path url-path-allowed-chars
)))
478 (setq query
(url-hexify-string query url-query-allowed-chars
)))
479 (setf (url-filename obj
) (if query
(concat path
"?" query
) path
))
482 (setf (url-target obj
)
483 (url-hexify-string frag url-query-allowed-chars
)))
484 (url-recreate-url obj
)))
487 (defun url-file-extension (fname &optional x
)
488 "Return the filename extension of FNAME.
489 If optional argument X is t, then return the basename
490 of the file with the extension stripped off."
492 (setq fname
(url-file-nondirectory fname
))
493 (string-match "\\.[^./]+$" fname
))
494 (if x
(substring fname
0 (match-beginning 0))
495 (substring fname
(match-beginning 0) nil
))
497 ;; If fname has no extension, and x then return fname itself instead of
498 ;; nothing. When caching it allows the correct .hdr file to be produced
499 ;; for filenames without extension.
506 (defun url-truncate-url-for-viewing (url &optional width
)
507 "Return a shortened version of URL that is WIDTH characters wide or less.
508 WIDTH defaults to the current frame width."
509 (let* ((fr-width (or width
(frame-width)))
510 (str-width (length url
))
514 ;; The first thing that can go are the search strings
515 (if (and (>= str-width fr-width
)
516 (string-match "?" url
))
517 (setq url
(concat (substring url
0 (match-beginning 0)) "?...")
518 str-width
(length url
)))
519 (if (< str-width fr-width
)
520 nil
; Hey, we are done!
521 (setq urlobj
(url-generic-parse-url url
)
522 fname
(url-filename urlobj
)
523 fr-width
(- fr-width
4))
524 (while (and (>= str-width fr-width
)
525 (string-match "/" fname
))
526 (setq fname
(substring fname
(match-end 0) nil
)
527 modified
(1+ modified
))
528 (setf (url-filename urlobj
) fname
)
529 (setq url
(url-recreate-url urlobj
)
530 str-width
(length url
)))
532 (setq fname
(concat "/.../" fname
))
533 (setq fname
(concat "/" fname
)))
534 (setf (url-filename urlobj
) fname
)
535 (setq url
(url-recreate-url urlobj
)))
539 (defun url-view-url (&optional no-show
)
540 "View the current document's URL.
541 Optional argument NO-SHOW means just return the URL, don't show it in
544 This uses `url-current-object', set locally to the buffer."
546 (if (not url-current-object
)
549 (url-recreate-url url-current-object
)
550 (message "%s" (url-recreate-url url-current-object
)))))
552 (defvar url-get-url-filename-chars
"-%.?@a-zA-Z0-9()_/:~=&"
553 "Valid characters in a URL.")
555 (defun url-get-url-at-point (&optional pt
)
556 "Get the URL closest to point, but don't change position.
557 Has a preference for looking backward when not directly on a symbol."
558 ;; Not at all perfect - point must be right in the name.
560 (if pt
(goto-char pt
))
563 ;; first see if you're just past a filename
565 (if (looking-at "[] \t\n[{}()]") ; whitespace or some parens
567 (skip-chars-backward " \n\t\r({[]})")
569 (backward-char 1)))))
570 (if (and (char-after (point))
571 (string-match (concat "[" url-get-url-filename-chars
"]")
572 (char-to-string (char-after (point)))))
574 (skip-chars-backward url-get-url-filename-chars
)
576 (skip-chars-forward url-get-url-filename-chars
))
577 (setq start
(point)))
578 (setq url
(buffer-substring-no-properties start
(point))))
579 (if (and url
(string-match "^(.*)\\.?$" url
))
580 (setq url
(match-string 1 url
)))
581 (if (and url
(string-match "^URL:" url
))
582 (setq url
(substring url
4 nil
)))
583 (if (and url
(string-match "\\.$" url
))
584 (setq url
(substring url
0 -
1)))
585 (if (and url
(string-match "^www\\." url
))
586 (setq url
(concat "http://" url
)))
587 (if (and url
(not (string-match url-nonrelative-link url
)))
591 (defun url-generate-unique-filename (&optional fmt
)
592 "Generate a unique filename in `url-temporary-directory'."
593 ;; This variable is obsolete, but so is this function.
594 (let ((tempdir (with-no-warnings url-temporary-directory
)))
596 (let ((base (format "url-tmp.%d" (user-real-uid)))
599 (setq fname
(format "%s%d" base x
))
600 (while (file-exists-p
601 (expand-file-name fname tempdir
))
603 fname
(concat base
(int-to-string x
))))
604 (expand-file-name fname tempdir
))
605 (let ((base (concat "url" (int-to-string (user-real-uid))))
608 (setq fname
(format fmt
(concat base
(int-to-string x
))))
609 (while (file-exists-p
610 (expand-file-name fname tempdir
))
612 fname
(format fmt
(concat base
(int-to-string x
)))))
613 (expand-file-name fname tempdir
)))))
614 (make-obsolete 'url-generate-unique-filename
'make-temp-file
"23.1")
616 (defun url-extract-mime-headers ()
617 "Set `url-current-mime-headers' in current buffer."
619 (goto-char (point-min))
620 (unless url-current-mime-headers
621 (set (make-local-variable 'url-current-mime-headers
)
622 (mail-header-extract)))))
624 (defun url-make-private-file (file)
625 "Make FILE only readable and writable by the current user.
626 Creates FILE and its parent directories if they do not exist."
627 (let ((dir (file-name-directory file
)))
629 ;; For historical reasons.
630 (make-directory dir t
)))
631 ;; Based on doc-view-make-safe-dir.
633 (let ((umask (default-file-modes)))
636 (set-default-file-modes #o0600
)
638 (write-region (point-min) (point-max)
639 file nil
'silent nil
'excl
)))
640 (set-default-file-modes umask
)))
642 (if (file-symlink-p file
)
643 (error "Danger: `%s' is a symbolic link" file
))
644 (set-file-modes file
#o0600
))))
648 ;;; url-util.el ends here