2001-12-18 01:00:00 ShengHuo ZHU <zsh@cs.rochester.edu>
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- Functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three:  Message Header Extensions for Non-ASCII Text".
27
28 ;;; Code:
29
30 (eval-when-compile (require 'cl))
31
32 (require 'qp)
33 (require 'mm-util)
34 (require 'ietf-drums)
35 (require 'mail-prsvr)
36 (require 'base64)
37 ;; Fixme: Avoid this (for gnus-point-at-...) mm dependence on gnus.
38 (require 'gnus-util)
39 (autoload 'mm-body-7-or-8 "mm-bodies")
40
41 (defvar rfc2047-header-encoding-alist
42   '(("Newsgroups" . nil)
43     ("Message-ID" . nil)
44     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
45      "-A-Za-z0-9!*+/=_")
46     (t . mime))
47   "*Header/encoding method alist.
48 The list is traversed sequentially.  The keys can either be
49 header regexps or t.
50
51 The values can be:
52
53 1) nil, in which case no encoding is done;
54 2) `mime', in which case the header will be encoded according to RFC2047;
55 3) a charset, in which case it will be encoded as that charset;
56 4) `default', in which case the field will be encoded as the rest
57    of the article.
58 5) a string, like `mime', expect for using it as word-chars.")
59
60 (defvar rfc2047-charset-encoding-alist
61   '((us-ascii . nil)
62     (iso-8859-1 . Q)
63     (iso-8859-2 . Q)
64     (iso-8859-3 . Q)
65     (iso-8859-4 . Q)
66     (iso-8859-5 . B)
67     (koi8-r . B)
68     (iso-8859-7 . Q)
69     (iso-8859-8 . Q)
70     (iso-8859-9 . Q)
71     (iso-8859-14 . Q)
72     (iso-8859-15 . Q)
73     (iso-2022-jp . B)
74     (iso-2022-kr . B)
75     (gb2312 . B)
76     (big5 . B)
77     (cn-big5 . B)
78     (cn-gb . B)
79     (cn-gb-2312 . B)
80     (euc-kr . B)
81     (iso-2022-jp-2 . B)
82     (iso-2022-int-1 . B))
83   "Alist of MIME charsets to RFC2047 encodings.
84 Valid encodings are nil, `Q' and `B'.")
85
86 (defvar rfc2047-encoding-function-alist
87   '((Q . rfc2047-q-encode-region)
88     (B . rfc2047-b-encode-region)
89     (nil . ignore))
90   "Alist of RFC2047 encodings to encoding functions.")
91
92 (defvar rfc2047-q-encoding-alist
93   '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
94      . "-A-Za-z0-9!*+/" )
95     ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
96     ;; Avoid using 8bit characters.
97     ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
98     ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
99   "Alist of header regexps and valid Q characters.")
100
101 ;;;
102 ;;; Functions for encoding RFC2047 messages
103 ;;;
104
105 (defun rfc2047-narrow-to-field ()
106   "Narrow the buffer to the header on the current line."
107   (beginning-of-line)
108   (narrow-to-region
109    (point)
110    (progn
111      (forward-line 1)
112      (if (re-search-forward "^[^ \n\t]" nil t)
113          (progn
114            (beginning-of-line)
115            (point))
116        (point-max))))
117   (goto-char (point-min)))
118
119 (defun rfc2047-encode-message-header ()
120   "Encode the message header according to `rfc2047-header-encoding-alist'.
121 Should be called narrowed to the head of the message."
122   (interactive "*")
123   (save-excursion
124     (goto-char (point-min))
125     (let (alist elem method)
126       (while (not (eobp))
127         (save-restriction
128           (rfc2047-narrow-to-field)
129           (if (not (rfc2047-encodable-p))
130               (prog1
131                 (if (and (eq (mm-body-7-or-8) '8bit)
132                          (mm-multibyte-p)
133                          (mm-coding-system-p
134                           (car message-posting-charset)))
135                     ;; 8 bit must be decoded.
136                     ;; Is message-posting-charset a coding system?
137                     (mm-encode-coding-region
138                      (point-min) (point-max)
139                      (car message-posting-charset)))
140                 ;; No encoding necessary, but folding is nice
141                 (rfc2047-fold-region (save-excursion
142                                        (goto-char (point-min))
143                                        (skip-chars-forward "^:")
144                                        (and (looking-at ": ")
145                                             (forward-char 2))
146                                        (point)) (point-max)))
147             ;; We found something that may perhaps be encoded.
148             (setq method nil
149                   alist rfc2047-header-encoding-alist)
150             (while (setq elem (pop alist))
151               (when (or (and (stringp (car elem))
152                              (looking-at (car elem)))
153                         (eq (car elem) t))
154                 (setq alist nil
155                       method (cdr elem))))
156             (cond
157              ((stringp method)
158               (rfc2047-encode-region (point-min) (point-max) method))
159              ((eq method 'mime)
160               (rfc2047-encode-region (point-min) (point-max)))
161              ((eq method 'default)
162               (if (and (featurep 'mule)
163                        (if (boundp 'default-enable-multibyte-characters)
164                            default-enable-multibyte-characters)
165                        mail-parse-charset)
166                   (mm-encode-coding-region (point-min) (point-max)
167                                            mail-parse-charset)))
168              ;; We get this when CC'ing messsages to newsgroups with
169              ;; 8-bit names.  The group name mail copy just get
170              ;; unconditionally encoded.  Previously, it would ask
171              ;; whether to encode, which was quite confusing for the
172              ;; user.  If the new behaviour is wrong, tell me. I have
173              ;; left the old code commented out below.
174              ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
175              ((null method)
176               (when (delq 'ascii 
177                           (mm-find-charset-region (point-min) (point-max)))
178                 (rfc2047-encode-region (point-min) (point-max))))
179 ;;;          ((null method)
180 ;;;           (and (delq 'ascii
181 ;;;                      (mm-find-charset-region (point-min)
182 ;;;                                              (point-max)))
183 ;;;                (if (or (message-options-get
184 ;;;                         'rfc2047-encode-message-header-encode-any)
185 ;;;                        (message-options-set
186 ;;;                         'rfc2047-encode-message-header-encode-any
187 ;;;                         (y-or-n-p
188 ;;;                          "Some texts are not encoded. Encode anyway?")))
189 ;;;                    (rfc2047-encode-region (point-min) (point-max))
190 ;;;                  (error "Cannot send unencoded text"))))
191              ((mm-coding-system-p method)
192               (if (and (featurep 'mule)
193                        (if (boundp 'default-enable-multibyte-characters)
194                            default-enable-multibyte-characters))
195                   (mm-encode-coding-region (point-min) (point-max) method)))
196              ;; Hm.
197              (t)))
198           (goto-char (point-max)))))))
199
200 ;; Fixme: This, and the require below may not be the Right Thing, but
201 ;; should be safe just before release.  -- fx 2001-02-08
202 (eval-when-compile (defvar message-posting-charset))
203
204 (defun rfc2047-encodable-p ()
205   "Return non-nil if any characters in current buffer need encoding in headers.
206 The buffer may be narrowed."
207   (require 'message)                    ; for message-posting-charset
208   (let ((charsets
209          (mapcar
210           'mm-mime-charset
211           (mm-find-charset-region (point-min) (point-max))))
212         (cs (list 'us-ascii (car message-posting-charset)))
213         found)
214     (while charsets
215       (unless (memq (pop charsets) cs)
216         (setq found t)))
217     found))
218
219 (defun rfc2047-dissect-region (b e &optional word-chars)
220   "Dissect the region between B and E into words."
221   (unless word-chars
222     ;; Anything except most CTLs, WSP
223     (setq word-chars "\010\012\014\041-\177"))
224   (let (mail-parse-mule-charset
225         words point current
226         result word)
227     (save-restriction
228       (narrow-to-region b e)
229       (goto-char (point-min))
230       (skip-chars-forward "\000-\177")
231       (while (not (eobp))
232         (setq point (point))
233         (skip-chars-backward word-chars b)
234         (unless (eq b (point))
235           (push (cons (buffer-substring b (point)) nil) words))
236         (setq b (point))
237         (goto-char point)
238         (setq current (mm-charset-after))
239         (forward-char 1)
240         (skip-chars-forward word-chars)
241         (while (and (not (eobp))
242                     (eq (mm-charset-after) current))
243           (forward-char 1)
244           (skip-chars-forward word-chars))
245         (unless (eq b (point))
246           (push (cons (buffer-substring b (point)) current) words))
247         (setq b (point))
248         (skip-chars-forward "\000-\177"))
249       (unless (eq b (point))
250         (push (cons (buffer-substring b (point)) nil) words)))
251     ;; merge adjacent words
252     (setq word (pop words))
253     (while word
254       (if (and (cdr word)
255                (caar words)
256                (not (cdar words))
257                (not (string-match "[^ \t]" (caar words))))
258           (if (eq (cdr (nth 1 words)) (cdr word))
259               (progn
260                 (setq word (cons (concat
261                                   (car (nth 1 words)) (caar words)
262                                   (car word))
263                                  (cdr word)))
264                 (pop words)
265                 (pop words))
266             (push (cons (concat (caar words) (car word)) (cdr word))
267                   result)
268             (pop words)
269             (setq word (pop words)))
270         (push word result)
271         (setq word (pop words))))
272     result))
273
274 (defun rfc2047-encode-region (b e &optional word-chars)
275   "Encode all encodable words in region B to E."
276   (let ((words (rfc2047-dissect-region b e word-chars)) word)
277     (save-restriction
278       (narrow-to-region b e)
279       (delete-region (point-min) (point-max))
280       (while (setq word (pop words))
281         (if (not (cdr word))
282             (insert (car word))
283           (rfc2047-fold-region (gnus-point-at-bol) (point))
284           (goto-char (point-max))
285           (if (> (- (point) (save-restriction
286                               (widen)
287                               (gnus-point-at-bol))) 76)
288               (insert "\n "))
289           ;; Insert blank between encoded words
290           (if (eq (char-before) ?=) (insert " "))
291           (rfc2047-encode (point)
292                           (progn (insert (car word)) (point))
293                           (cdr word))))
294       (rfc2047-fold-region (point-min) (point-max)))))
295
296 (defun rfc2047-encode-string (string &optional word-chars)
297   "Encode words in STRING."
298   (with-temp-buffer
299     (insert string)
300     (rfc2047-encode-region (point-min) (point-max) word-chars)
301     (buffer-string)))
302
303 (defun rfc2047-encode (b e charset)
304   "Encode the word in the region B to E with CHARSET."
305   (let* ((mime-charset (mm-mime-charset charset))
306          (cs (mm-charset-to-coding-system mime-charset))
307          (encoding (or (cdr (assq mime-charset
308                                   rfc2047-charset-encoding-alist))
309                        'B))
310          (start (concat
311                  "=?" (downcase (symbol-name mime-charset)) "?"
312                  (downcase (symbol-name encoding)) "?"))
313          (first t))
314     (save-restriction
315       (narrow-to-region b e)
316       (when (eq encoding 'B)
317         ;; break into lines before encoding
318         (goto-char (point-min))
319         (while (not (eobp))
320           (goto-char (min (point-max) (+ 15 (point))))
321           (unless (eobp)
322             (insert "\n"))))
323       (if (and (mm-multibyte-p)
324                (mm-coding-system-p cs))
325           (mm-encode-coding-region (point-min) (point-max) cs))
326       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
327                (point-min) (point-max))
328       (goto-char (point-min))
329       (while (not (eobp))
330         (unless first
331           (insert " "))
332         (setq first nil)
333         (insert start)
334         (end-of-line)
335         (insert "?=")
336         (forward-line 1)))))
337
338 (defun rfc2047-fold-region (b e)
339   "Fold long lines in region B to E."
340   (save-restriction
341     (narrow-to-region b e)
342     (goto-char (point-min))
343     (let ((break nil)
344           (qword-break nil)
345           (bol (save-restriction
346                  (widen)
347                  (gnus-point-at-bol))))
348       (while (not (eobp))
349         (when (and (or break qword-break) (> (- (point) bol) 76))
350           (goto-char (or break qword-break))
351           (setq break nil
352                 qword-break nil)
353           (if (looking-at "[ \t]")
354               (insert "\n")
355             (insert "\n "))
356           (setq bol (1- (point)))
357           ;; Don't break before the first non-LWSP characters.
358           (skip-chars-forward " \t")
359           (unless (eobp) (forward-char 1)))
360         (cond
361          ((eq (char-after) ?\n)
362           (forward-char 1)
363           (setq bol (point)
364                 break nil
365                 qword-break nil)
366           (skip-chars-forward " \t")
367           (unless (or (eobp) (eq (char-after) ?\n))
368             (forward-char 1)))
369          ((eq (char-after) ?\r)
370           (forward-char 1))
371          ((memq (char-after) '(?  ?\t))
372           (skip-chars-forward " \t")
373           (setq break (1- (point))))
374          ((not break)
375           (if (not (looking-at "=\\?[^=]"))
376               (if (eq (char-after) ?=)
377                   (forward-char 1)
378                 (skip-chars-forward "^ \t\n\r="))
379             (setq qword-break (point))
380             (skip-chars-forward "^ \t\n\r")))
381          (t
382           (skip-chars-forward "^ \t\n\r"))))
383       (when (and (or break qword-break) (> (- (point) bol) 76))
384         (goto-char (or break qword-break))
385         (setq break nil
386               qword-break nil)
387           (if (looking-at "[ \t]")
388               (insert "\n")
389             (insert "\n "))
390         (setq bol (1- (point)))
391         ;; Don't break before the first non-LWSP characters.
392         (skip-chars-forward " \t")
393         (unless (eobp) (forward-char 1))))))
394
395 (defun rfc2047-unfold-region (b e)
396   "Unfold lines in region B to E."
397   (save-restriction
398     (narrow-to-region b e)
399     (goto-char (point-min))
400     (let ((bol (save-restriction
401                  (widen)
402                  (gnus-point-at-bol)))
403           (eol (gnus-point-at-eol))
404           leading)
405       (forward-line 1)
406       (while (not (eobp))
407         (looking-at "[ \t]*")
408         (setq leading (- (match-end 0) (match-beginning 0)))
409         (if (< (- (gnus-point-at-eol) bol leading) 76)
410             (progn
411               (goto-char eol)
412               (delete-region eol (progn
413                                    (skip-chars-forward " \t\n\r")
414                                    (1- (point)))))
415           (setq bol (gnus-point-at-bol)))
416         (setq eol (gnus-point-at-eol))
417         (forward-line 1)))))
418
419 (defun rfc2047-b-encode-region (b e)
420   "Base64-encode the header contained in region B to E."
421   (save-restriction
422     (narrow-to-region (goto-char b) e)
423     (while (not (eobp))
424       (base64-encode-region (point) (progn (end-of-line) (point)) t)
425       (if (and (bolp) (eolp))
426           (delete-backward-char 1))
427       (forward-line))))
428
429 (defun rfc2047-q-encode-region (b e)
430   "Quoted-printable-encode the header in region B to E."
431   (save-excursion
432     (save-restriction
433       (narrow-to-region (goto-char b) e)
434       (let ((alist rfc2047-q-encoding-alist)
435             (bol (save-restriction
436                    (widen)
437                    (gnus-point-at-bol))))
438         (while alist
439           (when (looking-at (caar alist))
440             (mm-with-unibyte-current-buffer-mule4
441               (quoted-printable-encode-region
442                (point-min) (point-max) nil (cdar alist)))
443             (subst-char-in-region (point-min) (point-max) ?  ?_)
444             (setq alist nil))
445           (pop alist))
446         ;; The size of QP encapsulation is about 20, so set limit to
447         ;; 56=76-20.
448         (unless (< (- (point-max) (point-min)) 56)
449           ;; Don't break if it could fit in one line.
450           ;; Let rfc2047-encode-region break it later.
451           (goto-char (1+ (point-min)))
452           (while (and (not (bobp)) (not (eobp)))
453             (goto-char (min (point-max) (+ 56 bol)))
454             (search-backward "=" (- (point) 2) t)
455             (unless (or (bobp) (eobp))
456               (insert "\n")
457               (setq bol (point)))))))))
458
459 ;;;
460 ;;; Functions for decoding RFC2047 messages
461 ;;;
462
463 (defvar rfc2047-encoded-word-regexp
464   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?=")
465
466 (defun rfc2047-decode-region (start end)
467   "Decode MIME-encoded words in region between START and END."
468   (interactive "r")
469   (let ((case-fold-search t)
470         b e)
471     (save-excursion
472       (save-restriction
473         (narrow-to-region start end)
474         (goto-char (point-min))
475         ;; Remove whitespace between encoded words.
476         (while (re-search-forward
477                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
478                         "\\(\n?[ \t]\\)+"
479                         "\\(" rfc2047-encoded-word-regexp "\\)")
480                 nil t)
481           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
482         ;; Decode the encoded words.
483         (setq b (goto-char (point-min)))
484         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
485           (setq e (match-beginning 0))
486           (insert (rfc2047-parse-and-decode
487                    (prog1
488                        (match-string 0)
489                      (delete-region (match-beginning 0) (match-end 0)))))
490           (when (and (mm-multibyte-p)
491                      mail-parse-charset
492                      (not (eq mail-parse-charset 'gnus-decoded)))
493             (mm-decode-coding-region b e mail-parse-charset))
494           (setq b (point)))
495         (when (and (mm-multibyte-p)
496                    mail-parse-charset
497                    (not (eq mail-parse-charset 'us-ascii))
498                    (not (eq mail-parse-charset 'gnus-decoded)))
499           (mm-decode-coding-region b (point-max) mail-parse-charset))
500         (rfc2047-unfold-region (point-min) (point-max))))))
501
502 (defun rfc2047-decode-string (string)
503   "Decode the quoted-printable-encoded STRING and return the results."
504   (let ((m (mm-multibyte-p)))
505     (with-temp-buffer
506       (when m
507         (mm-enable-multibyte))
508       (insert string)
509       (inline
510         (rfc2047-decode-region (point-min) (point-max)))
511       (buffer-string))))
512
513 (defun rfc2047-parse-and-decode (word)
514   "Decode WORD and return it if it is an encoded word.
515 Return WORD if not."
516   (if (not (string-match rfc2047-encoded-word-regexp word))
517       word
518     (or
519      (condition-case nil
520          (rfc2047-decode
521           (match-string 1 word)
522           (upcase (match-string 2 word))
523           (match-string 3 word))
524        (error word))
525      word)))
526
527 (defun rfc2047-pad-base64 (string)
528   "Pad STRING to quartets."
529   ;; Be more liberal to accept buggy base64 strings. If
530   ;; base64-decode-string accepts buggy strings, this function could
531   ;; be aliased to identity.
532   (case (mod (length string) 4)
533     (0 string)
534     (1 string) ;; Error, don't pad it.
535     (2 (concat string "=="))
536     (3 (concat string "="))))
537
538 (defun rfc2047-decode (charset encoding string)
539   "Decode STRING from the given MIME CHARSET in the given ENCODING.
540 Valid ENCODINGs are \"B\" and \"Q\".
541 If your Emacs implementation can't decode CHARSET, return nil."
542   (if (stringp charset)
543       (setq charset (intern (downcase charset))))
544   (if (or (not charset)
545           (eq 'gnus-all mail-parse-ignored-charsets)
546           (memq 'gnus-all mail-parse-ignored-charsets)
547           (memq charset mail-parse-ignored-charsets))
548       (setq charset mail-parse-charset))
549   (let ((cs (mm-charset-to-coding-system charset)))
550     (if (and (not cs) charset
551              (listp mail-parse-ignored-charsets)
552              (memq 'gnus-unknown mail-parse-ignored-charsets))
553         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
554     (when cs
555       (when (and (eq cs 'ascii)
556                  mail-parse-charset)
557         (setq cs mail-parse-charset))
558       (mm-with-unibyte-current-buffer-mule4
559         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
560         (mm-decode-coding-string
561          (cond
562           ((equal "B" encoding)
563            (base64-decode-string
564             (rfc2047-pad-base64 string)))
565           ((equal "Q" encoding)
566            (quoted-printable-decode-string
567             (mm-replace-chars-in-string string ?_ ? )))
568           (t (error "Invalid encoding: %s" encoding)))
569          cs)))))
570
571 (provide 'rfc2047)
572
573 ;;; rfc2047.el ends here