2001-02-13 20: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. Some versions of Emacs has bug!
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               (if (and (eq (mm-body-7-or-8) '8bit)
131                        (mm-multibyte-p)
132                        (mm-coding-system-p
133                         (car message-posting-charset)))
134                        ;; 8 bit must be decoded.
135                        ;; Is message-posting-charset a coding system?
136                        (mm-encode-coding-region
137                         (point-min) (point-max)
138                         (car message-posting-charset)))
139             ;; We found something that may perhaps be encoded.
140             (setq method nil
141                   alist rfc2047-header-encoding-alist)
142             (while (setq elem (pop alist))
143               (when (or (and (stringp (car elem))
144                              (looking-at (car elem)))
145                         (eq (car elem) t))
146                 (setq alist nil
147                       method (cdr elem))))
148             (cond
149              ((stringp method)
150               (rfc2047-encode-region (point-min) (point-max) method))
151              ((eq method 'mime)
152               (rfc2047-encode-region (point-min) (point-max)))
153              ((eq method 'default)
154               (if (and (featurep 'mule)
155                        (if (boundp 'default-enable-multibyte-characters)
156                            default-enable-multibyte-characters)
157                        mail-parse-charset)
158                   (mm-encode-coding-region (point-min) (point-max)
159                                            mail-parse-charset)))
160              ((null method)
161               (and (delq 'ascii
162                          (mm-find-charset-region (point-min)
163                                                  (point-max)))
164                    (if (or (message-options-get
165                             'rfc2047-encode-message-header-encode-any)
166                            (message-options-set
167                             'rfc2047-encode-message-header-encode-any
168                             (y-or-n-p
169                              "Some texts are not encoded. Encode anyway?")))
170                        (rfc2047-encode-region (point-min) (point-max))
171                      (error "Cannot send unencoded text."))))
172              ((mm-coding-system-p method)
173               (if (and (featurep 'mule)
174                        (if (boundp 'default-enable-multibyte-characters)
175                            default-enable-multibyte-characters))
176                   (mm-encode-coding-region (point-min) (point-max) method)))
177              ;; Hm.
178              (t)))
179           (goto-char (point-max)))))))
180
181 (defun rfc2047-encodable-p ()
182   "Return non-nil if any characters in current buffer need encoding in headers.
183 The buffer may be narrowed."
184   (let ((charsets
185          (mapcar
186           'mm-mime-charset
187           (mm-find-charset-region (point-min) (point-max))))
188         (cs (list 'us-ascii (car message-posting-charset)))
189         found)
190     (while charsets
191       (unless (memq (pop charsets) cs)
192         (setq found t)))
193     found))
194
195 (defun rfc2047-dissect-region (b e &optional word-chars)
196   "Dissect the region between B and E into words."
197   (unless word-chars
198     ;; Anything except most CTLs, WSP
199     (setq word-chars "\010\012\014\041-\177"))
200   (let (mail-parse-mule-charset
201         words point current
202         result word)
203     (save-restriction
204       (narrow-to-region b e)
205       (goto-char (point-min))
206       (skip-chars-forward "\000-\177")
207       (while (not (eobp))
208         (setq point (point))
209         (skip-chars-backward word-chars b)
210         (unless (eq b (point))
211           (push (cons (buffer-substring b (point)) nil) words))
212         (setq b (point))
213         (goto-char point)
214         (setq current (mm-charset-after))
215         (forward-char 1)
216         (skip-chars-forward word-chars)
217         (while (and (not (eobp))
218                     (eq (mm-charset-after) current))
219           (forward-char 1)
220           (skip-chars-forward word-chars))
221         (unless (eq b (point))
222           (push (cons (buffer-substring b (point)) current) words))
223         (setq b (point))
224         (skip-chars-forward "\000-\177"))
225       (unless (eq b (point))
226         (push (cons (buffer-substring b (point)) nil) words)))
227     ;; merge adjacent words
228     (setq word (pop words))
229     (while word
230       (if (and (cdr word)
231                (caar words)
232                (not (cdar words))
233                (not (string-match "[^ \t]" (caar words))))
234           (if (eq (cdr (nth 1 words)) (cdr word))
235               (progn
236                 (setq word (cons (concat
237                                   (car (nth 1 words)) (caar words)
238                                   (car word))
239                                  (cdr word)))
240                 (pop words)
241                 (pop words))
242             (push (cons (concat (caar words) (car word)) (cdr word))
243                   result)
244             (pop words)
245             (setq word (pop words)))
246         (push word result)
247         (setq word (pop words))))
248     result))
249
250 (defun rfc2047-encode-region (b e &optional word-chars)
251   "Encode all encodable words in region."
252   (let ((words (rfc2047-dissect-region b e word-chars)) word)
253     (save-restriction
254       (narrow-to-region b e)
255       (delete-region (point-min) (point-max))
256       (while (setq word (pop words))
257         (if (not (cdr word))
258             (insert (car word))
259           (rfc2047-fold-region (gnus-point-at-bol) (point))
260           (goto-char (point-max))
261           (if (> (- (point) (save-restriction
262                               (widen)
263                               (gnus-point-at-bol))) 76)
264               (insert "\n "))
265           ;; Insert blank between encoded words
266           (if (eq (char-before) ?=) (insert " "))
267           (rfc2047-encode (point)
268                           (progn (insert (car word)) (point))
269                           (cdr word))))
270       (rfc2047-fold-region (point-min) (point-max)))))
271
272 (defun rfc2047-encode-string (string &optional word-chars)
273   "Encode words in STRING."
274   (with-temp-buffer
275     (insert string)
276     (rfc2047-encode-region (point-min) (point-max) word-chars)
277     (buffer-string)))
278
279 (defun rfc2047-encode (b e charset)
280   "Encode the word in the region B to E with CHARSET."
281   (let* ((mime-charset (mm-mime-charset charset))
282          (cs (mm-charset-to-coding-system mime-charset))
283          (encoding (or (cdr (assq mime-charset
284                                   rfc2047-charset-encoding-alist))
285                        'B))
286          (start (concat
287                  "=?" (downcase (symbol-name mime-charset)) "?"
288                  (downcase (symbol-name encoding)) "?"))
289          (first t))
290     (save-restriction
291       (narrow-to-region b e)
292       (when (eq encoding 'B)
293         ;; break into lines before encoding
294         (goto-char (point-min))
295         (while (not (eobp))
296           (goto-char (min (point-max) (+ 15 (point))))
297           (unless (eobp)
298             (insert "\n"))))
299       (if (and (mm-multibyte-p)
300                (mm-coding-system-p cs))
301           (mm-encode-coding-region (point-min) (point-max) cs))
302       (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
303                (point-min) (point-max))
304       (goto-char (point-min))
305       (while (not (eobp))
306         (unless first
307           (insert " "))
308         (setq first nil)
309         (insert start)
310         (end-of-line)
311         (insert "?=")
312         (forward-line 1)))))
313
314 (defun rfc2047-fold-region (b e)
315   "Fold long lines in the region."
316   (save-restriction
317     (narrow-to-region b e)
318     (goto-char (point-min))
319     (let ((break nil)
320           (qword-break nil)
321           (bol (save-restriction
322                  (widen)
323                  (gnus-point-at-bol))))
324       (while (not (eobp))
325         (when (and (or break qword-break) (> (- (point) bol) 76))
326           (goto-char (or break qword-break))
327           (setq break nil
328                 qword-break nil)
329           (if (looking-at " \t")
330               (insert "\n")
331             (insert "\n "))
332           (setq bol (1- (point)))
333           ;; Don't break before the first non-LWSP characters.
334           (skip-chars-forward " \t")
335           (forward-char 1))
336         (cond
337          ((eq (char-after) ?\n)
338           (forward-char 1)
339           (setq bol (point)
340                 break nil
341                 qword-break nil)
342           (skip-chars-forward " \t")
343           (unless (or (eobp) (eq (char-after) ?\n))
344             (forward-char 1)))
345          ((eq (char-after) ?\r)
346           (forward-char 1))
347          ((memq (char-after) '(?  ?\t))
348           (skip-chars-forward " \t")
349           (setq break (1- (point))))
350          ((not break)
351           (if (not (looking-at "=\\?[^=]"))
352               (if (eq (char-after) ?=)
353                   (forward-char 1)
354                 (skip-chars-forward "^ \t\n\r="))
355             (setq qword-break (point))
356             (skip-chars-forward "^ \t\n\r")))
357          (t
358           (skip-chars-forward "^ \t\n\r"))))
359       (when (and (or break qword-break) (> (- (point) bol) 76))
360         (goto-char (or break qword-break))
361         (setq break nil
362               qword-break nil)
363           (if (looking-at " \t")
364               (insert "\n")
365             (insert "\n "))
366         (setq bol (1- (point)))
367         ;; Don't break before the first non-LWSP characters.
368         (skip-chars-forward " \t")
369         (forward-char 1)))))
370
371 (defun rfc2047-unfold-region (b e)
372   "Unfold lines in the region."
373   (save-restriction
374     (narrow-to-region b e)
375     (goto-char (point-min))
376     (let ((bol (save-restriction
377                  (widen)
378                  (gnus-point-at-bol)))
379           (eol (gnus-point-at-eol))
380           leading)
381       (forward-line 1)
382       (while (not (eobp))
383         (looking-at "[ \t]*")
384         (setq leading (- (match-end 0) (match-beginning 0)))
385         (if (< (- (gnus-point-at-eol) bol leading) 76)
386             (progn
387               (goto-char eol)
388               (delete-region eol (progn
389                                    (skip-chars-forward "[ \t\n\r]+")
390                                    (1- (point)))))
391           (setq bol (gnus-point-at-bol)))
392         (setq eol (gnus-point-at-eol))
393         (forward-line 1)))))
394
395 (defun rfc2047-b-encode-region (b e)
396   "Base64-encode the header contained in region B to E."
397   (save-restriction
398     (narrow-to-region (goto-char b) e)
399     (while (not (eobp))
400       (base64-encode-region (point) (progn (end-of-line) (point)) t)
401       (if (and (bolp) (eolp))
402           (delete-backward-char 1))
403       (forward-line))))
404
405 (defun rfc2047-q-encode-region (b e)
406   "Quoted-printable-encode the header in region B to E."
407   (save-excursion
408     (save-restriction
409       (narrow-to-region (goto-char b) e)
410       (let ((alist rfc2047-q-encoding-alist)
411             (bol (save-restriction
412                    (widen)
413                    (gnus-point-at-bol))))
414         (while alist
415           (when (looking-at (caar alist))
416             (mm-with-unibyte-current-buffer-mule4
417               (quoted-printable-encode-region 
418                (point-min) (point-max) nil (cdar alist)))
419             (subst-char-in-region (point-min) (point-max) ?  ?_)
420             (setq alist nil))
421           (pop alist))
422         ;; The size of QP encapsulation is about 20, so set limit to
423         ;; 56=76-20.
424         (unless (< (- (point-max) (point-min)) 56)
425           ;; Don't break if it could fit in one line.
426           ;; Let rfc2047-encode-region break it later.
427           (goto-char (1+ (point-min)))
428           (while (and (not (bobp)) (not (eobp)))
429             (goto-char (min (point-max) (+ 56 bol)))
430             (search-backward "=" (- (point) 2) t)
431             (unless (or (bobp) (eobp))
432               (insert "\n")
433               (setq bol (point)))))))))
434
435 ;;;
436 ;;; Functions for decoding RFC2047 messages
437 ;;;
438
439 (defvar rfc2047-encoded-word-regexp
440   "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]*\\)\\?=")
441
442 (defun rfc2047-decode-region (start end)
443   "Decode MIME-encoded words in region between START and END."
444   (interactive "r")
445   (let ((case-fold-search t)
446         b e)
447     (save-excursion
448       (save-restriction
449         (narrow-to-region start end)
450         (goto-char (point-min))
451         ;; Remove whitespace between encoded words.
452         (while (re-search-forward
453                 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
454                         "\\(\n?[ \t]\\)+"
455                         "\\(" rfc2047-encoded-word-regexp "\\)")
456                 nil t)
457           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
458         ;; Decode the encoded words.
459         (setq b (goto-char (point-min)))
460         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
461           (setq e (match-beginning 0))
462           (insert (rfc2047-parse-and-decode
463                    (prog1
464                        (match-string 0)
465                      (delete-region (match-beginning 0) (match-end 0)))))
466           (when (and (mm-multibyte-p)
467                      mail-parse-charset
468                      (not (eq mail-parse-charset 'gnus-decoded)))
469             (mm-decode-coding-region b e mail-parse-charset))
470           (setq b (point)))
471         (when (and (mm-multibyte-p)
472                    mail-parse-charset
473                    (not (eq mail-parse-charset 'us-ascii))
474                    (not (eq mail-parse-charset 'gnus-decoded)))
475           (mm-decode-coding-region b (point-max) mail-parse-charset))
476         (rfc2047-unfold-region (point-min) (point-max))))))
477
478 (defun rfc2047-decode-string (string)
479   "Decode the quoted-printable-encoded STRING and return the results."
480   (let ((m (mm-multibyte-p)))
481     (with-temp-buffer
482       (when m
483         (mm-enable-multibyte))
484       (insert string)
485       (inline
486         (rfc2047-decode-region (point-min) (point-max)))
487       (buffer-string))))
488
489 (defun rfc2047-parse-and-decode (word)
490   "Decode WORD and return it if it is an encoded word.
491 Return WORD if not."
492   (if (not (string-match rfc2047-encoded-word-regexp word))
493       word
494     (or
495      (condition-case nil
496          (rfc2047-decode
497           (match-string 1 word)
498           (upcase (match-string 2 word))
499           (match-string 3 word))
500        (error word))
501      word)))
502
503 (defun rfc2047-pad-base64 (string)
504   "Pad STRING to quartets."
505   ;; Be more liberal to accept buggy base64 strings. If
506   ;; base64-decode-string accepts buggy strings, this function could
507   ;; be aliased to identity.
508   (case (mod (length string) 4)
509     (0 string)
510     (1 string) ;; Error, don't pad it.
511     (2 (concat string "=="))
512     (3 (concat string "="))))
513
514 (defun rfc2047-decode (charset encoding string)
515   "Decode STRING from the given MIME CHARSET in the given ENCODING.
516 Valid ENCODINGs are \"B\" and \"Q\".
517 If your Emacs implementation can't decode CHARSET, return nil."
518   (if (stringp charset)
519       (setq charset (intern (downcase charset))))
520   (if (or (not charset)
521           (eq 'gnus-all mail-parse-ignored-charsets)
522           (memq 'gnus-all mail-parse-ignored-charsets)
523           (memq charset mail-parse-ignored-charsets))
524       (setq charset mail-parse-charset))
525   (let ((cs (mm-charset-to-coding-system charset)))
526     (if (and (not cs) charset
527              (listp mail-parse-ignored-charsets)
528              (memq 'gnus-unknown mail-parse-ignored-charsets))
529         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
530     (when cs
531       (when (and (eq cs 'ascii)
532                  mail-parse-charset)
533         (setq cs mail-parse-charset))
534       (mm-with-unibyte-current-buffer-mule4
535         ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
536         (mm-decode-coding-string
537          (cond
538           ((equal "B" encoding)
539            (base64-decode-string
540             (rfc2047-pad-base64 string)))
541           ((equal "Q" encoding)
542            (quoted-printable-decode-string
543             (mm-replace-chars-in-string string ?_ ? )))
544           (t (error "Invalid encoding: %s" encoding)))
545          cs)))))
546
547 (provide 'rfc2047)
548
549 ;;; rfc2047.el ends here