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