url-http.el 58 KB

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