(nnimap-request-list): Protect against not being able to open the server.
[gnus] / lisp / mm-url.el
1 ;;; mm-url.el --- a wrapper of url functions/commands for Gnus
2
3 ;; Copyright (C) 2001-2011  Free Software Foundation, Inc.
4
5 ;; Author: Shenghuo Zhu <zsh@cs.rochester.edu>
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software: you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Some codes are stolen from w3 and url packages. Some are moved from
25 ;; nnweb.
26
27 ;; TODO: Support POST, cookie.
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl))
32
33 (require 'mm-util)
34 (require 'gnus)
35
36 (defvar url-current-object)
37 (defvar url-package-name)
38 (defvar url-package-version)
39
40 (defgroup mm-url nil
41   "A wrapper of url package and external url command for Gnus."
42   :group 'gnus)
43
44 (defcustom mm-url-use-external (not
45                                 (condition-case nil
46                                     (require 'url)
47                                   (error nil)))
48   "*If non-nil, use external grab program `mm-url-program'."
49   :version "22.1"
50   :type 'boolean
51   :group 'mm-url)
52
53 (defvar mm-url-predefined-programs
54   '((wget "wget" "--user-agent=mm-url" "-q" "-O" "-")
55     (w3m  "w3m" "-dump_source")
56     (lynx "lynx" "-source")
57     (curl "curl" "--silent" "--user-agent" "mm-url" "--location")))
58
59 (defcustom mm-url-program
60   (cond
61    ((executable-find "wget") 'wget)
62    ((executable-find "w3m") 'w3m)
63    ((executable-find "lynx") 'lynx)
64    ((executable-find "curl") 'curl)
65    (t "GET"))
66   "The url grab program.
67 Likely values are `wget', `w3m', `lynx' and `curl'."
68   :version "22.1"
69   :type '(choice
70           (symbol :tag "wget" wget)
71           (symbol :tag "w3m" w3m)
72           (symbol :tag "lynx" lynx)
73           (symbol :tag "curl" curl)
74           (string :tag "other"))
75   :group 'mm-url)
76
77 (defcustom mm-url-arguments nil
78   "The arguments for `mm-url-program'."
79   :version "22.1"
80   :type '(repeat string)
81   :group 'mm-url)
82
83 \f
84 ;;; Internal variables
85
86 (defvar mm-url-package-name
87   (gnus-replace-in-string
88    (gnus-replace-in-string gnus-version " v.*$" "")
89    " " "-"))
90
91 (defvar mm-url-package-version gnus-version-number)
92
93 ;; Stolen from w3.
94 (defvar mm-url-html-entities
95   '(
96     ;;(excl        .  33)
97     (quot        .  34)
98     ;;(num         .  35)
99     ;;(dollar      .  36)
100     ;;(percent     .  37)
101     (amp         .  38)
102     (rsquo       .  39)                 ; should be U+8217
103     ;;(apos        .  39)
104     ;;(lpar        .  40)
105     ;;(rpar        .  41)
106     ;;(ast         .  42)
107     ;;(plus        .  43)
108     ;;(comma       .  44)
109     ;;(period      .  46)
110     ;;(colon       .  58)
111     ;;(semi        .  59)
112     (lt          .  60)
113     ;;(equals      .  61)
114     (gt          .  62)
115     ;;(quest       .  63)
116     ;;(commat      .  64)
117     ;;(lsqb        .  91)
118     ;;(rsqb        .  93)
119     (uarr        .  94)                 ; should be U+8593
120     ;;(lowbar      .  95)
121     (lsquo       .  96)                 ; should be U+8216
122     (lcub        . 123)
123     ;;(verbar      . 124)
124     (rcub        . 125)
125     (tilde       . 126)
126     (nbsp        . 160)
127     (iexcl       . 161)
128     (cent        . 162)
129     (pound       . 163)
130     (curren      . 164)
131     (yen         . 165)
132     (brvbar      . 166)
133     (sect        . 167)
134     (uml         . 168)
135     (copy        . 169)
136     (ordf        . 170)
137     (laquo       . 171)
138     (not         . 172)
139     (shy         . 173)
140     (reg         . 174)
141     (macr        . 175)
142     (deg         . 176)
143     (plusmn      . 177)
144     (sup2        . 178)
145     (sup3        . 179)
146     (acute       . 180)
147     (micro       . 181)
148     (para        . 182)
149     (middot      . 183)
150     (cedil       . 184)
151     (sup1        . 185)
152     (ordm        . 186)
153     (raquo       . 187)
154     (frac14      . 188)
155     (frac12      . 189)
156     (frac34      . 190)
157     (iquest      . 191)
158     (Agrave      . 192)
159     (Aacute      . 193)
160     (Acirc       . 194)
161     (Atilde      . 195)
162     (Auml        . 196)
163     (Aring       . 197)
164     (AElig       . 198)
165     (Ccedil      . 199)
166     (Egrave      . 200)
167     (Eacute      . 201)
168     (Ecirc       . 202)
169     (Euml        . 203)
170     (Igrave      . 204)
171     (Iacute      . 205)
172     (Icirc       . 206)
173     (Iuml        . 207)
174     (ETH         . 208)
175     (Ntilde      . 209)
176     (Ograve      . 210)
177     (Oacute      . 211)
178     (Ocirc       . 212)
179     (Otilde      . 213)
180     (Ouml        . 214)
181     (times       . 215)
182     (Oslash      . 216)
183     (Ugrave      . 217)
184     (Uacute      . 218)
185     (Ucirc       . 219)
186     (Uuml        . 220)
187     (Yacute      . 221)
188     (THORN       . 222)
189     (szlig       . 223)
190     (agrave      . 224)
191     (aacute      . 225)
192     (acirc       . 226)
193     (atilde      . 227)
194     (auml        . 228)
195     (aring       . 229)
196     (aelig       . 230)
197     (ccedil      . 231)
198     (egrave      . 232)
199     (eacute      . 233)
200     (ecirc       . 234)
201     (euml        . 235)
202     (igrave      . 236)
203     (iacute      . 237)
204     (icirc       . 238)
205     (iuml        . 239)
206     (eth         . 240)
207     (ntilde      . 241)
208     (ograve      . 242)
209     (oacute      . 243)
210     (ocirc       . 244)
211     (otilde      . 245)
212     (ouml        . 246)
213     (divide      . 247)
214     (oslash      . 248)
215     (ugrave      . 249)
216     (uacute      . 250)
217     (ucirc       . 251)
218     (uuml        . 252)
219     (yacute      . 253)
220     (thorn       . 254)
221     (yuml        . 255)
222
223     ;; Special handling of these
224     (frac56      . "5/6")
225     (frac16      . "1/6")
226     (frac45      . "4/5")
227     (frac35      . "3/5")
228     (frac25      . "2/5")
229     (frac15      . "1/5")
230     (frac23      . "2/3")
231     (frac13      . "1/3")
232     (frac78      . "7/8")
233     (frac58      . "5/8")
234     (frac38      . "3/8")
235     (frac18      . "1/8")
236
237     ;; The following 5 entities are not mentioned in the HTML 2.0
238     ;; standard, nor in any other HTML proposed standard of which I
239     ;; am aware.  I am not even sure they are ISO entity names.  ***
240     ;; Hence, some arrangement should be made to give a bad HTML
241     ;; message when they are seen.
242     (ndash       .  45)
243     (mdash       .  45)
244     (emsp        .  32)
245     (ensp        .  32)
246     (sim         . 126)
247     (le          . "<=")
248     (agr         . "alpha")
249     (rdquo       . "''")
250     (ldquo       . "``")
251     (trade       . "(TM)")
252     ;; To be done
253     ;; (shy      . ????) ; soft hyphen
254     )
255   "*An assoc list of entity names and how to actually display them.")
256
257 (defconst mm-url-unreserved-chars
258   '(
259     ?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
260     ?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
261     ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
262     ?- ?_ ?. ?! ?~ ?* ?' ?\( ?\))
263   "A list of characters that are _NOT_ reserved in the URL spec.
264 This is taken from RFC 2396.")
265
266 (defun mm-url-load-url ()
267   "Load `url-insert-file-contents'."
268   (unless (condition-case ()
269               (progn
270                 (require 'url-handlers)
271                 (require 'url-parse)
272                 (require 'url-vars))
273             (error nil))
274     ;; w3-4.0pre0.46 or earlier version.
275     (require 'w3-vars)
276     (require 'url)))
277
278 ;;;###autoload
279 (defun mm-url-insert-file-contents (url)
280   "Insert file contents of URL.
281 If `mm-url-use-external' is non-nil, use `mm-url-program'."
282   (if mm-url-use-external
283       (progn
284         (if (string-match "^file:/+" url)
285             (insert-file-contents (substring url (1- (match-end 0))))
286           (mm-url-insert-file-contents-external url))
287         (goto-char (point-min))
288         (if (fboundp 'url-generic-parse-url)
289             (setq url-current-object
290                   (url-generic-parse-url url)))
291         (list url (buffer-size)))
292     (mm-url-load-url)
293     (let ((name buffer-file-name)
294           (url-request-extra-headers
295            ;; ISTM setting a Connection header was a workaround for
296            ;; older versions of url included with w3, but it does more
297            ;; harm than good with the one shipped with Emacs. --ansel
298            (if (not (and (boundp 'url-version)
299                          (equal url-version "Emacs")))
300                (list (cons "Connection" "Close"))))
301           (url-package-name (or mm-url-package-name
302                                 url-package-name))
303           (url-package-version (or mm-url-package-version
304                                    url-package-version))
305           result)
306       (setq result (url-insert-file-contents url))
307       (save-excursion
308         (goto-char (point-min))
309         (while (re-search-forward "\r 1000\r ?" nil t)
310           (replace-match "")))
311       (setq buffer-file-name name)
312       (if (and (fboundp 'url-generic-parse-url)
313                (listp result))
314           (setq url-current-object (url-generic-parse-url
315                                     (car result))))
316       result)))
317
318 ;;;###autoload
319 (defun mm-url-insert-file-contents-external (url)
320   "Insert file contents of URL using `mm-url-program'."
321   (let (program args)
322     (if (symbolp mm-url-program)
323         (let ((item (cdr (assq mm-url-program mm-url-predefined-programs))))
324           (setq program (car item)
325                 args (append (cdr item) (list url))))
326       (setq program mm-url-program
327             args (append mm-url-arguments (list url))))
328     (unless (eq 0 (apply 'call-process program nil t nil args))
329       (error "Couldn't fetch %s" url))))
330
331 (defvar mm-url-timeout 30
332   "The number of seconds before timing out an URL fetch.")
333
334 (defvar mm-url-retries 10
335   "The number of retries after timing out when fetching an URL.")
336
337 (defun mm-url-insert (url &optional follow-refresh)
338   "Insert the contents from an URL in the current buffer.
339 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
340   (let ((times mm-url-retries)
341         (done nil)
342         (first t)
343         result)
344     (while (and (not (zerop (decf times)))
345                 (not done))
346       (with-timeout (mm-url-timeout)
347         (unless first
348           (message "Trying again (%s)..." (- mm-url-retries times)))
349         (setq first nil)
350         (if follow-refresh
351             (save-restriction
352               (narrow-to-region (point) (point))
353               (mm-url-insert-file-contents url)
354               (goto-char (point-min))
355               (when (re-search-forward
356                      "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
357                 (let ((url (match-string 1)))
358                   (delete-region (point-min) (point-max))
359                   (setq result (mm-url-insert url t)))))
360           (setq result (mm-url-insert-file-contents url)))
361         (setq done t)))
362     result))
363
364 (defun mm-url-decode-entities ()
365   "Decode all HTML entities."
366   (goto-char (point-min))
367   (while (re-search-forward "&\\(#[0-9]+\\|#x[0-9a-f]+\\|[a-z]+[0-9]*\\);"
368                             nil t)
369     (let* ((entity (match-string 1))
370            (elem (if (eq (aref entity 0) ?\#)
371                      (let ((c
372                             ;; Hex number: &#x3212
373                             (if (eq (aref entity 1) ?x)
374                                 (string-to-number (substring entity 2)
375                                                   16)
376                               ;; Decimal number: &#23
377                               (string-to-number (substring entity 1)))))
378                        (setq c (or (cdr (assq c mm-extra-numeric-entities))
379                                    (mm-ucs-to-char c)))
380                        (if (mm-char-or-char-int-p c) c ?#))
381                    (or (cdr (assq (intern entity)
382                                   mm-url-html-entities))
383                        ?#))))
384       (unless (stringp elem)
385         (setq elem (char-to-string elem)))
386       (replace-match elem t t))))
387
388 (defun mm-url-decode-entities-nbsp ()
389   "Decode all HTML entities and &nbsp; to a space."
390   (let ((mm-url-html-entities (cons '(nbsp . 32) mm-url-html-entities)))
391     (mm-url-decode-entities)))
392
393 (defun mm-url-decode-entities-string (string)
394   (with-temp-buffer
395     (insert string)
396     (mm-url-decode-entities)
397     (buffer-string)))
398
399 (defun mm-url-form-encode-xwfu (chunk)
400   "Escape characters in a string for application/x-www-form-urlencoded.
401 Blasphemous crap because someone didn't think %20 was good enough for encoding
402 spaces.  Die Die Die."
403   ;; This will get rid of the 'attributes' specified by the file type,
404   ;; which are useless for an application/x-www-form-urlencoded form.
405   (if (consp chunk)
406       (setq chunk (cdr chunk)))
407
408   (mapconcat
409    (lambda (char)
410      (cond
411       ((= char ?  ) "+")
412       ((memq char mm-url-unreserved-chars) (char-to-string char))
413       (t (upcase (format "%%%02x" char)))))
414    (mm-encode-coding-string chunk
415                             (if (fboundp 'find-coding-systems-string)
416                                 (car (find-coding-systems-string chunk))
417                               buffer-file-coding-system))
418    ""))
419
420 (defun mm-url-encode-www-form-urlencoded (pairs)
421   "Return PAIRS encoded for forms."
422   (mapconcat
423    (lambda (data)
424      (concat (mm-url-form-encode-xwfu (car data)) "="
425              (mm-url-form-encode-xwfu (cdr data))))
426    pairs "&"))
427
428 (autoload 'mml-compute-boundary "mml")
429
430 (defun mm-url-encode-multipart-form-data (pairs &optional boundary)
431   "Return PAIRS encoded in multipart/form-data."
432   ;; RFC1867
433
434   ;; Get a good boundary
435   (unless boundary
436     (setq boundary (mml-compute-boundary '())))
437
438   (concat
439
440    ;; Start with the boundary
441    "--" boundary "\r\n"
442
443    ;; Create name value pairs
444    (mapconcat
445     'identity
446     ;; Delete any returned items that are empty
447     (delq nil
448           (mapcar (lambda (data)
449             (when (car data)
450               ;; For each pair
451               (concat
452
453                ;; Encode the name
454                "Content-Disposition: form-data; name=\""
455                (car data) "\"\r\n"
456                "Content-Type: text/plain; charset=utf-8\r\n"
457                "Content-Transfer-Encoding: binary\r\n\r\n"
458
459                (cond ((stringp (cdr data))
460                       (cdr data))
461                      ((integerp (cdr data))
462                       (int-to-string (cdr data))))
463
464                "\r\n")))
465                   pairs))
466     ;; use the boundary as a separator
467     (concat "--" boundary "\r\n"))
468
469    ;; put a boundary at the end.
470    "--" boundary "--\r\n"))
471
472 (defun mm-url-fetch-form (url pairs)
473   "Fetch a form from URL with PAIRS as the data using the POST method."
474   (mm-url-load-url)
475   (let ((url-request-data (mm-url-encode-www-form-urlencoded pairs))
476         (url-request-method "POST")
477         (url-request-extra-headers
478          '(("Content-type" . "application/x-www-form-urlencoded"))))
479     (url-insert-file-contents url)
480     (setq buffer-file-name nil))
481   t)
482
483 (defun mm-url-fetch-simple (url content)
484   (mm-url-load-url)
485   (let ((url-request-data content)
486         (url-request-method "POST")
487         (url-request-extra-headers
488          '(("Content-type" . "application/x-www-form-urlencoded"))))
489     (url-insert-file-contents url)
490     (setq buffer-file-name nil))
491   t)
492
493 (defun mm-url-remove-markup ()
494   "Remove all HTML markup, leaving just plain text."
495   (goto-char (point-min))
496   (while (search-forward "<!--" nil t)
497     (delete-region (match-beginning 0)
498                    (or (search-forward "-->" nil t)
499                        (point-max))))
500   (goto-char (point-min))
501   (while (re-search-forward "<[^>]+>" nil t)
502     (replace-match "" t t)))
503
504 (provide 'mm-url)
505
506 ;;; mm-url.el ends here