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