Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1219 lines
51 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. ;;; request.el --- Compatible layer for URL request -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012 Takafumi Arakaki
  3. ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2012
  4. ;; Free Software Foundation, Inc.
  5. ;; Author: Takafumi Arakaki <aka.tkf at gmail.com>
  6. ;; URL: https://github.com/tkf/emacs-request
  7. ;; Package-Version: 20210410.2218
  8. ;; Package-Commit: f3a5b4352e9f444ace2a332939abff504b573887
  9. ;; Package-Requires: ((emacs "24.4"))
  10. ;; Version: 0.3.3
  11. ;; This file is NOT part of GNU Emacs.
  12. ;; request.el is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; request.el is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with request.el.
  22. ;; If not, see <https://www.gnu.org/licenses/>.
  23. ;;; Commentary:
  24. ;; Uses ``curl`` as its backend or Emacs's native ``url.el`` library if
  25. ;; ``curl`` is not found.
  26. ;;
  27. ;; The default encoding for requests is ``utf-8``. Please explicitly specify
  28. ;; ``:encoding 'binary`` for binary data.
  29. ;;; Code:
  30. (eval-when-compile
  31. (defvar url-http-method)
  32. (defvar url-http-response-status))
  33. (require 'cl-lib)
  34. (require 'url)
  35. (require 'mail-utils)
  36. (require 'autorevert)
  37. (require 'auth-source)
  38. (require 'mailheader)
  39. (defgroup request nil
  40. "Compatible layer for URL request in Emacs."
  41. :group 'comm
  42. :prefix "request-")
  43. (defconst request-version "0.3.3")
  44. (defcustom request-storage-directory
  45. (concat (file-name-as-directory user-emacs-directory) "request")
  46. "Directory to store data related to request.el."
  47. :type 'directory)
  48. (defcustom request-curl "curl"
  49. "Executable for curl command."
  50. :type 'string)
  51. (defcustom request-curl-options nil
  52. "List of curl command options.
  53. List of strings that will be passed to every curl invocation.
  54. You can pass extra options here, like setting the proxy."
  55. :type '(repeat string))
  56. (defcustom request-backend (if (executable-find request-curl)
  57. 'curl
  58. 'url-retrieve)
  59. "Backend to be used for HTTP request.
  60. Automatically set to `curl' if curl command is found."
  61. :type '(choice (const :tag "cURL backend" curl)
  62. (const :tag "url-retrieve backend" url-retrieve)))
  63. (defcustom request-timeout nil
  64. "Default request timeout in second.
  65. nil means no timeout."
  66. :type '(choice (integer :tag "Request timeout seconds")
  67. (boolean :tag "No timeout" nil)))
  68. (make-obsolete-variable 'request-temp-prefix nil "0.3.3")
  69. (defcustom request-log-level -1
  70. "Logging level for request.
  71. One of `error'/`warn'/`info'/`verbose'/`debug'/`trace'/`blather'.
  72. -1 means no logging."
  73. :type '(choice (integer :tag "No logging" -1)
  74. (const :tag "Level error" error)
  75. (const :tag "Level warn" warn)
  76. (const :tag "Level info" info)
  77. (const :tag "Level Verbose" verbose)
  78. (const :tag "Level DEBUG" debug)
  79. (const :tag "Level TRACE" trace)
  80. (const :tag "Level BLATHER" blather)))
  81. (defcustom request-message-level 'warn
  82. "Logging level for request.
  83. See `request-log-level'."
  84. :type '(choice (integer :tag "No logging" -1)
  85. (const :tag "Level error" error)
  86. (const :tag "Level warn" warn)
  87. (const :tag "Level info" info)
  88. (const :tag "Level Verbose" verbose)
  89. (const :tag "Level DEBUG" debug)
  90. (const :tag "Level TRACE" trace)
  91. (const :tag "Level BLATHER" blather)))
  92. (defmacro request--document-function (function docstring)
  93. "Document FUNCTION with DOCSTRING. Use this for defstruct accessor etc."
  94. (declare (indent defun)
  95. (doc-string 2))
  96. `(put ',function 'function-documentation ,docstring))
  97. (defconst request--log-level-def
  98. '(;; debugging
  99. (blather . 60) (trace . 50) (debug . 40)
  100. ;; information
  101. (verbose . 30) (info . 20)
  102. ;; errors
  103. (warn . 10) (error . 0))
  104. "Named logging levels.")
  105. (defvar request-log-buffer-name " *request-log*")
  106. (defmacro request-log (level fmt &rest args)
  107. "Main logging function at warning LEVEL in FMT with ARGS."
  108. (declare (indent 1))
  109. `(cl-flet ((log-level-as-int
  110. (level)
  111. (if (integerp level)
  112. level
  113. (or (cdr (assq level request--log-level-def)) 0))))
  114. (let ((level (log-level-as-int ,level))
  115. (log-level (log-level-as-int request-log-level))
  116. (msg-level (log-level-as-int request-message-level)))
  117. (when (<= level (max log-level msg-level))
  118. (let ((msg (format "[%s] %s" ,level (format ,fmt ,@args))))
  119. (when (<= level log-level)
  120. (with-current-buffer (get-buffer-create request-log-buffer-name)
  121. (setq buffer-read-only t)
  122. (let ((inhibit-read-only t))
  123. (goto-char (point-max))
  124. (insert msg "\n"))))
  125. (when (<= level msg-level)
  126. (message "%s" msg)))))))
  127. (defconst request--url-unreserved-chars
  128. '(?a ?b ?c ?d ?e ?f ?g ?h ?i ?j ?k ?l ?m ?n ?o ?p ?q ?r ?s ?t ?u ?v ?w ?x ?y ?z
  129. ?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z
  130. ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
  131. ?- ?_ ?. ?~)
  132. "`url-unreserved-chars' copied from Emacs 24.3 release candidate.
  133. This is used for making `request--urlencode-alist' RFC 3986 compliant
  134. for older Emacs versions.")
  135. (defun request--urlencode-alist (alist)
  136. "Hexify ALIST fields according to RFC3986."
  137. (let ((url-unreserved-chars request--url-unreserved-chars))
  138. (cl-loop for sep = "" then "&"
  139. for (k . v) in alist
  140. concat sep
  141. concat (url-hexify-string (format "%s" k))
  142. concat "="
  143. concat (url-hexify-string (format "%s" v)))))
  144. (defun request--parse-response-at-point ()
  145. "Parse the first header line such as \"HTTP/1.1 200 OK\"."
  146. (when (re-search-forward "\\=[ \t\n]*HTTP/\\([0-9\\.]+\\) +\\([0-9]+\\)" nil t)
  147. (list :version (match-string 1)
  148. :code (string-to-number (match-string 2)))))
  149. (defun request--goto-next-body (&optional noerror)
  150. "Scan forward to next blank line allowing NOERROR if missing."
  151. (re-search-forward "^\r\n" nil noerror))
  152. (cl-defstruct request-response
  153. "A structure holding all relevant information of a request."
  154. status-code history data error-thrown symbol-status url
  155. done-p settings
  156. ;; internal variables
  157. -buffer -raw-header -timer -backend)
  158. (defmacro request--document-response (function docstring)
  159. "Append to FUNCTION's DOCSTRING some more canned verbiage."
  160. (declare (indent defun) (doc-string 2))
  161. `(request--document-function ,function ,(concat docstring "
  162. .. This is an accessor for `request-response' object.
  163. \(fn RESPONSE)")))
  164. (request--document-response request-response-status-code
  165. "Integer HTTP response code (e.g., 200).")
  166. (request--document-response request-response-history
  167. "Redirection history (a list of response object).
  168. The first element is the oldest redirection.
  169. You can use restricted portion of functions for the response
  170. objects in the history slot. It also depends on backend. Here
  171. is the table showing what functions you can use for the response
  172. objects in the history slot.
  173. ==================================== ============== ==============
  174. Slots Backends
  175. ------------------------------------ -----------------------------
  176. \\ curl url-retrieve
  177. ==================================== ============== ==============
  178. request-response-url yes yes
  179. request-response-header yes no
  180. other functions no no
  181. ==================================== ============== ==============
  182. ")
  183. (request--document-response request-response-data
  184. "Response parsed by the given parser.")
  185. (request--document-response request-response-error-thrown
  186. "Error thrown during request.
  187. It takes the form of ``(ERROR-SYMBOL . DATA)``, which can be
  188. re-raised (`signal'ed) by ``(signal ERROR-SYMBOL DATA)``.")
  189. (request--document-response request-response-symbol-status
  190. "A symbol representing the status of request (not HTTP response code).
  191. One of success/error/timeout/abort/parse-error.")
  192. (request--document-response request-response-url
  193. "Final URL location of response.")
  194. (request--document-response request-response-done-p
  195. "Return t when the request is finished or aborted.")
  196. (request--document-response request-response-settings
  197. "Keyword arguments passed to `request' function.
  198. Some arguments such as HEADERS is changed to the one actually
  199. passed to the backend. Also, it has additional keywords such
  200. as URL which is the requested URL.")
  201. (defun request-response-header (response field-name)
  202. "Fetch the values of RESPONSE header field named FIELD-NAME.
  203. It returns comma separated values when the header has multiple
  204. field with the same name, as :RFC:`2616` specifies.
  205. Examples::
  206. (request-response-header response
  207. \"content-type\") ; => \"text/html; charset=utf-8\"
  208. (request-response-header response
  209. \"unknown-field\") ; => nil"
  210. (let ((raw-header (request-response--raw-header response)))
  211. (when raw-header
  212. (with-temp-buffer
  213. (erase-buffer)
  214. (insert raw-header)
  215. ;; ALL=t to fetch all fields with the same name to get comma
  216. ;; separated value [#rfc2616-sec4]_.
  217. (mail-fetch-field field-name nil t)))))
  218. ;; .. [#rfc2616-sec4] RFC2616 says this is the right thing to do
  219. ;; (see https://tools.ietf.org/html/rfc2616.html#section-4.2).
  220. ;; Python's requests module does this too.
  221. (defun request-response-headers (response)
  222. "Return RESPONSE headers as an alist.
  223. I would have chosen a function name that wasn't so suggestive that
  224. `headers` is a member of the `request-response` struct, but
  225. as there's already precedent with `request-response-header', I
  226. hew to consistency."
  227. (let ((raw-header (request-response--raw-header response)))
  228. (when raw-header
  229. (with-temp-buffer
  230. (save-excursion (insert raw-header))
  231. (when (save-excursion (request--parse-response-at-point))
  232. (forward-line))
  233. (mail-header-extract-no-properties)))))
  234. (defconst request--backend-alist
  235. '((url-retrieve
  236. . ((request . request--url-retrieve)
  237. (request-sync . request--url-retrieve-sync)
  238. (terminate-process . delete-process)
  239. (get-cookies . request--url-retrieve-get-cookies)))
  240. (curl
  241. . ((request . request--curl)
  242. (request-sync . request--curl-sync)
  243. (terminate-process . interrupt-process)
  244. (get-cookies . request--curl-get-cookies))))
  245. "Map backend and method name to actual method (symbol).
  246. It's alist of alist, of the following form::
  247. ((BACKEND . ((METHOD . FUNCTION) ...)) ...)
  248. It would be nicer if I can use EIEIO. But as CEDET is included
  249. in Emacs by 23.2, using EIEIO means abandon older Emacs versions.
  250. It is probably necessary if I need to support more backends. But
  251. let's stick to manual dispatch for now.")
  252. ;; See: (view-emacs-news "23.2")
  253. (defun request--choose-backend (method)
  254. "Return `fucall'able object for METHOD of current `request-backend'."
  255. (assoc-default
  256. method
  257. (or (assoc-default request-backend request--backend-alist)
  258. (error "%S is not valid `request-backend'" request-backend))))
  259. (defun request-cookie-string (host &optional localpart secure)
  260. "Lookup HOST LOCALPART SECURE in cookie jar as`document.cookie` string.
  261. Example::
  262. (request-cookie-string \"127.0.0.1\" \"/\") ; => \"key=value; key2=value2\""
  263. (mapconcat (lambda (nv) (concat (car nv) "=" (cdr nv)))
  264. (request-cookie-alist host localpart secure)
  265. "; "))
  266. (defun request-cookie-alist (host &optional localpart secure)
  267. "Lookup HOST LOCALPART SECURE in cookie jar as alist.
  268. Example::
  269. (request-cookie-alist \"127.0.0.1\" \"/\") ; => ((\"key\" . \"value\") ...)"
  270. (funcall (request--choose-backend 'get-cookies) host localpart secure))
  271. (cl-defun request (url &rest settings
  272. &key
  273. (params nil)
  274. (data nil)
  275. (headers nil)
  276. (encoding 'utf-8)
  277. (error nil)
  278. (sync nil)
  279. (response (make-request-response))
  280. &allow-other-keys)
  281. "Main entry requesting URL with property list SETTINGS as follow.
  282. ==================== ========================================================
  283. Keyword argument Explanation
  284. ==================== ========================================================
  285. TYPE (string) type of request to make: POST/GET/PUT/DELETE
  286. PARAMS (alist) set \"?key=val\" part in URL
  287. DATA (string/alist) data to be sent to the server
  288. FILES (alist) files to be sent to the server (see below)
  289. PARSER (symbol) a function that reads current buffer and return data
  290. HEADERS (alist) additional headers to send with the request
  291. ENCODING (symbol) encoding for request body (utf-8 by default)
  292. SUCCESS (function) called on success
  293. ERROR (function) called on error
  294. COMPLETE (function) called on both success and error
  295. TIMEOUT (number) timeout in second
  296. STATUS-CODE (alist) map status code (int) to callback
  297. SYNC (bool) If non-nil, wait until request is done. Default is nil.
  298. ==================== ========================================================
  299. * Callback functions
  300. Callback functions STATUS, ERROR, COMPLETE and `cdr's in element of
  301. the alist STATUS-CODE take same keyword arguments listed below. For
  302. forward compatibility, these functions must ignore unused keyword
  303. arguments (i.e., it's better to use `&allow-other-keys' [#]_).::
  304. (CALLBACK ; SUCCESS/ERROR/COMPLETE/STATUS-CODE
  305. :data data ; whatever PARSER function returns, or nil
  306. :error-thrown error-thrown ; (ERROR-SYMBOL . DATA), or nil
  307. :symbol-status symbol-status ; success/error/timeout/abort/parse-error
  308. :response response ; request-response object
  309. ...)
  310. .. [#] `&allow-other-keys' is a special \"markers\" available in macros
  311. in the CL library for function definition such as `cl-defun' and
  312. `cl-function'. Without this marker, you need to specify all arguments
  313. to be passed. This becomes problem when request.el adds new arguments
  314. when calling callback functions. If you use `&allow-other-keys'
  315. (or manually ignore other arguments), your code is free from this
  316. problem. See info node `(cl) Argument Lists' for more information.
  317. Arguments data, error-thrown, symbol-status can be accessed by
  318. `request-response-data', `request-response-error-thrown',
  319. `request-response-symbol-status' accessors, i.e.::
  320. (request-response-data RESPONSE) ; same as data
  321. Response object holds other information which can be accessed by
  322. the following accessors:
  323. `request-response-status-code',
  324. `request-response-url' and
  325. `request-response-settings'
  326. * STATUS-CODE callback
  327. STATUS-CODE is an alist of the following format::
  328. ((N-1 . CALLBACK-1)
  329. (N-2 . CALLBACK-2)
  330. ...)
  331. Here, N-1, N-2,... are integer status codes such as 200.
  332. * FILES
  333. FILES is an alist of the following format::
  334. ((NAME-1 . FILE-1)
  335. (NAME-2 . FILE-2)
  336. ...)
  337. where FILE-N is a list of the form::
  338. (FILENAME &key PATH BUFFER STRING MIME-TYPE)
  339. FILE-N can also be a string (path to the file) or a buffer object.
  340. In that case, FILENAME is set to the file name or buffer name.
  341. Example FILES argument::
  342. `((\"passwd\" . \"/etc/passwd\") ; filename = passwd
  343. (\"scratch\" . ,(get-buffer \"*scratch*\")) ; filename = *scratch*
  344. (\"passwd2\" . (\"password.txt\" :file \"/etc/passwd\"))
  345. (\"scratch2\" . (\"scratch.txt\" :buffer ,(get-buffer \"*scratch*\")))
  346. (\"data\" . (\"data.csv\" :data \"1,2,3\\n4,5,6\\n\")))
  347. .. note:: FILES is implemented only for curl backend for now.
  348. As furl.el_ supports multipart POST, it should be possible to
  349. support FILES in pure elisp by making furl.el_ another backend.
  350. Contributions are welcome.
  351. .. _furl.el: https://code.google.com/p/furl-el/
  352. * PARSER function
  353. PARSER function takes no argument and it is executed in the
  354. buffer with HTTP response body. The current position in the HTTP
  355. response buffer is at the beginning of the buffer. As the HTTP
  356. header is stripped off, the cursor is actually at the beginning
  357. of the response body. So, for example, you can pass `json-read'
  358. to parse JSON object in the buffer. To fetch whole response as a
  359. string, pass `buffer-string'.
  360. When using `json-read', it is useful to know that the returned
  361. type can be modified by `json-object-type', `json-array-type',
  362. `json-key-type', `json-false' and `json-null'. See docstring of
  363. each function for what it does. For example, to convert JSON
  364. objects to plist instead of alist, wrap `json-read' by `lambda'
  365. like this.::
  366. (request
  367. \"https://...\"
  368. :parser (lambda ()
  369. (let ((json-object-type 'plist))
  370. (json-read)))
  371. ...)
  372. This is analogous to the `dataType' argument of jQuery.ajax_.
  373. Only this function can access to the process buffer, which
  374. is killed immediately after the execution of this function.
  375. * SYNC
  376. Synchronous request is functional, but *please* don't use it
  377. other than testing or debugging. Emacs users have better things
  378. to do rather than waiting for HTTP request. If you want a better
  379. way to write callback chains, use `request-deferred'.
  380. If you can't avoid using it (e.g., you are inside of some hook
  381. which must return some value), make sure to set TIMEOUT to
  382. relatively small value.
  383. Due to limitation of `url-retrieve-synchronously', response slots
  384. `request-response-error-thrown', `request-response-history' and
  385. `request-response-url' are unknown (always nil) when using
  386. synchronous request with `url-retrieve' backend.
  387. * Note
  388. API of `request' is somewhat mixture of jQuery.ajax_ (Javascript)
  389. and requests.request_ (Python).
  390. .. _jQuery.ajax: https://api.jquery.com/jQuery.ajax/
  391. .. _requests.request: https://docs.python-requests.org"
  392. (declare (indent defun))
  393. ;; FIXME: support CACHE argument (if possible)
  394. ;; (unless cache
  395. ;; (setq url (request--url-no-cache url)))
  396. (unless error
  397. (setq error (cl-function
  398. (lambda (&rest args &key symbol-status &allow-other-keys)
  399. (request-log 'error
  400. "request-default-error-callback: %s %s"
  401. url symbol-status))))
  402. (setq settings (plist-put settings :error error)))
  403. (unless (or (stringp data)
  404. (null data)
  405. (assoc-string "Content-Type" headers t))
  406. (setq data (request--urlencode-alist data))
  407. (setq settings (plist-put settings :data data)))
  408. (when params
  409. (cl-assert (listp params) nil "PARAMS must be an alist. Given: %S" params)
  410. (setq url (concat url (if (string-match-p "\\?" url) "&" "?")
  411. (request--urlencode-alist params))))
  412. (setq settings (plist-put settings :url url))
  413. (setq settings (plist-put settings :response response))
  414. (setq settings (plist-put settings :encoding encoding))
  415. (setf (request-response-settings response) settings)
  416. (setf (request-response-url response) url)
  417. (setf (request-response--backend response) request-backend)
  418. ;; Call `request--url-retrieve'(`-sync') or `request--curl'(`-sync').
  419. (apply (if sync
  420. (request--choose-backend 'request-sync)
  421. (request--choose-backend 'request))
  422. url settings)
  423. response)
  424. (defun request--clean-header (response)
  425. "Strip off carriage return in the header of RESPONSE."
  426. (let* ((buffer (request-response--buffer response))
  427. (backend (request-response--backend response))
  428. ;; FIXME: a workaround when `url-http-clean-headers' fails...
  429. (sep-regexp (if (eq backend 'url-retrieve) "^\r?$" "^\r$")))
  430. (when (buffer-live-p buffer)
  431. (with-current-buffer buffer
  432. (goto-char (point-min))
  433. (when (and (re-search-forward sep-regexp nil t)
  434. (not (equal (match-string 0) "")))
  435. (request-log 'trace "request--clean-header: cleaning\n%s"
  436. (buffer-substring (save-excursion
  437. (forward-line -1)
  438. (line-beginning-position))
  439. (save-excursion
  440. (forward-line 1)
  441. (line-end-position))))
  442. (while (re-search-backward "\r$" (point-min) t)
  443. (replace-match "")))))))
  444. (defun request--cut-header (response)
  445. "Move the header to the raw-header slot of RESPONSE object."
  446. (let ((buffer (request-response--buffer response)))
  447. (when (buffer-live-p buffer)
  448. (with-current-buffer buffer
  449. (goto-char (point-min))
  450. (when (re-search-forward "^$" nil t)
  451. (setf (request-response--raw-header response)
  452. (buffer-substring (point-min) (point)))
  453. (request-log 'trace "request--cut-header: cutting\n%s"
  454. (buffer-substring (point-min) (min (1+ (point)) (point-max))))
  455. (delete-region (point-min) (min (1+ (point)) (point-max))))))))
  456. (defun request-untrampify-filename (file)
  457. "Return FILE as the local file name."
  458. (or (file-remote-p file 'localname) file))
  459. (defun request--parse-data (response encoding parser)
  460. "In RESPONSE buffer, decode via ENCODING, then send to PARSER."
  461. (let ((buffer (request-response--buffer response)))
  462. (when (buffer-live-p buffer)
  463. (with-current-buffer buffer
  464. (request-log 'trace "request--parse-data: %s" (buffer-string))
  465. (unless (eq (request-response-status-code response) 204)
  466. (recode-region (point-min) (point-max) encoding 'no-conversion)
  467. (goto-char (point-min))
  468. (setf (request-response-data response)
  469. (if parser (funcall parser) (buffer-string))))))))
  470. (defsubst request-url-file-p (url)
  471. "Return non-nil if URL looks like a file URL."
  472. (let ((scheme (and (stringp url) (url-type (url-generic-parse-url url)))))
  473. (and (stringp scheme)
  474. (not (string-match-p "^http" scheme)))))
  475. (cl-defun request--callback (buffer
  476. &key
  477. parser success error complete
  478. status-code response
  479. encoding
  480. &allow-other-keys)
  481. "Parse BUFFER according to PARSER.
  482. Delegate to callbacks SUCCESS, ERROR, and COMPLETE the STATUS-CODE of
  483. RESPONSE via ENCODING."
  484. (request-log 'debug "request--callback: UNPARSED\n%s"
  485. (when (buffer-live-p buffer)
  486. (with-current-buffer buffer (buffer-string))))
  487. ;; Reset RESPONSE buffer to argument BUFFER.
  488. (setf (request-response--buffer response) buffer)
  489. (cl-symbol-macrolet ((timer (request-response--timer response)))
  490. (when timer
  491. (cancel-timer timer)
  492. (setq timer nil)))
  493. (cl-symbol-macrolet
  494. ((error-thrown (request-response-error-thrown response))
  495. (symbol-status (request-response-symbol-status response))
  496. (data (request-response-data response))
  497. (done-p (request-response-done-p response)))
  498. (let* ((response-url (request-response-url response))
  499. (curl-file-p (and (eq (request-response--backend response) 'curl)
  500. (request-url-file-p response-url))))
  501. (unless curl-file-p
  502. (request--clean-header response)
  503. (request--cut-header response)))
  504. ;; Parse response even if `error-thrown' is set, e.g., timeout
  505. (condition-case err
  506. (request--parse-data response encoding parser)
  507. (error (unless error-thrown (setq error-thrown err))
  508. (unless symbol-status (setq symbol-status 'parse-error))))
  509. (kill-buffer buffer)
  510. ;; Ensuring `symbol-status' and `error-thrown' are consistent
  511. ;; is why we should get rid of `symbol-status'
  512. ;; (but downstream apps might ill-advisedly rely on it).
  513. (if error-thrown
  514. (progn
  515. (request-log 'error "request--callback: %s"
  516. (error-message-string error-thrown))
  517. (unless symbol-status (setq symbol-status 'error)))
  518. (unless symbol-status (setq symbol-status 'success))
  519. (request-log 'debug "request--callback: PARSED\n%s" data))
  520. (let ((args (list :data data
  521. :symbol-status symbol-status
  522. :error-thrown error-thrown
  523. :response response)))
  524. (let* ((success-p (eq symbol-status 'success))
  525. (cb (if success-p success error))
  526. (name (if success-p "success" "error")))
  527. (when cb
  528. (request-log 'debug "request--callback: executing %s" name)
  529. (apply cb args)))
  530. (let ((cb (cdr (assq (request-response-status-code response)
  531. status-code))))
  532. (when cb
  533. (request-log 'debug "request--callback: executing status-code")
  534. (apply cb args)))
  535. (when complete
  536. (request-log 'debug "request--callback: executing complete")
  537. (apply complete args)))
  538. (setq done-p t)))
  539. (cl-defun request-response--timeout-callback (response)
  540. "If RESPONSE times out, ensure `request--callback' gets called."
  541. (setf (request-response-symbol-status response) 'timeout)
  542. (setf (request-response-error-thrown response) '(error . ("Timeout")))
  543. (let* ((buffer (request-response--buffer response))
  544. (proc (and (buffer-live-p buffer) (get-buffer-process buffer))))
  545. (if proc
  546. ;; This implicitly calls `request--callback'!
  547. (funcall (request--choose-backend 'terminate-process) proc)
  548. (cl-symbol-macrolet ((done-p (request-response-done-p response)))
  549. (unless done-p
  550. (when (buffer-live-p buffer)
  551. (cl-destructuring-bind (&key code &allow-other-keys)
  552. (with-current-buffer buffer
  553. (goto-char (point-min))
  554. (request--parse-response-at-point))
  555. (setf (request-response-status-code response) code)))
  556. (apply #'request--callback
  557. buffer
  558. (request-response-settings response))
  559. (setq done-p t))))))
  560. (defun request-abort (response)
  561. "Abort request for RESPONSE (the object returned by `request').
  562. Note that this function invoke ERROR and COMPLETE callbacks.
  563. Callbacks may not be called immediately but called later when
  564. associated process is exited."
  565. (cl-symbol-macrolet ((buffer (request-response--buffer response))
  566. (symbol-status (request-response-symbol-status response))
  567. (done-p (request-response-done-p response)))
  568. (let ((process (get-buffer-process buffer)))
  569. (unless symbol-status ; should I use done-p here?
  570. (setq symbol-status 'abort)
  571. (setq done-p t)
  572. (when (process-live-p process)
  573. (funcall (request--choose-backend 'terminate-process) process))))))
  574. (cl-defun request--url-retrieve-preprocess-settings
  575. (&rest settings &key type data files headers &allow-other-keys)
  576. "Augment SETTINGS with properties TYPE DATA FILES HEADERS."
  577. (when files
  578. (error "`url-retrieve' backend does not support FILES"))
  579. (when (and (equal type "POST")
  580. data
  581. (not (assoc-string "Content-Type" headers t)))
  582. (push '("Content-Type" . "application/x-www-form-urlencoded") headers)
  583. (setq settings (plist-put settings :headers headers)))
  584. settings)
  585. (cl-defun request--url-retrieve (url &rest settings
  586. &key type data timeout response
  587. &allow-other-keys
  588. &aux headers)
  589. "Internal workhorse querying URL via curl.
  590. SETTINGS is a property list with keys (some optional) such as GET or POST TYPE,
  591. DATA for posting fields, TIMEOUT in seconds, RESPONSE a mandatory struct.
  592. HEADERS needs to be assigned after SETTINGS is preprocessed."
  593. (setq settings (apply #'request--url-retrieve-preprocess-settings settings))
  594. (setq headers (plist-get settings :headers))
  595. (let* ((url-request-extra-headers headers)
  596. (url-request-method type)
  597. (url-request-data data)
  598. (buffer (url-retrieve url #'request--url-retrieve-callback
  599. (nconc (list :response response) settings) t))
  600. (proc (get-buffer-process buffer)))
  601. (request--install-timeout timeout response)
  602. (setf (request-response--buffer response) buffer)
  603. (process-put proc :request-response response)
  604. (set-process-query-on-exit-flag proc nil)))
  605. (cl-defun request--url-retrieve-callback (status &rest settings
  606. &key response url
  607. &allow-other-keys)
  608. "Ensure `request--callback' gets called for STATUS.
  609. SETTINGS should include RESPONSE and URL properties which
  610. inform any necessary redirect or history recording logic."
  611. (when (featurep 'url-http)
  612. (setf (request-response-status-code response) url-http-response-status))
  613. (let ((redirect (plist-get status :redirect)))
  614. (when redirect
  615. (setf (request-response-url response) redirect)))
  616. ;; Construct history slot
  617. (cl-loop for v in
  618. (cl-loop with first = t
  619. with l = nil
  620. for (k v) on status by 'cddr
  621. when (eq k :redirect)
  622. if first
  623. do (setq first nil)
  624. else
  625. do (push v l)
  626. finally do (cons url l))
  627. do (let ((r (make-request-response :-backend 'url-retrieve)))
  628. (setf (request-response-url r) v)
  629. (push r (request-response-history response))))
  630. (cl-symbol-macrolet ((error-thrown (request-response-error-thrown response))
  631. (status-error (plist-get status :error)))
  632. (when status-error
  633. (request-log 'warn "request--url-retrieve-callback: %s" status-error)
  634. (unless error-thrown
  635. (setq error-thrown status-error))))
  636. (apply #'request--callback (current-buffer) settings))
  637. (cl-defun request--url-retrieve-sync (url &rest settings
  638. &key type data timeout response
  639. &allow-other-keys
  640. &aux headers)
  641. "Internal synchronous retrieve of URL.
  642. SETTINGS include typical TYPE DATA TIMEOUT RESPONSE properties.
  643. HEADERS needs to be assigned after SETTINGS is preprocessed."
  644. (setq settings (apply #'request--url-retrieve-preprocess-settings settings))
  645. (setq headers (plist-get settings :headers))
  646. (let* ((url-request-extra-headers headers)
  647. (url-request-method type)
  648. (url-request-data data)
  649. (buffer (if timeout
  650. (with-timeout
  651. (timeout
  652. (setf (request-response-symbol-status response)
  653. 'timeout)
  654. (setf (request-response-done-p response) t)
  655. nil)
  656. (url-retrieve-synchronously url t))
  657. (url-retrieve-synchronously url t))))
  658. (setf (request-response--buffer response) buffer)
  659. ;; It seems there is no way to get redirects and URL here...
  660. (when buffer
  661. ;; Fetch HTTP response code
  662. (with-current-buffer buffer
  663. (goto-char (point-min))
  664. (cl-destructuring-bind (&key code &allow-other-keys)
  665. (request--parse-response-at-point)
  666. (setf (request-response-status-code response) code)))
  667. ;; Parse response body, etc.
  668. (apply #'request--callback buffer settings)))
  669. response)
  670. (defun request--url-retrieve-get-cookies (host localpart secure)
  671. "Retrieve cookies corresponding to HOST LOCALPART SECURE."
  672. (mapcar
  673. (lambda (c) (cons (url-cookie-name c) (url-cookie-value c)))
  674. (url-cookie-retrieve host localpart secure)))
  675. (defvar request--curl-cookie-jar nil
  676. "Override what the function `request--curl-cookie-jar' returns.
  677. Currently it is used only for testing.")
  678. (defun request--curl-cookie-jar ()
  679. "Cookie storage for curl backend."
  680. (or request--curl-cookie-jar
  681. (expand-file-name "curl-cookie-jar" request-storage-directory)))
  682. (defvar request--curl-capabilities-cache
  683. (make-hash-table :test 'eq :weakness 'key)
  684. "Used to avoid invoking curl more than once for version info. By skeeto/elfeed.")
  685. (defun request--curl-capabilities ()
  686. "Return capabilities plist for curl. By skeeto/elfeed.
  687. :version -- cURL's version string
  688. :compression -- non-nil if --compressed is supported."
  689. (let ((cache-value (gethash request-curl request--curl-capabilities-cache)))
  690. (if cache-value
  691. cache-value
  692. (with-temp-buffer
  693. (call-process request-curl nil t nil "--version")
  694. (let ((version
  695. (progn
  696. (setf (point) (point-min))
  697. (when (re-search-forward "[.0-9]+" nil t)
  698. (match-string 0))))
  699. (compression
  700. (progn
  701. (setf (point) (point-min))
  702. (not (null (re-search-forward "libz\\>" nil t))))))
  703. (setf (gethash request-curl request--curl-capabilities-cache)
  704. `(:version ,version :compression ,compression)))))))
  705. (defconst request--curl-write-out-template
  706. (if (eq system-type 'windows-nt)
  707. "\\n(:num-redirects %{num_redirects} :url-effective %{url_effective})"
  708. "\\n(:num-redirects %{num_redirects} :url-effective \"%{url_effective}\")"))
  709. (cl-defun request--curl-command
  710. (url &key type data headers files unix-socket auth
  711. &allow-other-keys
  712. &aux (cookie-jar (convert-standard-filename
  713. (expand-file-name (request--curl-cookie-jar)))))
  714. "Internal command cobbler for curl to URL.
  715. TYPE, DATA, HEADERS, FILES, UNIX-SOCKET, AUTH are as described in `request'.
  716. COOKIE-JAR is the file location for the netscape cookie jar, usually
  717. in the request subdirectory of `user-emacs-directory'.
  718. BUG: Simultaneous requests are a known cause of cookie-jar corruption."
  719. (append
  720. (list request-curl
  721. "--silent" "--location"
  722. "--cookie" cookie-jar "--cookie-jar" cookie-jar)
  723. (when auth
  724. (let* ((host (url-host (url-generic-parse-url url)))
  725. (auth-source-creation-prompts `((user . ,(format "%s user: " host))
  726. (secret . "Password for %u: ")))
  727. (cred (car (auth-source-search
  728. :host host :require '(:user :secret) :create t :max 1))))
  729. (split-string (format "--%s --user %s:%s"
  730. auth
  731. (plist-get cred :user)
  732. (let ((secret (plist-get cred :secret)))
  733. (if (functionp secret)
  734. (funcall secret)
  735. secret))))))
  736. (unless (request-url-file-p url)
  737. (list "--include" "--write-out" request--curl-write-out-template))
  738. request-curl-options
  739. (when (plist-get (request--curl-capabilities) :compression) (list "--compressed"))
  740. (when unix-socket (list "--unix-socket" unix-socket))
  741. (cl-loop with stdin-p = data
  742. for (name . item) in files
  743. collect "--form"
  744. collect
  745. (apply #'format "%s=@%s;filename=%s%s"
  746. (cond ((stringp item)
  747. (list name item (file-name-nondirectory item) ""))
  748. ((bufferp item)
  749. (if stdin-p
  750. (error (concat "request--curl-command: "
  751. "only one buffer or data entry permitted"))
  752. (setq stdin-p t))
  753. (list name "-" (buffer-name item) ""))
  754. ((listp item)
  755. (unless (plist-get (cdr item) :file)
  756. (if stdin-p
  757. (error (concat "request--curl-command: "
  758. "only one buffer or data entry permitted"))
  759. (setq stdin-p t)))
  760. (list name (or (plist-get (cdr item) :file) "-") (car item)
  761. (if (plist-get item :mime-type)
  762. (format ";type=%s" (plist-get item :mime-type))
  763. "")))
  764. (t (error (concat "request--curl-command: "
  765. "%S not string, buffer, or list")
  766. item)))))
  767. (when data
  768. (split-string "--data-binary @-"))
  769. (when type (if (equal "head" (downcase type))
  770. (list "--head")
  771. (list "--request" type)))
  772. (cl-loop for (k . v) in headers
  773. collect "--header"
  774. collect (format "%s: %s" k v))
  775. (list url)))
  776. (defun request--install-timeout (timeout response)
  777. "Out-of-band trigger after TIMEOUT seconds to forestall a hung RESPONSE."
  778. (when (numberp timeout)
  779. (setf (request-response--timer response)
  780. (run-at-time timeout nil
  781. #'request-response--timeout-callback response))))
  782. (defun request--curl-occlude-secret (command)
  783. "Simple regex filter on anything looking like a secret in COMMAND."
  784. (let ((matched
  785. (string-match (concat (regexp-quote "--user") "\\s-*\\(\\S-+\\)") command)))
  786. (if matched
  787. (replace-match "elided" nil nil command 1)
  788. command)))
  789. (cl-defun request--curl (url &rest settings
  790. &key data files timeout response encoding semaphore
  791. &allow-other-keys)
  792. "Internal workhorse querying URL via curl.
  793. SETTINGS is a property list with keys (some optional) such as DATA for
  794. posting fields, FILES containing one or more lists of the form
  795. (NAME . FILENAME)
  796. (NAME . BUFFER)
  797. (NAME . (FILENAME :buffer BUFFER))
  798. (NAME . (FILENAME :data DATA))
  799. with NAME and FILENAME defined by curl(1)'s overwrought `--form` switch format,
  800. TIMEOUT in seconds, RESPONSE a mandatory struct, ENCODING, and SEMAPHORE,
  801. an internal semaphore.
  802. Redirection handling strategy
  803. -----------------------------
  804. curl follows redirection when --location is given. However,
  805. all headers are printed when it is used with --include option.
  806. Number of redirects is printed out sexp-based message using
  807. --write-out option (see `request--curl-write-out-template').
  808. This number is used for removing extra headers and parse
  809. location header from the last redirection header.
  810. Sexp at the end of buffer and extra headers for redirects are
  811. removed from the buffer before it is shown to the parser function."
  812. (ignore-errors
  813. (make-directory (file-name-directory (request--curl-cookie-jar)) t))
  814. (let* (process-connection-type ;; pipe, not pty, else curl hangs
  815. (home-directory (or (file-remote-p default-directory) "~/"))
  816. (default-directory (expand-file-name home-directory))
  817. (buffer (generate-new-buffer " *request curl*"))
  818. (command (apply #'request--curl-command url settings))
  819. (proc (apply #'start-process "request curl" buffer command))
  820. (file-items (mapcar #'cdr files))
  821. (file-buffer (or (cl-some (lambda (item)
  822. (when (bufferp item) item))
  823. file-items)
  824. (cl-some (lambda (item)
  825. (and (listp item)
  826. (plist-get (cdr item) :buffer)))
  827. file-items)))
  828. (file-data (cl-some (lambda (item)
  829. (and (listp item)
  830. (plist-get (cdr item) :data)))
  831. file-items)))
  832. (request--install-timeout timeout response)
  833. (request-log 'debug "request--curl: %s"
  834. (request--curl-occlude-secret (mapconcat #'identity command " ")))
  835. (setf (request-response--buffer response) buffer)
  836. (process-put proc :request-response response)
  837. (set-process-coding-system proc 'no-conversion 'no-conversion)
  838. (set-process-query-on-exit-flag proc nil)
  839. (when (or data file-buffer file-data)
  840. ;; We dynamic-let the global `buffer-file-coding-system' to `no-conversion'
  841. ;; in case the user-configured `encoding' doesn't fly.
  842. ;; If we do not dynamic-let the global, `select-safe-coding-system' would
  843. ;; plunge us into an undesirable interactive dialogue.
  844. (let* ((buffer-file-coding-system-orig
  845. (default-value 'buffer-file-coding-system))
  846. (select-safe-coding-system-accept-default-p
  847. (lambda (&rest _) t)))
  848. (unwind-protect
  849. (progn
  850. (setf (default-value 'buffer-file-coding-system) 'no-conversion)
  851. (with-temp-buffer
  852. (setq-local buffer-file-coding-system encoding)
  853. (insert (or data
  854. (when file-buffer
  855. (with-current-buffer file-buffer
  856. (buffer-substring-no-properties (point-min) (point-max))))
  857. file-data))
  858. (process-send-region proc (point-min) (point-max))
  859. (process-send-eof proc)))
  860. (setf (default-value 'buffer-file-coding-system)
  861. buffer-file-coding-system-orig))))
  862. (let ((callback-2 (apply-partially #'request--curl-callback url)))
  863. (if semaphore
  864. (set-process-sentinel proc (lambda (&rest args)
  865. (apply callback-2 args)
  866. (apply semaphore args)))
  867. (set-process-sentinel proc callback-2)))))
  868. (defun request--curl-read-and-delete-tail-info ()
  869. "Read a sexp at the end of buffer and remove it and preceding character.
  870. This function moves the point at the end of buffer by side effect.
  871. See also `request--curl-write-out-template'."
  872. (let (forward-sexp-function)
  873. (goto-char (point-max))
  874. (forward-sexp -1)
  875. (let ((beg (1- (point))))
  876. (prog1
  877. (read (current-buffer))
  878. (delete-region beg (point-max))))))
  879. (defconst request--cookie-reserved-re
  880. (mapconcat
  881. (lambda (x) (concat "\\(^" x "\\'\\)"))
  882. '("comment" "commenturl" "discard" "domain" "max-age" "path" "port"
  883. "secure" "version" "expires")
  884. "\\|")
  885. "Uninterested keys in cookie.
  886. See \"set-cookie-av\" in https://www.ietf.org/rfc/rfc2965.txt")
  887. (defun request--consume-100-continue ()
  888. "Remove \"HTTP/* 100 Continue\" header at the point."
  889. (cl-destructuring-bind (&key code &allow-other-keys)
  890. (save-excursion (request--parse-response-at-point))
  891. (when (equal code 100)
  892. (request-log 'debug "request--consume-100-continue: consuming\n%s"
  893. (buffer-substring (point)
  894. (save-excursion
  895. (request--goto-next-body t)
  896. (point))))
  897. (delete-region (point) (progn (request--goto-next-body) (point)))
  898. ;; FIXME: Does this make sense? Is it possible to have multiple 100?
  899. (request--consume-100-continue))))
  900. (defun request--consume-200-connection-established ()
  901. "Remove \"HTTP/* 200 Connection established\" header at the point."
  902. (when (looking-at-p "HTTP/1\\.[0-1] 200 Connection established")
  903. (delete-region (point) (progn (request--goto-next-body) (point)))))
  904. (defun request--curl-preprocess (&optional url)
  905. "Pre-process current buffer before showing it to user.
  906. Curl switches need to be adjusted if URL is a file://."
  907. (let (history)
  908. (cl-destructuring-bind (&key num-redirects url-effective)
  909. (if (request-url-file-p url)
  910. `(:num-redirects 0 :url-effective ,url)
  911. (request--curl-read-and-delete-tail-info))
  912. (goto-char (point-min))
  913. (request--consume-100-continue)
  914. (request--consume-200-connection-established)
  915. (when (> num-redirects 0)
  916. (cl-loop with case-fold-search = t
  917. repeat num-redirects
  918. ;; Do not store code=100 headers:
  919. do (request--consume-100-continue)
  920. do (let ((response (make-request-response
  921. :-buffer (current-buffer)
  922. :-backend 'curl)))
  923. (request--clean-header response)
  924. (request--cut-header response)
  925. (push response history))))
  926. (goto-char (point-min))
  927. (nconc (list :num-redirects num-redirects :url-effective url-effective
  928. :history (nreverse history))
  929. (request--parse-response-at-point)))))
  930. (defun request--curl-absolutify-redirects (start-url redirects)
  931. "Convert relative paths in REDIRECTS to absolute URLs.
  932. START-URL is the URL requested."
  933. (cl-loop for prev-url = start-url then url
  934. for url in redirects
  935. unless (string-match url-nonrelative-link url)
  936. do (setq url (url-expand-file-name url prev-url))
  937. collect url))
  938. (defun request--curl-absolutify-location-history (start-url history)
  939. "Convert relative paths in HISTORY to absolute URLs.
  940. START-URL is the URL requested."
  941. (when history
  942. (setf (request-response-url (car history)) start-url))
  943. (cl-loop for url in (request--curl-absolutify-redirects
  944. start-url
  945. (mapcar (lambda (response)
  946. (or (request-response-header response "location")
  947. (request-response-url response)))
  948. history))
  949. for response in (cdr history)
  950. do (setf (request-response-url response) url)))
  951. (defun request--curl-callback (url proc event)
  952. "Ensure `request--callback' gets called after curl to URL finishes.
  953. See info entries on sentinels regarding PROC and EVENT."
  954. (let* ((buffer (process-buffer proc))
  955. (response (process-get proc :request-response))
  956. (settings (request-response-settings response)))
  957. (request-log 'debug "request--curl-callback: event %s" event)
  958. (request-log 'trace "request--curl-callback: raw-bytes=\n%s"
  959. (when (buffer-live-p buffer)
  960. (with-current-buffer buffer (buffer-string))))
  961. (cond
  962. ((and (memq (process-status proc) '(exit signal))
  963. (/= (process-exit-status proc) 0))
  964. (setf (request-response-error-thrown response) (cons 'error event))
  965. (apply #'request--callback buffer settings))
  966. ((cl-search "finished" event)
  967. (cl-destructuring-bind (&key code history error url-effective &allow-other-keys)
  968. (condition-case err
  969. (with-current-buffer buffer
  970. (request--curl-preprocess url))
  971. ((debug error)
  972. (list :error err)))
  973. (request--curl-absolutify-location-history (plist-get settings :url)
  974. history)
  975. (setf (request-response-status-code response) code)
  976. (setf (request-response-url response) url-effective)
  977. (setf (request-response-history response) history)
  978. (setf (request-response-error-thrown response)
  979. (or error (and (numberp code) (>= code 400) `(error . (http ,code)))))
  980. (apply #'request--callback buffer settings))))))
  981. (defun request-auto-revert-notify-rm-watch ()
  982. "Backport of M. Engdegard's fix of `auto-revert-notify-rm-watch'."
  983. (let ((desc auto-revert-notify-watch-descriptor)
  984. (table (if (boundp 'auto-revert--buffers-by-watch-descriptor)
  985. auto-revert--buffers-by-watch-descriptor
  986. (when (boundp 'auto-revert-notify-watch-descriptor-hash-list)
  987. auto-revert-notify-watch-descriptor-hash-list))))
  988. (when (and desc table)
  989. (let ((buffers (delq (current-buffer) (gethash desc table))))
  990. (if buffers
  991. (puthash desc buffers table)
  992. (remhash desc table)))
  993. (condition-case nil ;; ignore-errors doesn't work for me, sorry
  994. (file-notify-rm-watch desc)
  995. (error))
  996. (remove-hook 'kill-buffer-hook #'auto-revert-notify-rm-watch t)))
  997. (setq auto-revert-notify-watch-descriptor nil
  998. auto-revert-notify-modified-p nil))
  999. (cl-defun request--curl-sync (url &rest settings &key response &allow-other-keys)
  1000. "Internal synchronous curl call to URL with SETTINGS bespeaking RESPONSE."
  1001. (let (finished)
  1002. (prog1 (apply #'request--curl url
  1003. :semaphore (lambda (&rest _) (setq finished t))
  1004. settings)
  1005. (let* ((proc (get-buffer-process (request-response--buffer response)))
  1006. (interval 0.05)
  1007. (timeout 5)
  1008. (maxiter (truncate (/ timeout interval))))
  1009. (auto-revert-set-timer)
  1010. (when auto-revert-use-notify
  1011. (dolist (buf (buffer-list))
  1012. (with-current-buffer buf
  1013. (request-auto-revert-notify-rm-watch))))
  1014. (with-local-quit
  1015. (cl-loop with iter = 0
  1016. until (or (>= iter maxiter) finished)
  1017. do (accept-process-output nil interval)
  1018. unless (process-live-p proc)
  1019. do (cl-incf iter)
  1020. end
  1021. finally (when (>= iter maxiter)
  1022. (let ((m "request--curl-sync: semaphore never called"))
  1023. (princ (format "%s\n" m) #'external-debugging-output)
  1024. (request-log 'error m)))))))))
  1025. (defun request--curl-get-cookies (host localpart secure)
  1026. "Return entry for HOST LOCALPART SECURE in cookie jar."
  1027. (request--netscape-get-cookies (request--curl-cookie-jar)
  1028. host localpart secure))
  1029. (defun request--netscape-cookie-parse ()
  1030. "Parse Netscape/Mozilla cookie format."
  1031. (goto-char (point-min))
  1032. (let ((tsv-re (concat "^\\(#HttpOnly_\\)?"
  1033. (cl-loop repeat 6 concat "\\([^\t\n]+\\)\t")
  1034. "\\(.*\\)"))
  1035. cookies)
  1036. (while (not (eobp))
  1037. ;; HttpOnly cookie starts with '#' but its line is not comment line(#60)
  1038. (cond ((and (looking-at-p "^#") (not (looking-at-p "^#HttpOnly_"))) t)
  1039. ((looking-at-p "^$") t)
  1040. ((looking-at tsv-re)
  1041. (let ((cookie (cl-loop for i from 1 to 8 collect (match-string i))))
  1042. (push cookie cookies))))
  1043. (forward-line 1))
  1044. (setq cookies (nreverse cookies))
  1045. (cl-loop for (http-only domain flag path secure expiration name value) in cookies
  1046. collect (list domain
  1047. (equal flag "TRUE")
  1048. path
  1049. (equal secure "TRUE")
  1050. (null (not http-only))
  1051. (string-to-number expiration)
  1052. name
  1053. value))))
  1054. (defun request--netscape-filter-cookies (cookies host localpart secure)
  1055. "Filter COOKIES for entries containing HOST LOCALPART SECURE."
  1056. (cl-loop for (domain _flag path secure-1 _http-only _expiration name value) in cookies
  1057. when (and (equal domain host)
  1058. (equal path localpart)
  1059. (or secure (not secure-1)))
  1060. collect (cons name value)))
  1061. (defun request--netscape-get-cookies (filename host localpart secure)
  1062. "Get cookies from FILENAME corresponding to HOST LOCALPART SECURE."
  1063. (when (file-readable-p filename)
  1064. (with-temp-buffer
  1065. (erase-buffer)
  1066. (insert-file-contents filename)
  1067. (request--netscape-filter-cookies (request--netscape-cookie-parse)
  1068. host localpart secure))))
  1069. (provide 'request)
  1070. ;;; request.el ends here