Merge from emacs--devo--0
[gnus] / lisp / rfc2047.el
1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
24
25 ;;; Commentary:
26
27 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
28 ;; Three:  Message Header Extensions for Non-ASCII Text".
29
30 ;;; Code:
31
32 (eval-when-compile
33   (require 'cl))
34 (defvar message-posting-charset)
35
36 (require 'qp)
37 (require 'mm-util)
38 (require 'ietf-drums)
39 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
40 (require 'mail-prsvr)
41 (require 'rfc2045) ;; rfc2045-encode-string
42 (autoload 'mm-body-7-or-8 "mm-bodies")
43
44 (defvar rfc2047-header-encoding-alist
45   '(("Newsgroups" . nil)
46     ("Followup-To" . nil)
47     ("Message-ID" . nil)
48     ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|\\(In-\\)?Reply-To\\|Sender\
49 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
50     (t . mime))
51   "*Header/encoding method alist.
52 The list is traversed sequentially.  The keys can either be
53 header regexps or t.
54
55 The values can be:
56
57 1) nil, in which case no encoding is done;
58 2) `mime', in which case the header will be encoded according to RFC2047;
59 3) `address-mime', like `mime', but takes account of the rules for address
60    fields (where quoted strings and comments must be treated separately);
61 4) a charset, in which case it will be encoded as that charset;
62 5) `default', in which case the field will be encoded as the rest
63    of the article.")
64
65 (defvar rfc2047-charset-encoding-alist
66   '((us-ascii . nil)
67     (iso-8859-1 . Q)
68     (iso-8859-2 . Q)
69     (iso-8859-3 . Q)
70     (iso-8859-4 . Q)
71     (iso-8859-5 . B)
72     (koi8-r . B)
73     (iso-8859-7 . B)
74     (iso-8859-8 . B)
75     (iso-8859-9 . Q)
76     (iso-8859-14 . Q)
77     (iso-8859-15 . Q)
78     (iso-2022-jp . B)
79     (iso-2022-kr . B)
80     (gb2312 . B)
81     (gbk . B)
82     (gb18030 . B)
83     (big5 . B)
84     (cn-big5 . B)
85     (cn-gb . B)
86     (cn-gb-2312 . B)
87     (euc-kr . B)
88     (iso-2022-jp-2 . B)
89     (iso-2022-int-1 . B)
90     (viscii . Q))
91   "Alist of MIME charsets to RFC2047 encodings.
92 Valid encodings are nil, `Q' and `B'.  These indicate binary (no) encoding,
93 quoted-printable and base64 respectively.")
94
95 (defvar rfc2047-encode-function-alist
96   '((Q . rfc2047-q-encode-string)
97     (B . rfc2047-b-encode-string)
98     (nil . identity))
99   "Alist of RFC2047 encodings to encoding functions.")
100
101 (defvar rfc2047-encode-encoded-words t
102   "Whether encoded words should be encoded again.")
103
104 (defvar rfc2047-allow-irregular-q-encoded-words t
105   "*Whether to decode irregular Q-encoded words.")
106
107 (eval-and-compile ;; Necessary to hard code them in `rfc2047-decode-region'.
108   (defconst rfc2047-encoded-word-regexp
109     "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
110 \\(B\\?[+/0-9A-Za-z]*=*\
111 \\|Q\\?[ ->@-~]*\
112 \\)\\?="
113     "Regexp that matches encoded word."
114     ;; The patterns for the B encoding and the Q encoding, i.e. the ones
115     ;; beginning with "B" and "Q" respectively, are restricted into only
116     ;; the characters that those encodings may generally use.
117     )
118   (defconst rfc2047-encoded-word-regexp-loose
119     "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\\?\
120 \\(B\\?[+/0-9A-Za-z]*=*\
121 \\|Q\\?\\(?:\\?+[ -<>@-~]\\)?\\(?:[ ->@-~]+\\?+[ -<>@-~]\\)*[ ->@-~]*\\?*\
122 \\)\\?="
123     "Regexp that matches encoded word allowing loose Q encoding."
124     ;; The pattern for the Q encoding, i.e. the one beginning with "Q",
125     ;; is similar to:
126     ;; "Q\\?\\(\\?+[^\n=?]\\)?\\([^\n?]+\\?+[^\n=?]\\)*[^\n?]*\\?*"
127     ;;      <--------1-------><----------2,3----------><--4--><-5->
128     ;; They mean:
129     ;; 1. After "Q?", allow "?"s that follow a character other than "=".
130     ;; 2. Allow "=" after "Q?"; it isn't regarded as the terminator.
131     ;; 3. In the middle of an encoded word, allow "?"s that follow a
132     ;;    character other than "=".
133     ;; 4. Allow any characters other than "?" in the middle of an
134     ;;    encoded word.
135     ;; 5. At the end, allow "?"s.
136     ))
137
138 ;;;
139 ;;; Functions for encoding RFC2047 messages
140 ;;;
141
142 (defun rfc2047-qp-or-base64 ()
143   "Return the type with which to encode the buffer.
144 This is either `base64' or `quoted-printable'."
145   (save-excursion
146     (let ((limit (min (point-max) (+ 2000 (point-min))))
147           (n8bit 0))
148       (goto-char (point-min))
149       (skip-chars-forward "\x20-\x7f\r\n\t" limit)
150       (while (< (point) limit)
151         (incf n8bit)
152         (forward-char 1)
153         (skip-chars-forward "\x20-\x7f\r\n\t" limit))
154       (if (or (< (* 6 n8bit) (- limit (point-min)))
155               ;; Don't base64, say, a short line with a single
156               ;; non-ASCII char when splitting parts by charset.
157               (= n8bit 1))
158           'quoted-printable
159         'base64))))
160
161 (defun rfc2047-narrow-to-field ()
162   "Narrow the buffer to the header on the current line."
163   (beginning-of-line)
164   (narrow-to-region
165    (point)
166    (progn
167      (forward-line 1)
168      (if (re-search-forward "^[^ \n\t]" nil t)
169          (point-at-bol)
170        (point-max))))
171   (goto-char (point-min)))
172
173 (defun rfc2047-field-value ()
174   "Return the value of the field at point."
175   (save-excursion
176     (save-restriction
177       (rfc2047-narrow-to-field)
178       (re-search-forward ":[ \t\n]*" nil t)
179       (buffer-substring-no-properties (point) (point-max)))))
180
181 (defun rfc2047-quote-special-characters-in-quoted-strings (&optional
182                                                            encodable-regexp)
183   "Quote special characters with `\\'s in quoted strings.
184 Quoting will not be done in a quoted string if it contains characters
185 matching ENCODABLE-REGEXP or it is within parentheses."
186   (goto-char (point-min))
187   (let ((tspecials (concat "[" ietf-drums-tspecials "]"))
188         (start (point))
189         beg end)
190     (with-syntax-table (standard-syntax-table)
191       (while (not (eobp))
192         (if (ignore-errors
193               (forward-list 1)
194               (eq (char-before) ?\)))
195             (forward-list -1)
196           (goto-char (point-max)))
197         (save-restriction
198           (narrow-to-region start (point))
199           (goto-char start)
200           (while (search-forward "\"" nil t)
201             (setq beg (match-beginning 0))
202             (unless (eq (char-before beg) ?\\)
203               (goto-char beg)
204               (setq beg (1+ beg))
205               (condition-case nil
206                   (progn
207                     (forward-sexp)
208                     (setq end (1- (point)))
209                     (goto-char beg)
210                     (if (and encodable-regexp
211                              (re-search-forward encodable-regexp end t))
212                         (goto-char (1+ end))
213                       (save-restriction
214                         (narrow-to-region beg end)
215                         (while (re-search-forward tspecials nil 'move)
216                           (if (eq (char-before) ?\\)
217                               (if (looking-at tspecials) ;; Already quoted.
218                                   (forward-char)
219                                 (insert "\\"))
220                             (goto-char (match-beginning 0))
221                             (insert "\\")
222                             (forward-char))))
223                       (forward-char)))
224                 (error
225                  (goto-char beg)))))
226           (goto-char (point-max)))
227         (forward-list 1)
228         (setq start (point))))))
229
230 (defvar rfc2047-encoding-type 'address-mime
231   "The type of encoding done by `rfc2047-encode-region'.
232 This should be dynamically bound around calls to
233 `rfc2047-encode-region' to either `mime' or `address-mime'.  See
234 `rfc2047-header-encoding-alist', for definitions.")
235
236 (defun rfc2047-encode-message-header ()
237   "Encode the message header according to `rfc2047-header-encoding-alist'.
238 Should be called narrowed to the head of the message."
239   (interactive "*")
240   (save-excursion
241     (goto-char (point-min))
242     (let (alist elem method)
243       (while (not (eobp))
244         (save-restriction
245           (rfc2047-narrow-to-field)
246           (setq method nil
247                 alist rfc2047-header-encoding-alist)
248           (while (setq elem (pop alist))
249             (when (or (and (stringp (car elem))
250                            (looking-at (car elem)))
251                       (eq (car elem) t))
252               (setq alist nil
253                     method (cdr elem))))
254           (if (not (rfc2047-encodable-p))
255               (prog2
256                   (when (eq method 'address-mime)
257                     (rfc2047-quote-special-characters-in-quoted-strings))
258                   (if (and (eq (mm-body-7-or-8) '8bit)
259                            (mm-multibyte-p)
260                            (mm-coding-system-p
261                             (car message-posting-charset)))
262                       ;; 8 bit must be decoded.
263                       (mm-encode-coding-region
264                        (point-min) (point-max)
265                        (mm-charset-to-coding-system
266                         (car message-posting-charset))))
267                 ;; No encoding necessary, but folding is nice
268                 (when nil
269                   (rfc2047-fold-region
270                    (save-excursion
271                      (goto-char (point-min))
272                      (skip-chars-forward "^:")
273                      (when (looking-at ": ")
274                        (forward-char 2))
275                      (point))
276                    (point-max))))
277             ;; We found something that may perhaps be encoded.
278             (re-search-forward "^[^:]+: *" nil t)
279             (cond
280              ((eq method 'address-mime)
281               (rfc2047-encode-region (point) (point-max)))
282              ((eq method 'mime)
283               (let ((rfc2047-encoding-type 'mime))
284                 (rfc2047-encode-region (point) (point-max))))
285              ((eq method 'default)
286               (if (and (featurep 'mule)
287                        (if (boundp 'default-enable-multibyte-characters)
288                            default-enable-multibyte-characters)
289                        mail-parse-charset)
290                   (mm-encode-coding-region (point) (point-max)
291                                            mail-parse-charset)))
292              ;; We get this when CC'ing messsages to newsgroups with
293              ;; 8-bit names.  The group name mail copy just got
294              ;; unconditionally encoded.  Previously, it would ask
295              ;; whether to encode, which was quite confusing for the
296              ;; user.  If the new behaviour is wrong, tell me. I have
297              ;; left the old code commented out below.
298              ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
299              ;; Modified by Dave Love, with the commented-out code changed
300              ;; in accordance with changes elsewhere.
301              ((null method)
302               (rfc2047-encode-region (point) (point-max)))
303 ;;;          ((null method)
304 ;;;           (if (or (message-options-get
305 ;;;                    'rfc2047-encode-message-header-encode-any)
306 ;;;                   (message-options-set
307 ;;;                    'rfc2047-encode-message-header-encode-any
308 ;;;                    (y-or-n-p
309 ;;;                     "Some texts are not encoded. Encode anyway?")))
310 ;;;               (rfc2047-encode-region (point-min) (point-max))
311 ;;;             (error "Cannot send unencoded text")))
312              ((mm-coding-system-p method)
313               (if (or (and (featurep 'mule)
314                            (if (boundp 'default-enable-multibyte-characters)
315                                default-enable-multibyte-characters))
316                       (featurep 'file-coding))
317                   (mm-encode-coding-region (point) (point-max) method)))
318              ;; Hm.
319              (t)))
320           (goto-char (point-max)))))))
321
322 ;; Fixme: This, and the require below may not be the Right Thing, but
323 ;; should be safe just before release.  -- fx 2001-02-08
324
325 (defun rfc2047-encodable-p ()
326   "Return non-nil if any characters in current buffer need encoding in headers.
327 The buffer may be narrowed."
328   (require 'message)                    ; for message-posting-charset
329   (let ((charsets
330          (mm-find-mime-charset-region (point-min) (point-max))))
331     (goto-char (point-min))
332     (or (and rfc2047-encode-encoded-words
333              (prog1
334                  (re-search-forward rfc2047-encoded-word-regexp nil t)
335                (goto-char (point-min))))
336         (and charsets
337              (not (equal charsets (list (car message-posting-charset))))))))
338
339 ;; Use this syntax table when parsing into regions that may need
340 ;; encoding.  Double quotes are string delimiters, backslash is
341 ;; character quoting, and all other RFC 2822 special characters are
342 ;; treated as punctuation so we can use forward-sexp/forward-word to
343 ;; skip to the end of regions appropriately.  Nb. ietf-drums does
344 ;; things differently.
345 (defconst rfc2047-syntax-table
346   ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
347   (let ((table (make-syntax-table)))
348     ;; The following is done to work for setting all elements of the table
349     ;; in Emacs 21-23 and XEmacs; it appears to be the cleanest way.
350     ;; Play safe and don't assume the form of the word syntax entry --
351     ;; copy it from ?a.
352     (if (fboundp 'set-char-table-range) ; Emacs
353         (funcall (intern "set-char-table-range")
354                  table t (aref (standard-syntax-table) ?a))
355       (if (fboundp 'put-char-table)
356           (if (fboundp 'get-char-table) ; warning avoidance
357               (put-char-table t (get-char-table ?a (standard-syntax-table))
358                               table))))
359     (modify-syntax-entry ?\\ "\\" table)
360     (modify-syntax-entry ?\" "\"" table)
361     (modify-syntax-entry ?\( "(" table)
362     (modify-syntax-entry ?\) ")" table)
363     (modify-syntax-entry ?\< "." table)
364     (modify-syntax-entry ?\> "." table)
365     (modify-syntax-entry ?\[ "." table)
366     (modify-syntax-entry ?\] "." table)
367     (modify-syntax-entry ?: "." table)
368     (modify-syntax-entry ?\; "." table)
369     (modify-syntax-entry ?, "." table)
370     (modify-syntax-entry ?@ "." table)
371     table))
372
373 (defun rfc2047-encode-region (b e)
374   "Encode words in region B to E that need encoding.
375 By default, the region is treated as containing RFC2822 addresses.
376 Dynamically bind `rfc2047-encoding-type' to change that."
377   (save-restriction
378     (narrow-to-region b e)
379     (let ((encodable-regexp (if rfc2047-encode-encoded-words
380                                 "[^\000-\177]+\\|=\\?"
381                               "[^\000-\177]+"))
382           start                         ; start of current token
383           end begin csyntax
384           ;; Whether there's an encoded word before the current token,
385           ;; either immediately or separated by space.
386           last-encoded
387           (orig-text (buffer-substring-no-properties b e)))
388       (if (eq 'mime rfc2047-encoding-type)
389           ;; Simple case.  Continuous words in which all those contain
390           ;; non-ASCII characters are encoded collectively.  Encoding
391           ;; ASCII words, including `Re:' used in Subject headers, is
392           ;; avoided for interoperability with non-MIME clients and
393           ;; for making it easy to find keywords.
394           (progn
395             (goto-char (point-min))
396             (while (progn (skip-chars-forward " \t\n")
397                           (not (eobp)))
398               (setq start (point))
399               (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
400                           (progn
401                             (setq end (match-end 0))
402                             (re-search-forward encodable-regexp end t)))
403                 (goto-char end))
404               (if (> (point) start)
405                   (rfc2047-encode start (point))
406                 (goto-char end))))
407         ;; `address-mime' case -- take care of quoted words, comments.
408         (rfc2047-quote-special-characters-in-quoted-strings encodable-regexp)
409         (with-syntax-table rfc2047-syntax-table
410           (goto-char (point-min))
411           (condition-case err           ; in case of unbalanced quotes
412               ;; Look for rfc2822-style: sequences of atoms, quoted
413               ;; strings, specials, whitespace.  (Specials mustn't be
414               ;; encoded.)
415               (while (not (eobp))
416                 ;; Skip whitespace.
417                 (skip-chars-forward " \t\n")
418                 (setq start (point))
419                 (cond
420                  ((not (char-after)))   ; eob
421                  ;; else token start
422                  ((eq ?\" (setq csyntax (char-syntax (char-after))))
423                   ;; Quoted word.
424                   (forward-sexp)
425                   (setq end (point))
426                   ;; Does it need encoding?
427                   (goto-char start)
428                   (if (re-search-forward encodable-regexp end 'move)
429                       ;; It needs encoding.  Strip the quotes first,
430                       ;; since encoded words can't occur in quotes.
431                       (progn
432                         (goto-char end)
433                         (delete-backward-char 1)
434                         (goto-char start)
435                         (delete-char 1)
436                         (when last-encoded
437                           ;; There was a preceding quoted word.  We need
438                           ;; to include any separating whitespace in this
439                           ;; word to avoid it getting lost.
440                           (skip-chars-backward " \t")
441                           ;; A space is needed between the encoded words.
442                           (insert ? )
443                           (setq start (point)
444                                 end (1+ end)))
445                         ;; Adjust the end position for the deleted quotes.
446                         (rfc2047-encode start (- end 2))
447                         (setq last-encoded t)) ; record that it was encoded
448                     (setq last-encoded  nil)))
449                  ((eq ?. csyntax)
450                   ;; Skip other delimiters, but record that they've
451                   ;; potentially separated quoted words.
452                   (forward-char)
453                   (setq last-encoded nil))
454                  ((eq ?\) csyntax)
455                   (error "Unbalanced parentheses"))
456                  ((eq ?\( csyntax)
457                   ;; Look for the end of parentheses.
458                   (forward-list)
459                   ;; Encode text as an unstructured field.
460                   (let ((rfc2047-encoding-type 'mime))
461                     (rfc2047-encode-region (1+ start) (1- (point))))
462                   (skip-chars-forward ")"))
463                  (t                 ; normal token/whitespace sequence
464                   ;; Find the end.
465                   ;; Skip one ASCII word, or encode continuous words
466                   ;; in which all those contain non-ASCII characters.
467                   (setq end nil)
468                   (while (not (or end (eobp)))
469                     (when (looking-at "[\000-\177]+")
470                       (setq begin (point)
471                             end (match-end 0))
472                       (when (progn
473                               (while (and (or (re-search-forward
474                                                "[ \t\n]\\|\\Sw" end 'move)
475                                               (setq end nil))
476                                           (eq ?\\ (char-syntax (char-before))))
477                                 ;; Skip backslash-quoted characters.
478                                 (forward-char))
479                               end)
480                         (setq end (match-beginning 0))
481                         (if rfc2047-encode-encoded-words
482                             (progn
483                               (goto-char begin)
484                               (when (search-forward "=?" end 'move)
485                                 (goto-char (match-beginning 0))
486                                 (setq end nil)))
487                           (goto-char end))))
488                     ;; Where the value nil of `end' means there may be
489                     ;; text to have to be encoded following the point.
490                     ;; Otherwise, the point reached to the end of ASCII
491                     ;; words separated by whitespace or a special char.
492                     (unless end
493                       (when (looking-at encodable-regexp)
494                         (goto-char (setq begin (match-end 0)))
495                         (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
496                                     (setq end (match-end 0))
497                                     (progn
498                                       (while (re-search-forward
499                                               encodable-regexp end t))
500                                       (< begin (point)))
501                                     (goto-char begin)
502                                     (or (not (re-search-forward "\\Sw" end t))
503                                         (progn
504                                           (goto-char (match-beginning 0))
505                                           nil)))
506                           (goto-char end))
507                         (when (looking-at "[^ \t\n]+")
508                           (setq end (match-end 0))
509                           (if (re-search-forward "\\Sw+" end t)
510                               ;; There are special characters better
511                               ;; to be encoded so that MTAs may parse
512                               ;; them safely.
513                               (cond ((= end (point)))
514                                     ((looking-at (concat "\\sw*\\("
515                                                          encodable-regexp
516                                                          "\\)"))
517                                      (setq end nil))
518                                     (t
519                                      (goto-char (1- (match-end 0)))
520                                      (unless (= (point) (match-beginning 0))
521                                        ;; Separate encodable text and
522                                        ;; delimiter.
523                                        (insert " "))))
524                             (goto-char end)
525                             (skip-chars-forward " \t\n")
526                             (if (and (looking-at "[^ \t\n]+")
527                                      (string-match encodable-regexp
528                                                    (match-string 0)))
529                                 (setq end nil)
530                               (goto-char end)))))))
531                   (skip-chars-backward " \t\n")
532                   (setq end (point))
533                   (goto-char start)
534                   (if (re-search-forward encodable-regexp end 'move)
535                       (progn
536                         (unless (memq (char-before start) '(nil ?\t ? ))
537                           (if (progn
538                                 (goto-char start)
539                                 (skip-chars-backward "^ \t\n")
540                                 (and (looking-at "\\Sw+")
541                                      (= (match-end 0) start)))
542                               ;; Also encode bogus delimiters.
543                               (setq start (point))
544                             ;; Separate encodable text and delimiter.
545                             (goto-char start)
546                             (insert " ")
547                             (setq start (1+ start)
548                                   end (1+ end))))
549                         (rfc2047-encode start end)
550                         (setq last-encoded t))
551                     (setq last-encoded nil)))))
552             (error
553              (if (or debug-on-quit debug-on-error)
554                  (signal (car err) (cdr err))
555                (error "Invalid data for rfc2047 encoding: %s"
556                       (mm-replace-in-string orig-text "[ \t\n]+" " "))))))))
557     (rfc2047-fold-region b (point))
558     (goto-char (point-max))))
559
560 (defun rfc2047-encode-string (string)
561   "Encode words in STRING.
562 By default, the string is treated as containing addresses (see
563 `rfc2047-encoding-type')."
564   (mm-with-multibyte-buffer
565     (insert string)
566     (rfc2047-encode-region (point-min) (point-max))
567     (buffer-string)))
568
569 ;; From RFC 2047:
570 ;; 2. Syntax of encoded-words
571 ;;    [...]
572 ;;    While there is no limit to the length of a multiple-line header
573 ;;    field, each line of a header field that contains one or more
574 ;;    'encoded-word's is limited to 76 characters.
575 ;;
576 ;; In `rfc2047-encode-parameter' it is bound to nil, so don't defconst it.
577 (defvar rfc2047-encode-max-chars 76
578   "Maximum characters of each header line that contain encoded-words.
579 According to RFC 2047, it is 76.  If it is nil, encoded-words
580 will not be folded.  Too small value may cause an error.  You
581 should not change this value.")
582
583 (defun rfc2047-encode-1 (column string cs encoder start crest tail
584                                 &optional eword)
585   "Subroutine used by `rfc2047-encode'."
586   (cond ((string-equal string "")
587          (or eword ""))
588         ((not rfc2047-encode-max-chars)
589          (concat start
590                  (funcall encoder (if cs
591                                       (mm-encode-coding-string string cs)
592                                     string))
593                  "?="))
594         ((>= column rfc2047-encode-max-chars)
595          (when eword
596            (cond ((string-match "\n[ \t]+\\'" eword)
597                   ;; Reomove a superfluous empty line.
598                   (setq eword (substring eword 0 (match-beginning 0))))
599                  ((string-match "(+\\'" eword)
600                   ;; Break the line before the open parenthesis.
601                   (setq crest (concat crest (match-string 0 eword))
602                         eword (substring eword 0 (match-beginning 0))))))
603          (rfc2047-encode-1 (length crest) string cs encoder start " " tail
604                            (concat eword "\n" crest)))
605         (t
606          (let ((index 0)
607                (limit (1- (length string)))
608                (prev "")
609                next len)
610            (while (and prev
611                        (<= index limit))
612              (setq next (concat start
613                                 (funcall encoder
614                                          (if cs
615                                              (mm-encode-coding-string
616                                               (substring string 0 (1+ index))
617                                               cs)
618                                            (substring string 0 (1+ index))))
619                                 "?=")
620                    len (+ column (length next)))
621              (if (> len rfc2047-encode-max-chars)
622                  (setq next prev
623                        prev nil)
624                (if (or (< index limit)
625                        (<= (+ len (or (string-match "\n" tail)
626                                       (length tail)))
627                            rfc2047-encode-max-chars))
628                    (setq prev next
629                          index (1+ index))
630                  (if (string-match "\\`)+" tail)
631                      ;; Break the line after the close parenthesis.
632                      (setq tail (concat (substring tail 0 (match-end 0))
633                                         "\n "
634                                         (substring tail (match-end 0)))
635                            prev next
636                            index (1+ index))
637                    (setq next prev
638                          prev nil)))))
639            (if (> index limit)
640                (concat eword next tail)
641              (if (= 0 index)
642                  (if (and eword
643                           (string-match "(+\\'" eword))
644                      (setq crest (concat crest (match-string 0 eword))
645                            eword (substring eword 0 (match-beginning 0)))
646                    (setq eword (concat eword next)))
647                (setq crest " "
648                      eword (concat eword next)))
649              (when (string-match "\n[ \t]+\\'" eword)
650                ;; Reomove a superfluous empty line.
651                (setq eword (substring eword 0 (match-beginning 0))))
652              (rfc2047-encode-1 (length crest) (substring string index)
653                                cs encoder start " " tail
654                                (concat eword "\n" crest)))))))
655
656 (defun rfc2047-encode (b e)
657   "Encode the word(s) in the region B to E.
658 Point moves to the end of the region."
659   (let ((mime-charset (or (mm-find-mime-charset-region b e) (list 'us-ascii)))
660         cs encoding tail crest eword)
661     (cond ((> (length mime-charset) 1)
662            (error "Can't rfc2047-encode `%s'"
663                   (buffer-substring-no-properties b e)))
664           ((= (length mime-charset) 1)
665            (setq mime-charset (car mime-charset)
666                  cs (mm-charset-to-coding-system mime-charset))
667            (unless (and (mm-multibyte-p)
668                         (mm-coding-system-p cs))
669              (setq cs nil))
670            (save-restriction
671              (narrow-to-region b e)
672              (setq encoding
673                    (or (cdr (assq mime-charset
674                                   rfc2047-charset-encoding-alist))
675                        ;; For the charsets that don't have a preferred
676                        ;; encoding, choose the one that's shorter.
677                        (if (eq (rfc2047-qp-or-base64) 'base64)
678                            'B
679                          'Q)))
680              (widen)
681              (goto-char e)
682              (skip-chars-forward "^ \t\n")
683              ;; `tail' may contain a close parenthesis.
684              (setq tail (buffer-substring-no-properties e (point)))
685              (goto-char b)
686              (setq b (point-marker)
687                    e (set-marker (make-marker) e))
688              (rfc2047-fold-region (point-at-bol) b)
689              (goto-char b)
690              (skip-chars-backward "^ \t\n")
691              (unless (= 0 (skip-chars-backward " \t"))
692                ;; `crest' may contain whitespace and an open parenthesis.
693                (setq crest (buffer-substring-no-properties (point) b)))
694              (setq eword (rfc2047-encode-1
695                           (- b (point-at-bol))
696                           (mm-replace-in-string
697                            (buffer-substring-no-properties b e)
698                            "\n\\([ \t]?\\)" "\\1")
699                           cs
700                           (or (cdr (assq encoding
701                                          rfc2047-encode-function-alist))
702                               'identity)
703                           (concat "=?" (downcase (symbol-name mime-charset))
704                                   "?" (upcase (symbol-name encoding)) "?")
705                           (or crest " ")
706                           tail))
707              (delete-region (if (eq (aref eword 0) ?\n)
708                                 (if (bolp)
709                                     ;; The line was folded before encoding.
710                                     (1- (point))
711                                   (point))
712                               (goto-char b))
713                             (+ e (length tail)))
714              ;; `eword' contains `crest' and `tail'.
715              (insert eword)
716              (set-marker b nil)
717              (set-marker e nil)
718              (unless (or (/= 0 (length tail))
719                          (eobp)
720                          (looking-at "[ \t\n)]"))
721                (insert " "))))
722           (t
723            (goto-char e)))))
724
725 (defun rfc2047-fold-field ()
726   "Fold the current header field."
727   (save-excursion
728     (save-restriction
729       (rfc2047-narrow-to-field)
730       (rfc2047-fold-region (point-min) (point-max)))))
731
732 (defun rfc2047-fold-region (b e)
733   "Fold long lines in region B to E."
734   (save-restriction
735     (narrow-to-region b e)
736     (goto-char (point-min))
737     (let ((break nil)
738           (qword-break nil)
739           (first t)
740           (bol (save-restriction
741                  (widen)
742                  (point-at-bol))))
743       (while (not (eobp))
744         (when (and (or break qword-break)
745                    (> (- (point) bol) 76))
746           (goto-char (or break qword-break))
747           (setq break nil
748                 qword-break nil)
749           (skip-chars-backward " \t")
750           (if (looking-at "[ \t]")
751               (insert ?\n)
752             (insert "\n "))
753           (setq bol (1- (point)))
754           ;; Don't break before the first non-LWSP characters.
755           (skip-chars-forward " \t")
756           (unless (eobp)
757             (forward-char 1)))
758         (cond
759          ((eq (char-after) ?\n)
760           (forward-char 1)
761           (setq bol (point)
762                 break nil
763                 qword-break nil)
764           (skip-chars-forward " \t")
765           (unless (or (eobp) (eq (char-after) ?\n))
766             (forward-char 1)))
767          ((eq (char-after) ?\r)
768           (forward-char 1))
769          ((memq (char-after) '(?  ?\t))
770           (skip-chars-forward " \t")
771           (unless first ;; Don't break just after the header name.
772             (setq break (point))))
773          ((not break)
774           (if (not (looking-at "=\\?[^=]"))
775               (if (eq (char-after) ?=)
776                   (forward-char 1)
777                 (skip-chars-forward "^ \t\n\r="))
778             ;; Don't break at the start of the field.
779             (unless (= (point) b)
780               (setq qword-break (point)))
781             (skip-chars-forward "^ \t\n\r")))
782          (t
783           (skip-chars-forward "^ \t\n\r")))
784         (setq first nil))
785       (when (and (or break qword-break)
786                  (> (- (point) bol) 76))
787         (goto-char (or break qword-break))
788         (setq break nil
789               qword-break nil)
790         (if (or (> 0 (skip-chars-backward " \t"))
791                 (looking-at "[ \t]"))
792             (insert ?\n)
793           (insert "\n "))
794         (setq bol (1- (point)))
795         ;; Don't break before the first non-LWSP characters.
796         (skip-chars-forward " \t")
797         (unless (eobp)
798           (forward-char 1))))))
799
800 (defun rfc2047-unfold-field ()
801   "Fold the current line."
802   (save-excursion
803     (save-restriction
804       (rfc2047-narrow-to-field)
805       (rfc2047-unfold-region (point-min) (point-max)))))
806
807 (defun rfc2047-unfold-region (b e)
808   "Unfold lines in region B to E."
809   (save-restriction
810     (narrow-to-region b e)
811     (goto-char (point-min))
812     (let ((bol (save-restriction
813                  (widen)
814                  (point-at-bol)))
815           (eol (point-at-eol)))
816       (forward-line 1)
817       (while (not (eobp))
818         (if (and (looking-at "[ \t]")
819                  (< (- (point-at-eol) bol) 76))
820             (delete-region eol (progn
821                                  (goto-char eol)
822                                  (skip-chars-forward "\r\n")
823                                  (point)))
824           (setq bol (point-at-bol)))
825         (setq eol (point-at-eol))
826         (forward-line 1)))))
827
828 (defun rfc2047-b-encode-string (string)
829   "Base64-encode the header contained in STRING."
830   (base64-encode-string string t))
831
832 (defun rfc2047-q-encode-string (string)
833   "Quoted-printable-encode the header in STRING."
834   (mm-with-unibyte-buffer
835     (insert string)
836     (quoted-printable-encode-region
837      (point-min) (point-max) nil
838      ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
839      ;; Avoid using 8bit characters.
840      ;; This list excludes `especials' (see the RFC2047 syntax),
841      ;; meaning that some characters in non-structured fields will
842      ;; get encoded when they con't need to be.  The following is
843      ;; what it used to be.
844      ;;;  ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
845      ;;;  "\010\012\014\040-\074\076\100-\136\140-\177")
846      "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
847     (subst-char-in-region (point-min) (point-max) ?  ?_)
848     (buffer-string)))
849
850 (defun rfc2047-encode-parameter (param value)
851   "Return and PARAM=VALUE string encoded in the RFC2047-like style.
852 This is a replacement for the `rfc2231-encode-string' function.
853
854 When attaching files as MIME parts, we should use the RFC2231 encoding
855 to specify the file names containing non-ASCII characters.  However,
856 many mail softwares don't support it in practice and recipients won't
857 be able to extract files with correct names.  Instead, the RFC2047-like
858 encoding is acceptable generally.  This function provides the very
859 RFC2047-like encoding, resigning to such a regrettable trend.  To use
860 it, put the following line in your ~/.gnus.el file:
861
862 \(defalias 'mail-header-encode-parameter 'rfc2047-encode-parameter)
863 "
864   (let ((rfc2047-encoding-type 'mime)
865         (rfc2047-encode-max-chars nil))
866     (rfc2045-encode-string param (rfc2047-encode-string value))))
867
868 ;;;
869 ;;; Functions for decoding RFC2047 messages
870 ;;;
871
872 (defvar rfc2047-quote-decoded-words-containing-tspecials nil
873   "If non-nil, quote decoded words containing special characters.")
874
875 (defvar rfc2047-allow-incomplete-encoded-text t
876   "*Non-nil means allow incomplete encoded-text in successive encoded-words.
877 Dividing of encoded-text in the place other than character boundaries
878 violates RFC2047 section 5, while we have a capability to decode it.
879 If it is non-nil, the decoder will decode B- or Q-encoding in each
880 encoded-word, concatenate them, and decode it by charset.  Otherwise,
881 the decoder will fully decode each encoded-word before concatenating
882 them.")
883
884 (defun rfc2047-strip-backslashes-in-quoted-strings ()
885   "Strip backslashes in quoted strings.  `\\\"' remains."
886   (goto-char (point-min))
887   (let (beg)
888     (with-syntax-table (standard-syntax-table)
889       (while (search-forward "\"" nil t)
890         (unless (eq (char-before) ?\\)
891           (setq beg (match-end 0))
892           (goto-char (match-beginning 0))
893           (condition-case nil
894               (progn
895                 (forward-sexp)
896                 (save-restriction
897                   (narrow-to-region beg (1- (point)))
898                   (goto-char beg)
899                   (while (search-forward "\\" nil 'move)
900                     (unless (memq (char-after) '(?\"))
901                       (delete-backward-char 1))
902                     (forward-char)))
903                 (forward-char))
904             (error
905              (goto-char beg))))))))
906
907 (defun rfc2047-charset-to-coding-system (charset)
908   "Return coding-system corresponding to MIME CHARSET.
909 If your Emacs implementation can't decode CHARSET, return nil."
910   (when (stringp charset)
911     (setq charset (intern (downcase charset))))
912   (when (or (not charset)
913             (eq 'gnus-all mail-parse-ignored-charsets)
914             (memq 'gnus-all mail-parse-ignored-charsets)
915             (memq charset mail-parse-ignored-charsets))
916     (setq charset mail-parse-charset))
917   (let ((cs (mm-charset-to-coding-system charset)))
918     (cond ((eq cs 'ascii)
919            (setq cs (or (mm-charset-to-coding-system mail-parse-charset)
920                         'raw-text)))
921           ((mm-coding-system-p cs))
922           ((and charset
923                 (listp mail-parse-ignored-charsets)
924                 (memq 'gnus-unknown mail-parse-ignored-charsets))
925            (setq cs (mm-charset-to-coding-system mail-parse-charset))))
926     (if (eq cs 'ascii)
927         'raw-text
928       cs)))
929
930 (defun rfc2047-decode-encoded-words (words)
931   "Decode successive encoded-words in WORDS and return a decoded string.
932 Each element of WORDS looks like (CHARSET ENCODING ENCODED-TEXT
933 ENCODED-WORD)."
934   (let (word charset cs encoding text rest)
935     (while words
936       (setq word (pop words))
937       (if (and (setq cs (rfc2047-charset-to-coding-system
938                          (setq charset (car word))))
939                (condition-case code
940                    (cond ((char-equal ?B (nth 1 word))
941                           (setq text (base64-decode-string
942                                       (rfc2047-pad-base64 (nth 2 word)))))
943                          ((char-equal ?Q (nth 1 word))
944                           (setq text (quoted-printable-decode-string
945                                       (mm-subst-char-in-string
946                                        ?_ ?  (nth 2 word) t)))))
947                  (error
948                   (message "%s" (error-message-string code))
949                   nil)))
950           (if (and rfc2047-allow-incomplete-encoded-text
951                    (eq cs (caar rest)))
952               ;; Concatenate text of which the charset is the same.
953               (setcdr (car rest) (concat (cdar rest) text))
954             (push (cons cs text) rest))
955         ;; Don't decode encoded-word.
956         (push (cons nil (nth 3 word)) rest)))
957     (while rest
958       (setq words (concat
959                    (or (and (setq cs (caar rest))
960                             (condition-case code
961                                 (mm-decode-coding-string (cdar rest) cs)
962                               (error
963                                (message "%s" (error-message-string code))
964                                nil)))
965                        (concat (when (cdr rest) " ")
966                                (cdar rest)
967                                (when (and words
968                                           (not (eq (string-to-char words) ? )))
969                                  " ")))
970                    words)
971             rest (cdr rest)))
972     words))
973
974 ;; Fixme: This should decode in place, not cons intermediate strings.
975 ;; Also check whether it needs to worry about delimiting fields like
976 ;; encoding.
977
978 ;; In fact it's reported that (invalid) encoding of mailboxes in
979 ;; addr-specs is in use, so delimiting fields might help.  Probably
980 ;; not decoding a word which isn't properly delimited is good enough
981 ;; and worthwhile (is it more correct or not?), e.g. something like
982 ;; `=?iso-8859-1?q?foo?=@'.
983
984 (defun rfc2047-decode-region (start end &optional address-mime)
985   "Decode MIME-encoded words in region between START and END.
986 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
987 other than `\"' and `\\' in quoted strings."
988   (interactive "r")
989   (let ((case-fold-search t)
990         (eword-regexp
991          (if rfc2047-allow-irregular-q-encoded-words
992              (eval-when-compile
993                (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp-loose "\\)"))
994            (eval-when-compile
995              (concat "[\n\t ]*\\(" rfc2047-encoded-word-regexp "\\)"))))
996         b e match words)
997     (save-excursion
998       (save-restriction
999         (narrow-to-region start end)
1000         (when address-mime
1001           (rfc2047-strip-backslashes-in-quoted-strings))
1002         (goto-char (setq b start))
1003         ;; Look for the encoded-words.
1004         (while (setq match (re-search-forward eword-regexp nil t))
1005           (setq e (match-beginning 1)
1006                 end (match-end 0)
1007                 words nil)
1008           (while match
1009             (push (list (match-string 2) ;; charset
1010                         (char-after (match-beginning 3)) ;; encoding
1011                         (substring (match-string 3) 2) ;; encoded-text
1012                         (match-string 1)) ;; encoded-word
1013                   words)
1014             ;; Look for the subsequent encoded-words.
1015             (when (setq match (looking-at eword-regexp))
1016               (goto-char (setq end (match-end 0)))))
1017           ;; Replace the encoded-words with the decoded one.
1018           (delete-region e end)
1019           (insert (rfc2047-decode-encoded-words (nreverse words)))
1020           (save-restriction
1021             (narrow-to-region e (point))
1022             (goto-char e)
1023             ;; Remove newlines between decoded words, though such
1024             ;; things essentially must not be there.
1025             (while (re-search-forward "[\n\r]+" nil t)
1026               (replace-match " "))
1027             ;; Quote decoded words if there are special characters
1028             ;; which might violate RFC2822.
1029             (when (and rfc2047-quote-decoded-words-containing-tspecials
1030                        (let ((regexp (car (rassq
1031                                            'address-mime
1032                                            rfc2047-header-encoding-alist))))
1033                          (when regexp
1034                            (save-restriction
1035                              (widen)
1036                              (beginning-of-line)
1037                              (while (and (memq (char-after) '(?  ?\t))
1038                                          (zerop (forward-line -1))))
1039                              (looking-at regexp)))))
1040               (let (quoted)
1041                 (goto-char e)
1042                 (skip-chars-forward " \t")
1043                 (setq start (point))
1044                 (setq quoted (eq (char-after) ?\"))
1045                 (goto-char (point-max))
1046                 (skip-chars-backward " \t")
1047                 (if (setq quoted (and quoted
1048                                       (> (point) (1+ start))
1049                                       (eq (char-before) ?\")))
1050                     (progn
1051                       (backward-char)
1052                       (setq start (1+ start)
1053                             end (point-marker)))
1054                   (setq end (point-marker)))
1055                 (goto-char start)
1056                 (while (search-forward "\"" end t)
1057                   (when (prog2
1058                             (backward-char)
1059                             (zerop (% (skip-chars-backward "\\\\") 2))
1060                           (goto-char (match-beginning 0)))
1061                     (insert "\\"))
1062                   (forward-char))
1063                 (when (and (not quoted)
1064                            (progn
1065                              (goto-char start)
1066                              (re-search-forward
1067                               (concat "[" ietf-drums-tspecials "]")
1068                               end t)))
1069                   (goto-char start)
1070                   (insert "\"")
1071                   (goto-char end)
1072                   (insert "\""))
1073                 (set-marker end nil)))
1074             (goto-char (point-max)))
1075           (when (and (mm-multibyte-p)
1076                      mail-parse-charset
1077                      (not (eq mail-parse-charset 'us-ascii))
1078                      (not (eq mail-parse-charset 'gnus-decoded)))
1079             (mm-decode-coding-region b e mail-parse-charset))
1080           (setq b (point)))
1081         (when (and (mm-multibyte-p)
1082                    mail-parse-charset
1083                    (not (eq mail-parse-charset 'us-ascii))
1084                    (not (eq mail-parse-charset 'gnus-decoded)))
1085           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
1086
1087 (defun rfc2047-decode-address-region (start end)
1088   "Decode MIME-encoded words in region between START and END.
1089 Backslashes which precede characters other than `\"' and `\\' in quoted
1090 strings are stripped."
1091   (rfc2047-decode-region start end t))
1092
1093 (defun rfc2047-decode-string (string &optional address-mime)
1094   "Decode MIME-encoded STRING and return the result.
1095 If ADDRESS-MIME is non-nil, strip backslashes which precede characters
1096 other than `\"' and `\\' in quoted strings."
1097   (let ((m (mm-multibyte-p)))
1098     (if (string-match "=\\?" string)
1099         (with-temp-buffer
1100           ;; Fixme: This logic is wrong, but seems to be required by
1101           ;; Gnus summary buffer generation.  The value of `m' depends
1102           ;; on the current buffer, not global multibyteness or that
1103           ;; of the string.  Also the string returned should always be
1104           ;; multibyte in a multibyte session, i.e. the buffer should
1105           ;; be multibyte before `buffer-string' is called.
1106           (when m
1107             (mm-enable-multibyte))
1108           (insert string)
1109           (inline
1110             (rfc2047-decode-region (point-min) (point-max) address-mime))
1111           (buffer-string))
1112       (when address-mime
1113         (setq string
1114               (with-temp-buffer
1115                 (when (mm-multibyte-string-p string)
1116                   (mm-enable-multibyte))
1117                 (insert string)
1118                 (rfc2047-strip-backslashes-in-quoted-strings)
1119                 (buffer-string))))
1120       ;; Fixme: As above, `m' here is inappropriate.
1121       (if (and m
1122                mail-parse-charset
1123                (not (eq mail-parse-charset 'us-ascii))
1124                (not (eq mail-parse-charset 'gnus-decoded)))
1125           ;; `decode-coding-string' in Emacs offers a third optional
1126           ;; arg NOCOPY to avoid consing a new string if the decoding
1127           ;; is "trivial".  Unfortunately it currently doesn't
1128           ;; consider anything else than a `nil' coding system
1129           ;; trivial.
1130           ;; `rfc2047-decode-string' is called multiple times for each
1131           ;; article during summary buffer generation, and we really
1132           ;; want to avoid unnecessary consing.  So we bypass
1133           ;; `decode-coding-string' if the string is purely ASCII.
1134           (if (and (fboundp 'detect-coding-string)
1135                    ;; string is purely ASCII
1136                    (eq (detect-coding-string string t) 'undecided))
1137               string
1138             (mm-decode-coding-string string mail-parse-charset))
1139         (mm-string-as-multibyte string)))))
1140
1141 (defun rfc2047-decode-address-string (string)
1142   "Decode MIME-encoded STRING and return the result.
1143 Backslashes which precede characters other than `\"' and `\\' in quoted
1144 strings are stripped."
1145   (rfc2047-decode-string string t))
1146
1147 (defun rfc2047-pad-base64 (string)
1148   "Pad STRING to quartets."
1149   ;; Be more liberal to accept buggy base64 strings. If
1150   ;; base64-decode-string accepts buggy strings, this function could
1151   ;; be aliased to identity.
1152   (if (= 0 (mod (length string) 4))
1153       string
1154     (when (string-match "=+$" string)
1155       (setq string (substring string 0 (match-beginning 0))))
1156     (case (mod (length string) 4)
1157       (0 string)
1158       (1 string) ;; Error, don't pad it.
1159       (2 (concat string "=="))
1160       (3 (concat string "=")))))
1161
1162 (provide 'rfc2047)
1163
1164 ;;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
1165 ;;; rfc2047.el ends here