Initial Commit
[packages] / xemacs-packages / w3 / lisp / url.el
1 ;;; url.el --- Uniform Resource Locator retrieval tool  -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1996-1999, 2001, 2004-2012  Free Software Foundation, Inc.
4
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Keywords: comm, data, processes, hypermedia
7
8 ;; This file is part of GNU Emacs.
9 ;;
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
25 ;; Registered URI schemes: http://www.iana.org/assignments/uri-schemes
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'mailcap)
32
33 (eval-when-compile
34   (require 'mm-decode)
35   (require 'mm-view))
36
37 (require 'url-vars)
38 (require 'url-cookie)
39 (require 'url-history)
40 (require 'url-expand)
41 (require 'url-privacy)
42 (require 'url-methods)
43 (require 'url-proxy)
44 (require 'url-parse)
45 (require 'url-util)
46
47
48 (defcustom url-configuration-directory
49   (if (featurep 'xemacs)
50       (or (and (file-accessible-directory-p (expand-file-name "~/.url/"))
51                (expand-file-name "~/.url/"))
52           (and (file-accessible-directory-p
53                 (expand-file-name user-init-directory))
54                (expand-file-name "url/" user-init-directory)))
55     (locate-user-emacs-file "url/" ".url/"))
56   "Directory used by the URL package for cookies, history, etc."
57   :type 'directory
58   :group 'url)
59
60 (defun url-do-setup ()
61   "Setup the URL package.
62 This is to avoid conflict with user settings if URL is dumped with
63 Emacs."
64   (unless url-setup-done
65
66     ;; Make OS/2 happy
67     ;;(push '("http" "80") tcp-binary-process-input-services)
68
69     (mailcap-parse-mailcaps)
70     (mailcap-parse-mimetypes)
71
72     ;; Register all the authentication schemes we can handle
73     (url-register-auth-scheme "basic" nil 4)
74     (url-register-auth-scheme "digest" nil 7)
75
76     (setq url-cookie-file
77           (or url-cookie-file
78               (expand-file-name "cookies" url-configuration-directory)))
79
80     (setq url-history-file
81           (or url-history-file
82               (expand-file-name "history" url-configuration-directory)))
83
84     ;; Parse the global history file if it exists, so that it can be used
85     ;; for URL completion, etc.
86     (url-history-parse-history)
87     (url-history-setup-save-timer)
88
89     ;; Ditto for cookies
90     (url-cookie-setup-save-timer)
91     (url-cookie-parse-file url-cookie-file)
92
93     ;; Read in proxy gateways
94     (let ((noproxy (and (not (assoc "no_proxy" url-proxy-services))
95                         (or (getenv "NO_PROXY")
96                             (getenv "no_PROXY")
97                             (getenv "no_proxy")))))
98       (if noproxy
99           (setq url-proxy-services
100                 (cons (cons "no_proxy"
101                             (concat "\\("
102                                     (mapconcat
103                                      (lambda (x)
104                                        (cond
105                                         ((= x ?,) "\\|")
106                                         ((= x ? ) "")
107                                         ((= x ?.) (regexp-quote "."))
108                                         ((= x ?*) ".*")
109                                         ((= x ??) ".")
110                                         (t (char-to-string x))))
111                                      noproxy "") "\\)"))
112                       url-proxy-services))))
113
114     (url-setup-privacy-info)
115     (run-hooks 'url-load-hook)
116     (setq url-setup-done t)))
117
118 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
119 ;;; Retrieval functions
120 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
121
122 (defvar url-redirect-buffer nil
123   "New buffer into which the retrieval will take place.
124 Sometimes while retrieving a URL, the URL library needs to use another buffer
125 than the one returned initially by `url-retrieve'.  In this case, it sets this
126 variable in the original buffer as a forwarding pointer.")
127
128 (defvar url-retrieve-number-of-calls 0)
129 (autoload 'url-cache-prune-cache "url-cache")
130
131 ;;;###autoload
132 (defun url-retrieve (url callback &optional cbargs silent inhibit-cookies)
133   "Retrieve URL asynchronously and call CALLBACK with CBARGS when finished.
134 URL is either a string or a parsed URL.
135
136 CALLBACK is called when the object has been completely retrieved, with
137 the current buffer containing the object, and any MIME headers associated
138 with it.  It is called as (apply CALLBACK STATUS CBARGS).
139 STATUS is a list with an even number of elements representing
140 what happened during the request, with most recent events first,
141 or an empty list if no events have occurred.  Each pair is one of:
142
143 \(:redirect REDIRECTED-TO) - the request was redirected to this URL
144 \(:error (ERROR-SYMBOL . DATA)) - an error occurred.  The error can be
145 signaled with (signal ERROR-SYMBOL DATA).
146
147 Return the buffer URL will load into, or nil if the process has
148 already completed (i.e. URL was a mailto URL or similar; in this case
149 the callback is not called).
150
151 The variables `url-request-data', `url-request-method' and
152 `url-request-extra-headers' can be dynamically bound around the
153 request; dynamic binding of other variables doesn't necessarily
154 take effect.
155
156 If SILENT, then don't message progress reports and the like.
157 If INHIBIT-COOKIES, cookies will neither be stored nor sent to
158 the server.
159 If URL is a multibyte string, it will be encoded as utf-8 and
160 URL-encoded before it's used."
161 ;;; XXX: There is code in Emacs that does dynamic binding
162 ;;; of the following variables around url-retrieve:
163 ;;; url-standalone-mode, url-gateway-unplugged, w3-honor-stylesheets,
164 ;;; url-confirmation-func, url-cookie-multiple-line,
165 ;;; url-cookie-{{,secure-}storage,confirmation}
166 ;;; url-standalone-mode and url-gateway-unplugged should work as
167 ;;; usual.  url-confirmation-func is only used in nnwarchive.el and
168 ;;; webmail.el; the latter should be updated.  Is
169 ;;; url-cookie-multiple-line needed anymore?  The other url-cookie-*
170 ;;; are (for now) only used in synchronous retrievals.
171   (url-retrieve-internal url callback (cons nil cbargs) silent
172                          inhibit-cookies))
173
174 (defun url-retrieve-internal (url callback cbargs &optional silent
175                                   inhibit-cookies)
176   "Internal function; external interface is `url-retrieve'.
177 CBARGS is what the callback will actually receive - the first item is
178 the list of events, as described in the docstring of `url-retrieve'.
179
180 If SILENT, don't message progress reports and the like.
181 If INHIBIT-COOKIES, cookies will neither be stored nor sent to
182 the server.
183 If URL is a non-ASCII string, it will be encoded as utf-8 and
184 URL-encoded before it's used."
185   (url-do-setup)
186   (url-gc-dead-buffers)
187   (if (stringp url)
188        (set-text-properties 0 (length url) nil url))
189   (when (save-match-data (string-match "[^\x00-\x7f]" url))
190     (let ((url-unreserved-chars (append '(?: ?/) url-unreserved-chars)))
191       (setq url (url-hexify-string url))))
192   (if (not (vectorp url))
193       (setq url (url-generic-parse-url url)))
194   (if (not (functionp callback))
195       (error "Must provide a callback function to url-retrieve"))
196   (unless (url-type url)
197     (error "Bad url: %s" (url-recreate-url url)))
198   (setf (url-silent url) silent)
199   (setf (url-use-cookies url) (not inhibit-cookies))
200   ;; Once in a while, remove old entries from the URL cache.
201   (when (zerop (% url-retrieve-number-of-calls 1000))
202     (condition-case error
203         (url-cache-prune-cache)
204       (file-error
205        (message "Error when expiring the cache: %s" error))))
206   (setq url-retrieve-number-of-calls (1+ url-retrieve-number-of-calls))
207   (let ((loader (url-scheme-get-property (url-type url) 'loader))
208         (url-using-proxy (if (url-host url)
209                              (url-find-proxy-for-url url (url-host url))))
210         (buffer nil)
211         (asynch (url-scheme-get-property (url-type url) 'asynchronous-p)))
212     (if url-using-proxy
213         (setq asynch t
214               loader 'url-proxy))
215     (if asynch
216         (let ((url-current-object url))
217           (setq buffer (funcall loader url callback cbargs)))
218       (setq buffer (funcall loader url))
219       (if buffer
220           (with-current-buffer buffer
221             (apply callback cbargs))))
222     (if url-history-track
223         (url-history-update-url url (current-time)))
224     buffer))
225
226 ;;;###autoload
227 (defun url-retrieve-synchronously (url)
228   "Retrieve URL synchronously.
229 Return the buffer containing the data, or nil if there are no data
230 associated with it (the case for dired, info, or mailto URLs that need
231 no further processing).  URL is either a string or a parsed URL."
232   (url-do-setup)
233
234   (let ((retrieval-done nil)
235         (asynch-buffer nil))
236     (setq asynch-buffer
237           (url-retrieve url (lambda (&rest ignored)
238                               (url-debug 'retrieval "Synchronous fetching done (%S)" (current-buffer))
239                               (setq retrieval-done t
240                                     asynch-buffer (current-buffer)))))
241     (if (null asynch-buffer)
242         ;; We do not need to do anything, it was a mailto or something
243         ;; similar that takes processing completely outside of the URL
244         ;; package.
245         nil
246       (let ((proc (get-buffer-process asynch-buffer)))
247         ;; If the access method was synchronous, `retrieval-done' should
248         ;; hopefully already be set to t.  If it is nil, and `proc' is also
249         ;; nil, it implies that the async process is not running in
250         ;; asynch-buffer.  This happens e.g. for FTP files.  In such a case
251         ;; url-file.el should probably set something like a `url-process'
252         ;; buffer-local variable so we can find the exact process that we
253         ;; should be waiting for.  In the mean time, we'll just wait for any
254         ;; process output.
255         (while (not retrieval-done)
256           (url-debug 'retrieval
257                      "Spinning in url-retrieve-synchronously: %S (%S)"
258                      retrieval-done asynch-buffer)
259           (if (buffer-local-value 'url-redirect-buffer asynch-buffer)
260               (setq proc (get-buffer-process
261                           (setq asynch-buffer
262                                 (buffer-local-value 'url-redirect-buffer
263                                                     asynch-buffer))))
264             (if (and proc (memq (process-status proc)
265                                 '(closed exit signal failed))
266                      ;; Make sure another process hasn't been started.
267                      (eq proc (or (get-buffer-process asynch-buffer) proc)))
268                 ;; FIXME: It's not clear whether url-retrieve's callback is
269                 ;; guaranteed to be called or not.  It seems that url-http
270                 ;; decides sometimes consciously not to call it, so it's not
271                 ;; clear that it's a bug, but even then we need to decide how
272                 ;; url-http can then warn us that the download has completed.
273                 ;; In the mean time, we use this here workaround.
274                 ;; XXX: The callback must always be called.  Any
275                 ;; exception is a bug that should be fixed, not worked
276                 ;; around.
277                 (progn ;; Call delete-process so we run any sentinel now.
278                   (delete-process proc)
279                   (setq retrieval-done t)))
280             ;; We used to use `sit-for' here, but in some cases it wouldn't
281             ;; work because apparently pending keyboard input would always
282             ;; interrupt it before it got a chance to handle process input.
283             ;; `sleep-for' was tried but it lead to other forms of
284             ;; hanging.  --Stef
285             (unless (or (with-local-quit
286                           (accept-process-output proc))
287                         (null proc))
288               ;; accept-process-output returned nil, maybe because the process
289               ;; exited (and may have been replaced with another).  If we got
290               ;; a quit, just stop.
291               (when quit-flag
292                 (delete-process proc))
293               (setq proc (and (not quit-flag)
294                               (get-buffer-process asynch-buffer)))))))
295       asynch-buffer)))
296
297 (defun url-mm-callback (&rest ignored)
298   (let ((handle (mm-dissect-buffer t)))
299     (url-mark-buffer-as-dead (current-buffer))
300     (with-current-buffer
301         (generate-new-buffer (url-recreate-url url-current-object))
302       (if (eq (mm-display-part handle) 'external)
303           (progn
304             (set-process-sentinel
305              ;; Fixme: this shouldn't have to know the form of the
306              ;; undisplayer produced by `mm-display-part'.
307              (get-buffer-process (cdr (mm-handle-undisplayer handle)))
308              `(lambda (proc event)
309                 (mm-destroy-parts (quote ,handle))))
310             (message "Viewing externally")
311             (kill-buffer (current-buffer)))
312         (display-buffer (current-buffer))
313         (add-hook 'kill-buffer-hook
314                   `(lambda () (mm-destroy-parts ',handle))
315                   nil
316                   t)))))
317
318 (defun url-mm-url (url)
319   "Retrieve URL and pass to the appropriate viewing application."
320   ;; These requires could advantageously be moved to url-mm-callback or
321   ;; turned into autoloads, but I suspect that it would introduce some bugs
322   ;; because loading those files from a process sentinel or filter may
323   ;; result in some undesirable corner cases.
324   (require 'mm-decode)
325   (require 'mm-view)
326   (url-retrieve url 'url-mm-callback nil))
327
328 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
329 ;;; Miscellaneous
330 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
331 (defvar url-dead-buffer-list nil)
332
333 (defun url-mark-buffer-as-dead (buff)
334   (push buff url-dead-buffer-list))
335
336 (defun url-gc-dead-buffers ()
337   (let ((buff))
338     (while (setq buff (pop url-dead-buffer-list))
339       (if (buffer-live-p buff)
340           (kill-buffer buff)))))
341
342 (cond
343  ((fboundp 'display-warning)
344   (defalias 'url-warn 'display-warning))
345  ((fboundp 'warn)
346   (defun url-warn (class message &optional level)
347     (warn "(%s/%s) %s" class (or level 'warning) message)))
348  (t
349   (defun url-warn (class message &optional level)
350     (with-current-buffer (get-buffer-create "*URL-WARNINGS*")
351       (goto-char (point-max))
352       (save-excursion
353         (insert (format "(%s/%s) %s\n" class (or level 'warning) message)))
354       (display-buffer (current-buffer))))))
355
356 (provide 'url)
357
358 ;;; url.el ends here