6766e6f0fac167cc1377dee89dc82524e4bd6183
[elisp/gnus.git-] / lisp / base64.el
1 ;;; base64.el,v --- Base64 encoding functions
2 ;; Author: Kyle E. Jones
3 ;; Created: 1997/03/12 14:37:09
4 ;; Version: 1.6
5 ;; Keywords: extensions
6
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; Copyright (C) 1997 Kyle E. Jones
9 ;;;
10 ;;; This file is not part of GNU Emacs, but the same permissions apply.
11 ;;;
12 ;;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2, or (at your option)
15 ;;; any later version.
16 ;;;
17 ;;; GNU Emacs is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27
28 ;; For non-MULE
29 (if (not (fboundp 'char-int))
30     (fset 'char-int 'identity))
31
32 (defvar base64-alphabet
33   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
34
35 (defvar base64-decoder-program nil
36   "*Non-nil value should be a string that names a MIME base64 decoder.
37 The program should expect to read base64 data on its standard
38 input and write the converted data to its standard output.")
39
40 (defvar base64-decoder-switches nil
41   "*List of command line flags passed to the command named by
42 base64-decoder-program.")
43
44 (defvar base64-encoder-program nil
45   "*Non-nil value should be a string that names a MIME base64 encoder.
46 The program should expect arbitrary data on its standard
47 input and write base64 data to its standard output.")
48
49 (defvar base64-encoder-switches nil
50   "*List of command line flags passed to the command named by
51 base64-encoder-program.")
52
53 (defconst base64-alphabet-decoding-alist
54   '(
55     ( ?A . 00) ( ?B . 01) ( ?C . 02) ( ?D . 03) ( ?E . 04) ( ?F . 05)
56     ( ?G . 06) ( ?H . 07) ( ?I . 08) ( ?J . 09) ( ?K . 10) ( ?L . 11)
57     ( ?M . 12) ( ?N . 13) ( ?O . 14) ( ?P . 15) ( ?Q . 16) ( ?R . 17)
58     ( ?S . 18) ( ?T . 19) ( ?U . 20) ( ?V . 21) ( ?W . 22) ( ?X . 23)
59     ( ?Y . 24) ( ?Z . 25) ( ?a . 26) ( ?b . 27) ( ?c . 28) ( ?d . 29)
60     ( ?e . 30) ( ?f . 31) ( ?g . 32) ( ?h . 33) ( ?i . 34) ( ?j . 35)
61     ( ?k . 36) ( ?l . 37) ( ?m . 38) ( ?n . 39) ( ?o . 40) ( ?p . 41)
62     ( ?q . 42) ( ?r . 43) ( ?s . 44) ( ?t . 45) ( ?u . 46) ( ?v . 47)
63     ( ?w . 48) ( ?x . 49) ( ?y . 50) ( ?z . 51) ( ?0 . 52) ( ?1 . 53)
64     ( ?2 . 54) ( ?3 . 55) ( ?4 . 56) ( ?5 . 57) ( ?6 . 58) ( ?7 . 59)
65     ( ?8 . 60) ( ?9 . 61) ( ?+ . 62) ( ?/ . 63)
66    ))
67
68 (defvar base64-alphabet-decoding-vector
69   (let ((v (make-vector 123 nil))
70         (p base64-alphabet-decoding-alist))
71     (while p
72       (aset v (car (car p)) (cdr (car p)))
73       (setq p (cdr p)))
74     v))
75
76 (defun base64-run-command-on-region (start end output-buffer command
77                                            &rest arg-list)
78   (let ((tempfile nil) status errstring default-process-coding-system)
79     (unwind-protect
80         (progn
81           (setq tempfile (make-temp-name "base64"))
82           (setq status
83                 (apply 'call-process-region
84                        start end command nil
85                        (list output-buffer tempfile)
86                        nil arg-list))
87           (cond ((equal status 0) t)
88                 ((zerop (save-excursion
89                           (set-buffer (find-file-noselect tempfile))
90                           (buffer-size)))
91                  t)
92                 (t (save-excursion
93                      (set-buffer (find-file-noselect tempfile))
94                      (setq errstring (buffer-string))
95                      (kill-buffer nil)
96                      (cons status errstring)))))
97       (ignore-errors
98         (delete-file tempfile)))))
99
100 (if (string-match "XEmacs" emacs-version)
101     (defalias 'base64-insert-char 'insert-char)
102   (defun base64-insert-char (char &optional count ignored buffer)
103     (if (or (null buffer) (eq buffer (current-buffer)))
104         (insert-char char count)
105       (with-current-buffer buffer
106         (insert-char char count)))))
107
108 (defun base64-decode-region (start end)
109   (interactive "r")
110   ;;(message "Decoding base64...")
111   (let ((work-buffer nil)
112         (done nil)
113         (counter 0)
114         (bits 0)
115         (lim 0) inputpos
116         (non-data-chars (concat "^=" base64-alphabet)))
117     (unwind-protect
118         (save-excursion
119           (setq work-buffer (generate-new-buffer " *base64-work*"))
120           (buffer-disable-undo work-buffer)
121           (if base64-decoder-program
122               (let* ((binary-process-output t) ; any text already has CRLFs
123                      (status (apply 'base64-run-command-on-region
124                                    start end work-buffer
125                                    base64-decoder-program
126                                    base64-decoder-switches)))
127                 (if (not (eq status t))
128                     (error "%s" (cdr status))))
129             (goto-char start)
130             (skip-chars-forward non-data-chars end)
131             (while (not done)
132               (setq inputpos (point))
133               (cond
134                ((> (skip-chars-forward base64-alphabet end) 0)
135                 (setq lim (point))
136                 (while (< inputpos lim)
137                   (setq bits (+ bits
138                                 (aref base64-alphabet-decoding-vector
139                                       (char-int (char-after inputpos)))))
140                   (setq counter (1+ counter)
141                         inputpos (1+ inputpos))
142                   (cond ((= counter 4)
143                          (base64-insert-char (lsh bits -16) 1 nil work-buffer)
144                          (base64-insert-char (logand (lsh bits -8) 255) 1 nil
145                                          work-buffer)
146                          (base64-insert-char (logand bits 255) 1 nil
147                                              work-buffer)
148                          (setq bits 0 counter 0))
149                         (t (setq bits (lsh bits 6)))))))
150               (cond
151                ((= (point) end)
152                 (if (not (zerop counter))
153                     (error "at least %d bits missing at end of base64 encoding"
154                            (* (- 4 counter) 6)))
155                 (setq done t))
156                ((eq (char-after (point)) ?=)
157                 (setq done t)
158                 (cond ((= counter 1)
159                        (error "at least 2 bits missing at end of base64 encoding"))
160                       ((= counter 2)
161                        (base64-insert-char (lsh bits -10) 1 nil work-buffer))
162                       ((= counter 3)
163                        (base64-insert-char (lsh bits -16) 1 nil work-buffer)
164                        (base64-insert-char (logand (lsh bits -8) 255)
165                                            1 nil work-buffer))
166                       ((= counter 0) t)))
167                (t (skip-chars-forward non-data-chars end)))))
168           (or (markerp end) (setq end (set-marker (make-marker) end)))
169           (goto-char start)
170           (insert-buffer-substring work-buffer)
171           (delete-region (point) end))
172       (and work-buffer (kill-buffer work-buffer))))
173   ;;(message "Decoding base64... done")
174   )
175
176 (defun base64-encode-region (start end &optional no-line-break)
177   (interactive "r")
178   (message "Encoding base64...")
179   (let ((work-buffer nil)
180         (counter 0)
181         (cols 0)
182         (bits 0)
183         (alphabet base64-alphabet)
184         inputpos)
185     (unwind-protect
186         (save-excursion
187           (setq work-buffer (generate-new-buffer " *base64-work*"))
188           (buffer-disable-undo work-buffer)
189           (if base64-encoder-program
190               (let ((status (apply 'base64-run-command-on-region
191                                    start end work-buffer
192                                    base64-encoder-program
193                                    base64-encoder-switches)))
194                 (if (not (eq status t))
195                     (error "%s" (cdr status))))
196             (setq inputpos start)
197             (while (< inputpos end)
198               (setq bits (+ bits (char-int (char-after inputpos))))
199               (setq counter (1+ counter))
200               (cond ((= counter 3)
201                      (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
202                                          work-buffer)
203                      (base64-insert-char
204                       (aref alphabet (logand (lsh bits -12) 63))
205                       1 nil work-buffer)
206                      (base64-insert-char
207                       (aref alphabet (logand (lsh bits -6) 63))
208                       1 nil work-buffer)
209                      (base64-insert-char
210                       (aref alphabet (logand bits 63))
211                       1 nil work-buffer)
212                      (setq cols (+ cols 4))
213                      (cond ((and (= cols 72)
214                                  (not no-line-break))
215                             (base64-insert-char ?\n 1 nil work-buffer)
216                             (setq cols 0)))
217                      (setq bits 0 counter 0))
218                     (t (setq bits (lsh bits 8))))
219               (setq inputpos (1+ inputpos)))
220             ;; write out any remaining bits with appropriate padding
221             (if (= counter 0)
222                 nil
223               (setq bits (lsh bits (- 16 (* 8 counter))))
224               (base64-insert-char (aref alphabet (lsh bits -18)) 1 nil
225                                   work-buffer)
226               (base64-insert-char (aref alphabet (logand (lsh bits -12) 63))
227                                   1 nil work-buffer)
228               (if (= counter 1)
229                   (base64-insert-char ?= 2 nil work-buffer)
230                 (base64-insert-char (aref alphabet (logand (lsh bits -6) 63))
231                                     1 nil work-buffer)
232                 (base64-insert-char ?= 1 nil work-buffer)))
233             (if (and (> cols 0)
234                      (not no-line-break))
235                 (base64-insert-char ?\n 1 nil work-buffer)))
236           (or (markerp end) (setq end (set-marker (make-marker) end)))
237           (goto-char start)
238           (insert-buffer-substring work-buffer)
239           (delete-region (point) end))
240       (and work-buffer (kill-buffer work-buffer))))
241   (message "Encoding base64... done"))
242
243 (defun base64-encode (string)
244   (save-excursion
245     (set-buffer (get-buffer-create " *base64-encode*"))
246     (erase-buffer)
247     (insert string)
248     (base64-encode-region (point-min) (point-max))
249     (skip-chars-backward " \t\r\n")
250     (delete-region (point-max) (point))
251     (prog1
252         (buffer-string)
253       (kill-buffer (current-buffer)))))
254
255 (defun base64-decode (string)
256   (save-excursion
257     (set-buffer (get-buffer-create " *base64-decode*"))
258     (erase-buffer)
259     (insert string)
260     (base64-decode-region (point-min) (point-max))
261     (goto-char (point-max))
262     (skip-chars-backward " \t\r\n")
263     (delete-region (point-max) (point))
264     (prog1
265         (buffer-string)
266       (kill-buffer (current-buffer)))))
267
268 (fset 'base64-decode-string 'base64-decode)
269
270 (provide 'base64)