(ispell-find-aspell-dictionaries): Remove interactive spec.
[bpt/emacs.git] / lisp / url / url-http.el
CommitLineData
8c8b8430 1;;; url-http.el --- HTTP retrieval routines
b43eb9ab 2
71ddfde5 3;; Copyright (C) 1999, 2001, 2004, 2005 Free Software Foundation, Inc.
b43eb9ab 4
8c8b8430 5;; Author: Bill Perry <wmperry@gnu.org>
8c8b8430 6;; Keywords: comm, data, processes
3f19601e 7
b43eb9ab
SM
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 2, or (at your option)
13;; 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; see the file COPYING. If not, write to the
4fc5845f
LK
22;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23;; Boston, MA 02110-1301, USA.
8c8b8430 24
b43eb9ab
SM
25;;; Commentary:
26
27;;; Code:
8c8b8430
SM
28
29(eval-when-compile
30 (require 'cl)
2344ffc1
JB
31 (defvar url-http-extra-headers)
32 (defvar url-http-cookies-sources))
8c8b8430
SM
33(require 'url-gw)
34(require 'url-util)
35(require 'url-parse)
36(require 'url-cookie)
37(require 'mail-parse)
38(require 'url-auth)
39(autoload 'url-retrieve-synchronously "url")
40(autoload 'url-retrieve "url")
41(autoload 'url-cache-create-filename "url-cache")
42(autoload 'url-mark-buffer-as-dead "url")
43
44(defconst url-http-default-port 80 "Default HTTP port.")
45(defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
46(defalias 'url-http-expand-file-name 'url-default-expander)
47
48(defvar url-http-real-basic-auth-storage nil)
49(defvar url-http-proxy-basic-auth-storage nil)
50
51(defvar url-http-open-connections (make-hash-table :test 'equal
52 :size 17)
53 "A hash table of all open network connections.")
54
55(defvar url-http-version "1.1"
56 "What version of HTTP we advertise, as a string.
57Valid values are 1.1 and 1.0.
58This is only useful when debugging the HTTP subsystem.
59
60Setting this to 1.0 will tell servers not to send chunked encoding,
61and other HTTP/1.1 specific features.
62")
63
64(defvar url-http-attempt-keepalives t
65 "Whether to use a single TCP connection multiple times in HTTP.
66This is only useful when debugging the HTTP subsystem. Setting to
67`nil' will explicitly close the connection to the server after every
68request.
69")
70
71;(eval-when-compile
72;; These are all macros so that they are hidden from external sight
73;; when the file is byte-compiled.
74;;
75;; This allows us to expose just the entry points we want.
76
77;; These routines will allow us to implement persistent HTTP
78;; connections.
79(defsubst url-http-debug (&rest args)
80 (if quit-flag
81 (let ((proc (get-buffer-process (current-buffer))))
82 ;; The user hit C-g, honor it! Some things can get in an
83 ;; incredibly tight loop (chunked encoding)
84 (if proc
85 (progn
86 (set-process-sentinel proc nil)
87 (set-process-filter proc nil)))
88 (error "Transfer interrupted!")))
89 (apply 'url-debug 'http args))
90
91(defun url-http-mark-connection-as-busy (host port proc)
92 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
93 (puthash (cons host port)
94 (delq proc (gethash (cons host port) url-http-open-connections))
95 url-http-open-connections)
96 proc)
97
98(defun url-http-mark-connection-as-free (host port proc)
99 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
100 (set-process-buffer proc nil)
101 (set-process-sentinel proc 'url-http-idle-sentinel)
102 (puthash (cons host port)
103 (cons proc (gethash (cons host port) url-http-open-connections))
104 url-http-open-connections)
105 nil)
106
107(defun url-http-find-free-connection (host port)
108 (let ((conns (gethash (cons host port) url-http-open-connections))
109 (found nil))
110 (while (and conns (not found))
111 (if (not (memq (process-status (car conns)) '(run open)))
112 (progn
113 (url-http-debug "Cleaning up dead process: %s:%d %S"
114 host port (car conns))
115 (url-http-idle-sentinel (car conns) nil))
116 (setq found (car conns))
117 (url-http-debug "Found existing connection: %s:%d %S" host port found))
118 (pop conns))
119 (if found
120 (url-http-debug "Reusing existing connection: %s:%d" host port)
121 (url-http-debug "Contacting host: %s:%d" host port))
122 (url-lazy-message "Contacting host: %s:%d" host port)
123 (url-http-mark-connection-as-busy host port
124 (or found
125 (url-open-stream host nil host
126 port)))))
127
128;; Building an HTTP request
129(defun url-http-user-agent-string ()
130 (if (or (eq url-privacy-level 'paranoid)
131 (and (listp url-privacy-level)
132 (memq 'agent url-privacy-level)))
133 ""
134 (format "User-Agent: %sURL/%s%s\r\n"
135 (if url-package-name
136 (concat url-package-name "/" url-package-version " ")
137 "")
138 url-version
139 (cond
140 ((and url-os-type url-system-type)
141 (concat " (" url-os-type "; " url-system-type ")"))
142 ((or url-os-type url-system-type)
143 (concat " (" (or url-system-type url-os-type) ")"))
144 (t "")))))
145
146(defun url-http-create-request (url &optional ref-url)
147 "Create an HTTP request for URL, referred to by REF-URL."
148 (declare (special proxy-object proxy-info))
149 (let* ((extra-headers)
150 (request nil)
151 (no-cache (cdr-safe (assoc "Pragma" url-request-extra-headers)))
152 (proxy-obj (and (boundp 'proxy-object) proxy-object))
153 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
154 url-request-extra-headers))
155 (not proxy-obj))
156 nil
157 (let ((url-basic-auth-storage
158 'url-http-proxy-basic-auth-storage))
159 (url-get-authentication url nil 'any nil))))
e893ce91 160 (real-fname (url-filename (or proxy-obj url)))
8c8b8430
SM
161 (host (url-host (or proxy-obj url)))
162 (auth (if (cdr-safe (assoc "Authorization" url-request-extra-headers))
163 nil
164 (url-get-authentication (or
165 (and (boundp 'proxy-info)
166 proxy-info)
167 url) nil 'any nil))))
168 (if (equal "" real-fname)
169 (setq real-fname "/"))
170 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
171 (if auth
172 (setq auth (concat "Authorization: " auth "\r\n")))
173 (if proxy-auth
174 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
175
176 ;; Protection against stupid values in the referer
177 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
178 (string= ref-url "")))
179 (setq ref-url nil))
180
181 ;; We do not want to expose the referer if the user is paranoid.
182 (if (or (memq url-privacy-level '(low high paranoid))
183 (and (listp url-privacy-level)
184 (memq 'lastloc url-privacy-level)))
185 (setq ref-url nil))
186
187 ;; url-request-extra-headers contains an assoc-list of
188 ;; header/value pairs that we need to put into the request.
189 (setq extra-headers (mapconcat
190 (lambda (x)
191 (concat (car x) ": " (cdr x)))
192 url-request-extra-headers "\r\n"))
193 (if (not (equal extra-headers ""))
194 (setq extra-headers (concat extra-headers "\r\n")))
195
196 ;; This was done with a call to `format'. Concatting parts has
197 ;; the advantage of keeping the parts of each header togther and
198 ;; allows us to elide null lines directly, at the cost of making
199 ;; the layout less clear.
200 (setq request
201 (concat
202 ;; The request
231add10
RS
203 (or url-request-method "GET") " "
204 (if proxy-obj (url-recreate-url proxy-obj) real-fname)
205 " HTTP/" url-http-version "\r\n"
8c8b8430
SM
206 ;; Version of MIME we speak
207 "MIME-Version: 1.0\r\n"
208 ;; (maybe) Try to keep the connection open
209 "Connection: " (if (or proxy-obj
210 (not url-http-attempt-keepalives))
211 "close" "keep-alive") "\r\n"
212 ;; HTTP extensions we support
213 (if url-extensions-header
214 (format
215 "Extension: %s\r\n" url-extensions-header))
216 ;; Who we want to talk to
217 (if (/= (url-port (or proxy-obj url))
218 (url-scheme-get-property
219 (url-type (or proxy-obj url)) 'default-port))
220 (format
221 "Host: %s:%d\r\n" host (url-port (or proxy-obj url)))
222 (format "Host: %s\r\n" host))
223 ;; Who its from
224 (if url-personal-mail-address
225 (concat
226 "From: " url-personal-mail-address "\r\n"))
227 ;; Encodings we understand
228 (if url-mime-encoding-string
229 (concat
230 "Accept-encoding: " url-mime-encoding-string "\r\n"))
231 (if url-mime-charset-string
232 (concat
233 "Accept-charset: " url-mime-charset-string "\r\n"))
234 ;; Languages we understand
235 (if url-mime-language-string
236 (concat
237 "Accept-language: " url-mime-language-string "\r\n"))
238 ;; Types we understand
239 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
240 ;; User agent
241 (url-http-user-agent-string)
242 ;; Proxy Authorization
243 proxy-auth
244 ;; Authorization
245 auth
246 ;; Cookies
247 (url-cookie-generate-header-lines host real-fname
248 (equal "https" (url-type url)))
249 ;; If-modified-since
250 (if (and (not no-cache)
251 (member url-request-method '("GET" nil)))
252 (let ((tm (url-is-cached (or proxy-obj url))))
253 (if tm
254 (concat "If-modified-since: "
255 (url-get-normalized-date tm) "\r\n"))))
256 ;; Whence we came
257 (if ref-url (concat
258 "Referer: " ref-url "\r\n"))
259 extra-headers
dc1a0a7a 260 ;; Length of data
8c8b8430
SM
261 (if url-request-data
262 (concat
263 "Content-length: " (number-to-string
264 (length url-request-data))
dc1a0a7a 265 "\r\n"))
8c8b8430 266 ;; End request
dc1a0a7a
AS
267 "\r\n"
268 ;; Any data
269 url-request-data))
8c8b8430
SM
270 (url-http-debug "Request is: \n%s" request)
271 request))
272
273;; Parsing routines
274(defun url-http-clean-headers ()
275 "Remove trailing \r from header lines.
276This allows us to use `mail-fetch-field', etc."
277 (declare (special url-http-end-of-headers))
278 (goto-char (point-min))
279 (while (re-search-forward "\r$" url-http-end-of-headers t)
280 (replace-match "")))
281
282(defun url-http-handle-authentication (proxy)
283 (declare (special status success url-http-method url-http-data
284 url-callback-function url-callback-arguments))
285 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
286 (let ((auth (or (mail-fetch-field (if proxy "proxy-authenticate" "www-authenticate"))
287 "basic"))
288 (type nil)
289 (url (url-recreate-url url-current-object))
290 (url-basic-auth-storage 'url-http-real-basic-auth-storage)
291 )
292
293 ;; Cheating, but who cares? :)
294 (if proxy
295 (setq url-basic-auth-storage 'url-http-proxy-basic-auth-storage))
296
297 (setq auth (url-eat-trailing-space (url-strip-leading-spaces auth)))
298 (if (string-match "[ \t]" auth)
299 (setq type (downcase (substring auth 0 (match-beginning 0))))
300 (setq type (downcase auth)))
301
302 (if (not (url-auth-registered type))
303 (progn
304 (widen)
305 (goto-char (point-max))
306 (insert "<hr>Sorry, but I do not know how to handle " type
307 " authentication. If you'd like to write it,"
308 " send it to " url-bug-address ".<hr>")
309 (setq status t))
310 (let* ((args auth)
311 (ctr (1- (length args)))
312 auth)
313 (while (/= 0 ctr)
314 (if (char-equal ?, (aref args ctr))
315 (aset args ctr ?\;))
316 (setq ctr (1- ctr)))
317 (setq args (url-parse-args args)
318 auth (url-get-authentication url (cdr-safe (assoc "realm" args))
319 type t args))
320 (if (not auth)
321 (setq success t)
322 (push (cons (if proxy "Proxy-Authorization" "Authorization") auth)
323 url-http-extra-headers)
324 (let ((url-request-method url-http-method)
325 (url-request-data url-http-data)
326 (url-request-extra-headers url-http-extra-headers))
e817f9a2
TTN
327 (url-retrieve url url-callback-function
328 url-callback-arguments)))))))
8c8b8430
SM
329
330(defun url-http-parse-response ()
331 "Parse just the response code."
332 (declare (special url-http-end-of-headers url-http-response-status))
333 (if (not url-http-end-of-headers)
334 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
335 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
336 (goto-char (point-min))
337 (skip-chars-forward " \t\n") ; Skip any blank crap
338 (skip-chars-forward "HTTP/") ; Skip HTTP Version
339 (read (current-buffer))
340 (setq url-http-response-status (read (current-buffer))))
341
342(defun url-http-handle-cookies ()
343 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
344The buffer must already be narrowed to the headers, so mail-fetch-field will
345work correctly."
346 (let ((cookies (mail-fetch-field "Set-Cookie" nil nil t))
cacfe88b
AS
347 (cookies2 (mail-fetch-field "Set-Cookie2" nil nil t))
348 (url-current-object url-http-cookies-sources))
8c8b8430
SM
349 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
350 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
351 (while cookies
352 (url-cookie-handle-set-cookie (pop cookies)))
353;;; (while cookies2
354;;; (url-cookie-handle-set-cookie2 (pop cookies)))
355 )
356 )
357
358(defun url-http-parse-headers ()
359 "Parse and handle HTTP specific headers.
360Return t if and only if the current buffer is still active and
361should be shown to the user."
362 ;; The comments after each status code handled are taken from RFC
363 ;; 2616 (HTTP/1.1)
364 (declare (special url-http-end-of-headers url-http-response-status
365 url-http-method url-http-data url-http-process
366 url-callback-function url-callback-arguments))
367
368 (url-http-mark-connection-as-free (url-host url-current-object)
369 (url-port url-current-object)
370 url-http-process)
371
372 (if (or (not (boundp 'url-http-end-of-headers))
373 (not url-http-end-of-headers))
374 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
375 (goto-char (point-min))
376 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
377 (url-http-parse-response)
378 (mail-narrow-to-head)
379 ;;(narrow-to-region (point-min) url-http-end-of-headers)
b43eb9ab 380 (let ((class nil)
8c8b8430
SM
381 (success nil))
382 (setq class (/ url-http-response-status 100))
383 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status)
384 (url-http-handle-cookies)
385
386 (case class
387 ;; Classes of response codes
388 ;;
389 ;; 5xx = Server Error
390 ;; 4xx = Client Error
391 ;; 3xx = Redirection
392 ;; 2xx = Successful
393 ;; 1xx = Informational
394 (1 ; Information messages
395 ;; 100 = Continue with request
396 ;; 101 = Switching protocols
397 ;; 102 = Processing (Added by DAV)
398 (url-mark-buffer-as-dead (current-buffer))
399 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status))
400 (2 ; Success
401 ;; 200 Ok
402 ;; 201 Created
403 ;; 202 Accepted
404 ;; 203 Non-authoritative information
405 ;; 204 No content
406 ;; 205 Reset content
407 ;; 206 Partial content
408 ;; 207 Multi-status (Added by DAV)
409 (case url-http-response-status
410 ((204 205)
411 ;; No new data, just stay at the same document
412 (url-mark-buffer-as-dead (current-buffer))
413 (setq success t))
414 (otherwise
415 ;; Generic success for all others. Store in the cache, and
416 ;; mark it as successful.
417 (widen)
76bad534 418 (if (and url-automatic-caching (equal url-http-method "GET"))
8c8b8430
SM
419 (url-store-in-cache (current-buffer)))
420 (setq success t))))
421 (3 ; Redirection
422 ;; 300 Multiple choices
423 ;; 301 Moved permanently
424 ;; 302 Found
425 ;; 303 See other
426 ;; 304 Not modified
427 ;; 305 Use proxy
428 ;; 307 Temporary redirect
429 (let ((redirect-uri (or (mail-fetch-field "Location")
430 (mail-fetch-field "URI"))))
431 (case url-http-response-status
432 (300
433 ;; Quoth the spec (section 10.3.1)
434 ;; -------------------------------
435 ;; The requested resource corresponds to any one of a set of
436 ;; representations, each with its own specific location and
437 ;; agent-driven negotiation information is being provided so
438 ;; that the user can select a preferred representation and
439 ;; redirect its request to that location.
440 ;; [...]
441 ;; If the server has a preferred choice of representation, it
442 ;; SHOULD include the specific URI for that representation in
443 ;; the Location field; user agents MAY use the Location field
444 ;; value for automatic redirection.
445 ;; -------------------------------
446 ;; We do not support agent-driven negotiation, so we just
447 ;; redirect to the preferred URI if one is provided.
448 nil)
449 ((301 302 307)
450 ;; If the 301|302 status code is received in response to a
451 ;; request other than GET or HEAD, the user agent MUST NOT
452 ;; automatically redirect the request unless it can be
453 ;; confirmed by the user, since this might change the
454 ;; conditions under which the request was issued.
455 (if (member url-http-method '("HEAD" "GET"))
456 ;; Automatic redirection is ok
457 nil
458 ;; It is just too big of a pain in the ass to get this
459 ;; prompt all the time. We will just silently lose our
460 ;; data and convert to a GET method.
461 (url-http-debug "Converting `%s' request to `GET' because of REDIRECT(%d)"
462 url-http-method url-http-response-status)
463 (setq url-http-method "GET"
cfdd484f 464 url-http-data nil)))
8c8b8430
SM
465 (303
466 ;; The response to the request can be found under a different
467 ;; URI and SHOULD be retrieved using a GET method on that
468 ;; resource.
469 (setq url-http-method "GET"
470 url-http-data nil))
471 (304
472 ;; The 304 response MUST NOT contain a message-body.
473 (url-http-debug "Extracting document from cache... (%s)"
474 (url-cache-create-filename (url-view-url t)))
475 (url-cache-extract (url-cache-create-filename (url-view-url t)))
476 (setq redirect-uri nil
477 success t))
478 (305
479 ;; The requested resource MUST be accessed through the
480 ;; proxy given by the Location field. The Location field
481 ;; gives the URI of the proxy. The recipient is expected
482 ;; to repeat this single request via the proxy. 305
483 ;; responses MUST only be generated by origin servers.
484 (error "Redirection thru a proxy server not supported: %s"
485 redirect-uri))
486 (otherwise
487 ;; Treat everything like '300'
488 nil))
489 (when redirect-uri
490 ;; Clean off any whitespace and/or <...> cruft.
491 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
492 (setq redirect-uri (match-string 1 redirect-uri)))
493 (if (string-match "^<\\(.*\\)>$" redirect-uri)
494 (setq redirect-uri (match-string 1 redirect-uri)))
495
496 ;; Some stupid sites (like sourceforge) send a
497 ;; non-fully-qualified URL (ie: /), which royally confuses
498 ;; the URL library.
499 (if (not (string-match url-nonrelative-link redirect-uri))
500 (setq redirect-uri (url-expand-file-name redirect-uri)))
501 (let ((url-request-method url-http-method)
502 (url-request-data url-http-data)
503 (url-request-extra-headers url-http-extra-headers))
504 (url-retrieve redirect-uri url-callback-function
dc524e8b
RS
505 (cons :redirect
506 (cons redirect-uri
507 url-callback-arguments)))
8c8b8430
SM
508 (url-mark-buffer-as-dead (current-buffer))))))
509 (4 ; Client error
510 ;; 400 Bad Request
511 ;; 401 Unauthorized
512 ;; 402 Payment required
513 ;; 403 Forbidden
514 ;; 404 Not found
515 ;; 405 Method not allowed
516 ;; 406 Not acceptable
517 ;; 407 Proxy authentication required
518 ;; 408 Request time-out
519 ;; 409 Conflict
520 ;; 410 Gone
521 ;; 411 Length required
522 ;; 412 Precondition failed
523 ;; 413 Request entity too large
524 ;; 414 Request-URI too large
525 ;; 415 Unsupported media type
526 ;; 416 Requested range not satisfiable
527 ;; 417 Expectation failed
528 ;; 422 Unprocessable Entity (Added by DAV)
529 ;; 423 Locked
530 ;; 424 Failed Dependency
531 (case url-http-response-status
532 (401
533 ;; The request requires user authentication. The response
534 ;; MUST include a WWW-Authenticate header field containing a
535 ;; challenge applicable to the requested resource. The
536 ;; client MAY repeat the request with a suitable
537 ;; Authorization header field.
538 (url-http-handle-authentication nil))
539 (402
540 ;; This code is reserved for future use
541 (url-mark-buffer-as-dead (current-buffer))
542 (error "Somebody wants you to give them money"))
543 (403
544 ;; The server understood the request, but is refusing to
545 ;; fulfill it. Authorization will not help and the request
546 ;; SHOULD NOT be repeated.
547 (setq success t))
548 (404
549 ;; Not found
550 (setq success t))
551 (405
552 ;; The method specified in the Request-Line is not allowed
553 ;; for the resource identified by the Request-URI. The
554 ;; response MUST include an Allow header containing a list of
555 ;; valid methods for the requested resource.
556 (setq success t))
557 (406
558 ;; The resource identified by the request is only capable of
559 ;; generating response entities which have content
560 ;; characteristics nota cceptable according to the accept
561 ;; headers sent in the request.
562 (setq success t))
563 (407
564 ;; This code is similar to 401 (Unauthorized), but indicates
565 ;; that the client must first authenticate itself with the
566 ;; proxy. The proxy MUST return a Proxy-Authenticate header
567 ;; field containing a challenge applicable to the proxy for
568 ;; the requested resource.
569 (url-http-handle-authentication t))
570 (408
571 ;; The client did not produce a request within the time that
572 ;; the server was prepared to wait. The client MAY repeat
573 ;; the request without modifications at any later time.
574 (setq success t))
575 (409
576 ;; The request could not be completed due to a conflict with
577 ;; the current state of the resource. This code is only
578 ;; allowed in situations where it is expected that the user
579 ;; mioght be able to resolve the conflict and resubmit the
580 ;; request. The response body SHOULD include enough
581 ;; information for the user to recognize the source of the
582 ;; conflict.
583 (setq success t))
584 (410
585 ;; The requested resource is no longer available at the
586 ;; server and no forwarding address is known.
587 (setq success t))
588 (411
589 ;; The server refuses to accept the request without a defined
590 ;; Content-Length. The client MAY repeat the request if it
591 ;; adds a valid Content-Length header field containing the
592 ;; length of the message-body in the request message.
593 ;;
594 ;; NOTE - this will never happen because
595 ;; `url-http-create-request' automatically calculates the
596 ;; content-length.
597 (setq success t))
598 (412
599 ;; The precondition given in one or more of the
600 ;; request-header fields evaluated to false when it was
601 ;; tested on the server.
602 (setq success t))
603 ((413 414)
604 ;; The server is refusing to process a request because the
605 ;; request entity|URI is larger than the server is willing or
606 ;; able to process.
607 (setq success t))
608 (415
609 ;; The server is refusing to service the request because the
610 ;; entity of the request is in a format not supported by the
611 ;; requested resource for the requested method.
612 (setq success t))
613 (416
614 ;; A server SHOULD return a response with this status code if
615 ;; a request included a Range request-header field, and none
616 ;; of the range-specifier values in this field overlap the
617 ;; current extent of the selected resource, and the request
618 ;; did not include an If-Range request-header field.
619 (setq success t))
620 (417
621 ;; The expectation given in an Expect request-header field
622 ;; could not be met by this server, or, if the server is a
623 ;; proxy, the server has unambiguous evidence that the
624 ;; request could not be met by the next-hop server.
625 (setq success t))
626 (otherwise
627 ;; The request could not be understood by the server due to
628 ;; malformed syntax. The client SHOULD NOT repeat the
629 ;; request without modifications.
630 (setq success t))))
631 (5
632 ;; 500 Internal server error
633 ;; 501 Not implemented
634 ;; 502 Bad gateway
635 ;; 503 Service unavailable
636 ;; 504 Gateway time-out
637 ;; 505 HTTP version not supported
638 ;; 507 Insufficient storage
639 (setq success t)
640 (case url-http-response-status
641 (501
642 ;; The server does not support the functionality required to
643 ;; fulfill the request.
644 nil)
645 (502
646 ;; The server, while acting as a gateway or proxy, received
647 ;; an invalid response from the upstream server it accessed
648 ;; in attempting to fulfill the request.
649 nil)
650 (503
651 ;; The server is currently unable to handle the request due
652 ;; to a temporary overloading or maintenance of the server.
653 ;; The implication is that this is a temporary condition
654 ;; which will be alleviated after some delay. If known, the
655 ;; length of the delay MAY be indicated in a Retry-After
656 ;; header. If no Retry-After is given, the client SHOULD
657 ;; handle the response as it would for a 500 response.
658 nil)
659 (504
660 ;; The server, while acting as a gateway or proxy, did not
661 ;; receive a timely response from the upstream server
662 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
663 ;; auxiliary server (e.g. DNS) it needed to access in
664 ;; attempting to complete the request.
665 nil)
666 (505
667 ;; The server does not support, or refuses to support, the
668 ;; HTTP protocol version that was used in the request
669 ;; message.
670 nil)
671 (507 ; DAV
672 ;; The method could not be performed on the resource
673 ;; because the server is unable to store the representation
674 ;; needed to successfully complete the request. This
675 ;; condition is considered to be temporary. If the request
676 ;; which received this status code was the result of a user
677 ;; action, the request MUST NOT be repeated until it is
678 ;; requested by a separate user action.
679 nil)))
680 (otherwise
681 (error "Unknown class of HTTP response code: %d (%d)"
682 class url-http-response-status)))
683 (if (not success)
684 (url-mark-buffer-as-dead (current-buffer)))
685 (url-http-debug "Finished parsing HTTP headers: %S" success)
686 (widen)
687 success))
688
689;; Miscellaneous
690(defun url-http-activate-callback ()
691 "Activate callback specified when this buffer was created."
692 (declare (special url-http-process
693 url-callback-function
694 url-callback-arguments))
695 (url-http-mark-connection-as-free (url-host url-current-object)
696 (url-port url-current-object)
697 url-http-process)
698 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
699 (apply url-callback-function url-callback-arguments))
700
701;; )
702
703;; These unfortunately cannot be macros... please ignore them!
704(defun url-http-idle-sentinel (proc why)
705 "Remove this (now defunct) process PROC from the list of open connections."
706 (maphash (lambda (key val)
707 (if (memq proc val)
708 (puthash key (delq proc val) url-http-open-connections)))
709 url-http-open-connections))
710
711(defun url-http-end-of-document-sentinel (proc why)
712 ;; Sentinel used for old HTTP/0.9 or connections we know are going
713 ;; to die as the 'end of document' notifier.
714 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
715 (process-buffer proc))
716 (url-http-idle-sentinel proc why)
717 (save-excursion
718 (set-buffer (process-buffer proc))
719 (goto-char (point-min))
720 (if (not (looking-at "HTTP/"))
721 ;; HTTP/0.9 just gets passed back no matter what
722 (url-http-activate-callback)
723 (if (url-http-parse-headers)
724 (url-http-activate-callback)))))
725
726(defun url-http-simple-after-change-function (st nd length)
727 ;; Function used when we do NOT know how long the document is going to be
728 ;; Just _very_ simple 'downloaded %d' type of info.
729 (declare (special url-http-end-of-headers))
730 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
731
732(defun url-http-content-length-after-change-function (st nd length)
733 "Function used when we DO know how long the document is going to be.
734More sophisticated percentage downloaded, etc.
735Also does minimal parsing of HTTP headers and will actually cause
736the callback to be triggered."
737 (declare (special url-current-object
738 url-http-end-of-headers
739 url-http-content-length
740 url-http-content-type
741 url-http-process))
742 (if url-http-content-type
743 (url-display-percentage
744 "Reading [%s]... %s of %s (%d%%)"
745 (url-percentage (- nd url-http-end-of-headers)
746 url-http-content-length)
747 url-http-content-type
748 (url-pretty-length (- nd url-http-end-of-headers))
749 (url-pretty-length url-http-content-length)
750 (url-percentage (- nd url-http-end-of-headers)
751 url-http-content-length))
752 (url-display-percentage
753 "Reading... %s of %s (%d%%)"
754 (url-percentage (- nd url-http-end-of-headers)
755 url-http-content-length)
756 (url-pretty-length (- nd url-http-end-of-headers))
757 (url-pretty-length url-http-content-length)
758 (url-percentage (- nd url-http-end-of-headers)
759 url-http-content-length)))
760
761 (if (> (- nd url-http-end-of-headers) url-http-content-length)
762 (progn
763 ;; Found the end of the document! Wheee!
764 (url-display-percentage nil nil)
765 (message "Reading... done.")
766 (if (url-http-parse-headers)
767 (url-http-activate-callback)))))
768
769(defun url-http-chunked-encoding-after-change-function (st nd length)
770 "Function used when dealing with 'chunked' encoding.
771Cannot give a sophisticated percentage, but we need a different
772function to look for the special 0-length chunk that signifies
773the end of the document."
774 (declare (special url-current-object
775 url-http-end-of-headers
776 url-http-content-type
777 url-http-chunked-length
778 url-http-chunked-counter
779 url-http-process url-http-chunked-start))
780 (save-excursion
781 (goto-char st)
782 (let ((read-next-chunk t)
783 (case-fold-search t)
784 (regexp nil)
785 (no-initial-crlf nil))
786 ;; We need to loop thru looking for more chunks even within
787 ;; one after-change-function call.
788 (while read-next-chunk
789 (setq no-initial-crlf (= 0 url-http-chunked-counter))
790 (if url-http-content-type
791 (url-display-percentage nil
792 "Reading [%s]... chunk #%d"
793 url-http-content-type url-http-chunked-counter)
794 (url-display-percentage nil
795 "Reading... chunk #%d"
796 url-http-chunked-counter))
797 (url-http-debug "Reading chunk %d (%d %d %d)"
798 url-http-chunked-counter st nd length)
799 (setq regexp (if no-initial-crlf
800 "\\([0-9a-z]+\\).*\r?\n"
801 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
802
803 (if url-http-chunked-start
804 ;; We know how long the chunk is supposed to be, skip over
805 ;; leading crap if possible.
806 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
807 (progn
808 (url-http-debug "Got to the end of chunk #%d!"
809 url-http-chunked-counter)
810 (goto-char (+ url-http-chunked-start
811 url-http-chunked-length)))
812 (url-http-debug "Still need %d bytes to hit end of chunk"
813 (- (+ url-http-chunked-start
814 url-http-chunked-length)
815 nd))
816 (setq read-next-chunk nil)))
817 (if (not read-next-chunk)
818 (url-http-debug "Still spinning for next chunk...")
819 (if no-initial-crlf (skip-chars-forward "\r\n"))
820 (if (not (looking-at regexp))
821 (progn
822 ;; Must not have received the entirety of the chunk header,
823 ;; need to spin some more.
824 (url-http-debug "Did not see start of chunk @ %d!" (point))
825 (setq read-next-chunk nil))
826 (add-text-properties (match-beginning 0) (match-end 0)
827 (list 'start-open t
828 'end-open t
829 'chunked-encoding t
830 'face (if (featurep 'xemacs)
831 'text-cursor
832 'cursor)
833 'invisible t))
216d3806
JB
834 (setq url-http-chunked-length (string-to-number (buffer-substring
835 (match-beginning 1)
836 (match-end 1))
837 16)
8c8b8430
SM
838 url-http-chunked-counter (1+ url-http-chunked-counter)
839 url-http-chunked-start (set-marker
840 (or url-http-chunked-start
841 (make-marker))
842 (match-end 0)))
843; (if (not url-http-debug)
844 (delete-region (match-beginning 0) (match-end 0));)
845 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
846 url-http-chunked-counter url-http-chunked-length
847 (marker-position url-http-chunked-start))
848 (if (= 0 url-http-chunked-length)
849 (progn
850 ;; Found the end of the document! Wheee!
851 (url-http-debug "Saw end of stream chunk!")
852 (setq read-next-chunk nil)
853 (url-display-percentage nil nil)
854 (goto-char (match-end 1))
855 (if (re-search-forward "^\r*$" nil t)
63db9644 856 (url-http-debug "Saw end of trailers..."))
8c8b8430
SM
857 (if (url-http-parse-headers)
858 (url-http-activate-callback))))))))))
859
860(defun url-http-wait-for-headers-change-function (st nd length)
861 ;; This will wait for the headers to arrive and then splice in the
862 ;; next appropriate after-change-function, etc.
863 (declare (special url-current-object
864 url-http-end-of-headers
865 url-http-content-type
866 url-http-content-length
867 url-http-transfer-encoding
868 url-callback-function
869 url-callback-arguments
870 url-http-process
871 url-http-method
872 url-http-after-change-function
873 url-http-response-status))
874 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
875 (buffer-name))
876 (if (not (bobp))
877 (let ((end-of-headers nil)
878 (old-http nil)
879 (content-length nil))
880 (goto-char (point-min))
881 (if (not (looking-at "^HTTP/[1-9]\\.[0-9]"))
882 ;; Not HTTP/x.y data, must be 0.9
883 ;; God, I wish this could die.
884 (setq end-of-headers t
885 url-http-end-of-headers 0
886 old-http t)
887 (if (re-search-forward "^\r*$" nil t)
888 ;; Saw the end of the headers
889 (progn
890 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
891 (setq url-http-end-of-headers (set-marker (make-marker)
892 (point))
893 end-of-headers t)
894 (url-http-clean-headers))))
895
896 (if (not end-of-headers)
897 ;; Haven't seen the end of the headers yet, need to wait
898 ;; for more data to arrive.
899 nil
900 (if old-http
901 (message "HTTP/0.9 How I hate thee!")
902 (progn
903 (url-http-parse-response)
904 (mail-narrow-to-head)
905 ;;(narrow-to-region (point-min) url-http-end-of-headers)
906 (setq url-http-transfer-encoding (mail-fetch-field
907 "transfer-encoding")
908 url-http-content-type (mail-fetch-field "content-type"))
909 (if (mail-fetch-field "content-length")
910 (setq url-http-content-length
216d3806 911 (string-to-number (mail-fetch-field "content-length"))))
8c8b8430
SM
912 (widen)))
913 (if url-http-transfer-encoding
914 (setq url-http-transfer-encoding
915 (downcase url-http-transfer-encoding)))
916
917 (cond
918 ((or (= url-http-response-status 204)
919 (= url-http-response-status 205))
920 (url-http-debug "%d response must have headers only (%s)."
921 url-http-response-status (buffer-name))
922 (if (url-http-parse-headers)
923 (url-http-activate-callback)))
924 ((string= "HEAD" url-http-method)
925 ;; A HEAD request is _ALWAYS_ terminated by the header
926 ;; information, regardless of any entity headers,
927 ;; according to section 4.4 of the HTTP/1.1 draft.
928 (url-http-debug "HEAD request must have headers only (%s)."
929 (buffer-name))
930 (if (url-http-parse-headers)
931 (url-http-activate-callback)))
932 ((string= "CONNECT" url-http-method)
933 ;; A CONNECT request is finished, but we cannot stick this
934 ;; back on the free connectin list
935 (url-http-debug "CONNECT request must have headers only.")
936 (if (url-http-parse-headers)
937 (url-http-activate-callback)))
938 ((equal url-http-response-status 304)
939 ;; Only allowed to have a header section. We have to handle
940 ;; this here instead of in url-http-parse-headers because if
941 ;; you have a cached copy of something without a known
942 ;; content-length, and try to retrieve it from the cache, we'd
943 ;; fall into the 'being dumb' section and wait for the
944 ;; connection to terminate, which means we'd wait for 10
945 ;; seconds for the keep-alives to time out on some servers.
946 (if (url-http-parse-headers)
947 (url-http-activate-callback)))
948 (old-http
949 ;; HTTP/0.9 always signaled end-of-connection by closing the
950 ;; connection.
951 (url-http-debug
952 "Saw HTTP/0.9 response, connection closed means end of document.")
953 (setq url-http-after-change-function
954 'url-http-simple-after-change-function))
955 ((equal url-http-transfer-encoding "chunked")
956 (url-http-debug "Saw chunked encoding.")
957 (setq url-http-after-change-function
958 'url-http-chunked-encoding-after-change-function)
959 (if (> nd url-http-end-of-headers)
960 (progn
961 (url-http-debug
962 "Calling initial chunked-encoding for extra data at end of headers")
963 (url-http-chunked-encoding-after-change-function
964 (marker-position url-http-end-of-headers) nd
965 (- nd url-http-end-of-headers)))))
966 ((integerp url-http-content-length)
967 (url-http-debug
968 "Got a content-length, being smart about document end.")
969 (setq url-http-after-change-function
970 'url-http-content-length-after-change-function)
971 (cond
972 ((= 0 url-http-content-length)
973 ;; We got a NULL body! Activate the callback
974 ;; immediately!
975 (url-http-debug
976 "Got 0-length content-length, activating callback immediately.")
977 (if (url-http-parse-headers)
978 (url-http-activate-callback)))
979 ((> nd url-http-end-of-headers)
980 ;; Have some leftover data
981 (url-http-debug "Calling initial content-length for extra data at end of headers")
982 (url-http-content-length-after-change-function
983 (marker-position url-http-end-of-headers)
984 nd
985 (- nd url-http-end-of-headers)))
986 (t
987 nil)))
988 (t
989 (url-http-debug "No content-length, being dumb.")
990 (setq url-http-after-change-function
991 'url-http-simple-after-change-function)))))
992 ;; We are still at the beginning of the buffer... must just be
993 ;; waiting for a response.
994 (url-http-debug "Spinning waiting for headers..."))
995 (goto-char (point-max)))
996
997;;;###autoload
998(defun url-http (url callback cbargs)
999 "Retrieve URL via HTTP asynchronously.
1000URL must be a parsed URL. See `url-generic-parse-url' for details.
1001When retrieval is completed, the function CALLBACK is executed with
1002CBARGS as the arguments."
1003 (check-type url vector "Need a pre-parsed URL.")
1004 (declare (special url-current-object
1005 url-http-end-of-headers
1006 url-http-content-type
1007 url-http-content-length
1008 url-http-transfer-encoding
1009 url-http-after-change-function
1010 url-callback-function
1011 url-callback-arguments
1012 url-http-method
1013 url-http-extra-headers
1014 url-http-data
1015 url-http-chunked-length
1016 url-http-chunked-start
1017 url-http-chunked-counter
1018 url-http-process))
1019 (let ((connection (url-http-find-free-connection (url-host url)
1020 (url-port url)))
1021 (buffer (generate-new-buffer (format " *http %s:%d*"
1022 (url-host url)
1023 (url-port url)))))
1024 (if (not connection)
1025 ;; Failed to open the connection for some reason
1026 (progn
1027 (kill-buffer buffer)
1028 (setq buffer nil)
1029 (error "Could not create connection to %s:%d" (url-host url)
1030 (url-port url)))
1031 (save-excursion
1032 (set-buffer buffer)
1033 (mm-disable-multibyte)
1034 (setq url-current-object url
1035 mode-line-format "%b [%s]")
1036
1037 (dolist (var '(url-http-end-of-headers
1038 url-http-content-type
1039 url-http-content-length
1040 url-http-transfer-encoding
1041 url-http-after-change-function
1042 url-http-response-status
1043 url-http-chunked-length
1044 url-http-chunked-counter
1045 url-http-chunked-start
1046 url-callback-function
1047 url-callback-arguments
1048 url-http-process
1049 url-http-method
1050 url-http-extra-headers
cacfe88b
AS
1051 url-http-data
1052 url-http-cookies-sources))
8c8b8430
SM
1053 (set (make-local-variable var) nil))
1054
1055 (setq url-http-method (or url-request-method "GET")
1056 url-http-extra-headers url-request-extra-headers
1057 url-http-data url-request-data
1058 url-http-process connection
1059 url-http-chunked-length nil
1060 url-http-chunked-start nil
1061 url-http-chunked-counter 0
1062 url-callback-function callback
1063 url-callback-arguments cbargs
cacfe88b
AS
1064 url-http-after-change-function 'url-http-wait-for-headers-change-function
1065 url-http-cookies-sources (if (boundp 'proxy-object)
1066 proxy-object
1067 url-current-object))
8c8b8430
SM
1068
1069 (set-process-buffer connection buffer)
1070 (set-process-sentinel connection 'url-http-end-of-document-sentinel)
1071 (set-process-filter connection 'url-http-generic-filter)
1072 (process-send-string connection (url-http-create-request url))))
1073 buffer))
1074
1075;; Since Emacs 19/20 does not allow you to change the
1076;; `after-change-functions' hook in the midst of running them, we fake
1077;; an after change by hooking into the process filter and inserting
1078;; the data ourselves. This is slightly less efficient, but there
1079;; were tons of weird ways the after-change code was biting us in the
1080;; shorts.
1081(defun url-http-generic-filter (proc data)
1082 ;; Sometimes we get a zero-length data chunk after the process has
1083 ;; been changed to 'free', which means it has no buffer associated
1084 ;; with it. Do nothing if there is no buffer, or 0 length data.
1085 (declare (special url-http-after-change-function))
1086 (and (process-buffer proc)
1087 (/= (length data) 0)
1088 (save-excursion
1089 (set-buffer (process-buffer proc))
1090 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1091 (funcall url-http-after-change-function
1092 (point-max)
1093 (progn
1094 (goto-char (point-max))
1095 (insert data)
1096 (point-max))
1097 (length data)))))
1098
1099;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1100;;; file-name-handler stuff from here on out
1101;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1102(if (not (fboundp 'symbol-value-in-buffer))
1103 (defun url-http-symbol-value-in-buffer (symbol buffer
1104 &optional unbound-value)
1105 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1106 (save-excursion
1107 (set-buffer buffer)
1108 (if (not (boundp symbol))
1109 unbound-value
1110 (symbol-value symbol))))
1111 (defalias 'url-http-symbol-value-in-buffer 'symbol-value-in-buffer))
1112
1113(defun url-http-head (url)
1114 (let ((url-request-method "HEAD")
1115 (url-request-data nil))
1116 (url-retrieve-synchronously url)))
1117
1118;;;###autoload
1119(defun url-http-file-exists-p (url)
b43eb9ab 1120 (let ((status nil)
8c8b8430
SM
1121 (exists nil)
1122 (buffer (url-http-head url)))
1123 (if (not buffer)
1124 (setq exists nil)
1125 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1126 buffer 500)
1127 exists (and (>= status 200) (< status 300)))
1128 (kill-buffer buffer))
1129 exists))
1130
1131;;;###autoload
1132(defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1133
3f19601e 1134(defun url-http-head-file-attributes (url &optional id-format)
8c8b8430
SM
1135 (let ((buffer (url-http-head url))
1136 (attributes nil))
1137 (when buffer
1138 (setq attributes (make-list 11 nil))
1139 (setf (nth 1 attributes) 1) ; Number of links to file
1140 (setf (nth 2 attributes) 0) ; file uid
1141 (setf (nth 3 attributes) 0) ; file gid
1142 (setf (nth 7 attributes) ; file size
1143 (url-http-symbol-value-in-buffer 'url-http-content-length
1144 buffer -1))
1145 (setf (nth 8 attributes) (eval-when-compile (make-string 10 ?-)))
1146 (kill-buffer buffer))
1147 attributes))
1148
1149;;;###autoload
3f19601e 1150(defun url-http-file-attributes (url &optional id-format)
8c8b8430 1151 (if (url-dav-supported-p url)
3f19601e
SM
1152 (url-dav-file-attributes url id-format)
1153 (url-http-head-file-attributes url id-format)))
8c8b8430
SM
1154
1155;;;###autoload
1156(defun url-http-options (url)
1157 "Returns a property list describing options available for URL.
1158This list is retrieved using the `OPTIONS' HTTP method.
1159
1160Property list members:
1161
1162methods
1163 A list of symbols specifying what HTTP methods the resource
1164 supports.
1165
1166dav
1167 A list of numbers specifying what DAV protocol/schema versions are
1168 supported.
1169
1170dasl
1171 A list of supported DASL search types supported (string form)
1172
1173ranges
1174 A list of the units available for use in partial document fetches.
1175
1176p3p
1177 The `Platform For Privacy Protection' description for the resource.
1178 Currently this is just the raw header contents. This is likely to
1179 change once P3P is formally supported by the URL package or
1180 Emacs/W3.
1181"
1182 (let* ((url-request-method "OPTIONS")
1183 (url-request-data nil)
1184 (buffer (url-retrieve-synchronously url))
1185 (header nil)
1186 (options nil))
1187 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1188 'url-http-response-status buffer 0) 100)))
1189 ;; Only parse the options if we got a 2xx response code!
1190 (save-excursion
1191 (save-restriction
1192 (save-match-data
1193 (set-buffer buffer)
1194 (mail-narrow-to-head)
1195
1196 ;; Figure out what methods are supported.
1197 (when (setq header (mail-fetch-field "allow"))
1198 (setq options (plist-put
1199 options 'methods
1200 (mapcar 'intern (split-string header "[ ,]+")))))
1201
1202 ;; Check for DAV
1203 (when (setq header (mail-fetch-field "dav"))
1204 (setq options (plist-put
1205 options 'dav
1206 (delq 0
1207 (mapcar 'string-to-number
1208 (split-string header "[, ]+"))))))
1209
1210 ;; Now for DASL
1211 (when (setq header (mail-fetch-field "dasl"))
1212 (setq options (plist-put
1213 options 'dasl
1214 (split-string header "[, ]+"))))
1215
1216 ;; P3P - should get more detailed here. FIXME
1217 (when (setq header (mail-fetch-field "p3p"))
1218 (setq options (plist-put options 'p3p header)))
1219
1220 ;; Check for whether they accept byte-range requests.
1221 (when (setq header (mail-fetch-field "accept-ranges"))
1222 (setq options (plist-put
1223 options 'ranges
1224 (delq 'none
1225 (mapcar 'intern
1226 (split-string header "[, ]+"))))))
1227 ))))
1228 (if buffer (kill-buffer buffer))
1229 options))
1230
1231(provide 'url-http)
1232
b43eb9ab 1233;; arch-tag: ba7c59ae-c0f4-4a31-9617-d85f221732ee
8c8b8430 1234;;; url-http.el ends here