Contents of aws4-auth.lisp have been moved to request.lisp.
[zs3.git] / utils.lisp
blob4aad707d5c12e05cace25bad8c9ccd903507a3c6
1 ;;;;
2 ;;;; Copyright (c) 2008 Zachary Beane, All Rights Reserved
3 ;;;;
4 ;;;; Redistribution and use in source and binary forms, with or without
5 ;;;; modification, are permitted provided that the following conditions
6 ;;;; are met:
7 ;;;;
8 ;;;; * Redistributions of source code must retain the above copyright
9 ;;;; notice, this list of conditions and the following disclaimer.
10 ;;;;
11 ;;;; * Redistributions in binary form must reproduce the above
12 ;;;; copyright notice, this list of conditions and the following
13 ;;;; disclaimer in the documentation and/or other materials
14 ;;;; provided with the distribution.
15 ;;;;
16 ;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
17 ;;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 ;;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ;;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
20 ;;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 ;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
22 ;;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 ;;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 ;;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 ;;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 ;;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 ;;;;
28 ;;;; utils.lisp
30 (in-package #:zs3)
32 (defvar *months* #("Jan" "Feb" "Mar" "Apr" "May" "Jun"
33 "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
35 (defvar *days* #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
37 (deftype octet ()
38 '(unsigned-byte 8))
40 (deftype octet-vector (&optional size)
41 `(simple-array octet (,size)))
43 (deftype empty-vector ()
44 `(vector * 0))
46 (defun http-date-string (&optional (time (get-universal-time)))
47 "Return a HTTP-style date string."
48 (multiple-value-bind (second minute hour day month year day-of-week)
49 (decode-universal-time time 0)
50 (let ((*print-pretty* nil))
51 (format nil "~A, ~2,'0D ~A ~4,'0D ~2,'0D:~2,'0D:~2,'0D GMT"
52 (aref *days* day-of-week)
53 day
54 (aref *months* (1- month))
55 year
56 hour
57 minute
58 second))))
60 (defun iso8601-date-string (&optional (time (get-universal-time)))
61 "Return an ISO8601-style date string."
62 (multiple-value-bind (second minute hour day month year)
63 (decode-universal-time time 0)
64 (let ((*print-pretty* nil))
65 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0DZ"
66 year month day hour minute second))))
68 (defun iso8601-basic-timestamp-string (&optional (time (get-universal-time)))
69 "Return an ISO8601-style basic date string."
70 (multiple-value-bind (second minute hour day month year)
71 (decode-universal-time time 0)
72 (let ((*print-pretty* nil))
73 (format nil "~4,'0D~2,'0D~2,'0DT~2,'0D~2,'0D~2,'0DZ"
74 year month day hour minute second))))
76 (defun iso8601-basic-date-string (&optional (time (get-universal-time)))
77 "Return an ISO8601-style basic date string."
78 (multiple-value-bind (second minute hour day month year)
79 (decode-universal-time time 0)
80 (declare (ignore second minute hour))
81 (let ((*print-pretty* nil))
82 (format nil "~4,'0D~2,'0D~2,'0D"
83 year month day))))
85 (defun string-octets (string)
86 "Return the UTF-8 encoding of STRING as a vector of octets."
87 (flexi-streams:string-to-octets string :external-format :utf-8))
89 (defun string64 (string)
90 (cl-base64:usb8-array-to-base64-string (string-octets string)))
92 (defun url-decode (string)
93 (with-output-to-string (out)
94 (let ((code 0))
95 (labels ((in-string (char)
96 (case char
97 (#\%
98 #'h1)
100 (write-char char out)
101 #'in-string)))
102 (weight (char)
103 (let ((weight (digit-char-p char 16)))
104 (unless weight
105 (error "~S is not a hex digit" char))
106 weight))
107 (h1 (char)
108 (setf code (ash (weight char) 4))
109 #'h2)
110 (h2 (char)
111 (incf code (weight char))
112 (write-char (code-char code) out)
113 #'in-string))
114 (let ((state #'in-string))
115 (loop for char across string
116 do (setf state (funcall state char))))))))
118 ;;; The following two functions were adatpted from Drakma source. It
119 ;;; has been adapted to more closely follow the description of
120 ;;; UriEncode() in
121 ;;; http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
123 (defun url-encode (string &key (encode-slash t))
124 "Returns a URL-encoded version of the string STRING using the
125 LispWorks external format EXTERNAL-FORMAT."
126 (let ((*print-pretty* nil))
127 (with-output-to-string (out)
128 (loop for octet across (string-octets (or string ""))
129 for char = (code-char octet)
130 ;;'A'-'Z', 'a'-'z', '0'-'9', '-', '.', '_', and '~'
131 do (cond ((or (char<= #\0 char #\9)
132 (char<= #\a char #\z)
133 (char<= #\A char #\Z)
134 (and (not encode-slash) (char= char #\/))
135 (find char "-._~" :test #'char=))
136 (write-char char out))
137 ((char= char #\Space)
138 (write-string "%20" out))
139 (t (format out "%~2,'0x" octet)))))))
141 (defun alist-to-url-encoded-string (alist)
142 "ALIST is supposed to be an alist of name/value pairs where both
143 names and values are strings. This function returns a string where
144 this list is represented as for the content type
145 `application/x-www-form-urlencoded', i.e. the values are URL-encoded
146 using the external format EXTERNAL-FORMAT, the pairs are joined with a
147 #\\& character, and each name is separated from its value with a #\\=
148 character."
149 (let ((*print-pretty* nil))
150 (with-output-to-string (out)
151 (loop for first = t then nil
152 for (name . value) in alist
153 unless first do (write-char #\& out)
154 do (format out "~A=~A"
155 (url-encode name)
156 (url-encode value))))))
158 (defun save (response file)
159 "Write a sequence of octets RESPONSE to FILE."
160 (with-open-file (stream file :direction :output
161 :if-exists :supersede
162 :element-type 'octet)
163 (write-sequence response stream))
164 (probe-file file))
166 (defun parse-amazon-timestamp (string)
167 "Convert the ISO 8601-format STRING to a universal time."
168 (flet ((number-at (start length)
169 (parse-integer string :start start :end (+ start length))))
170 (let ((year (number-at 0 4))
171 (month (number-at 5 2))
172 (day (number-at 8 2))
173 (hour (number-at 11 2))
174 (minute (number-at 14 2))
175 (second (number-at 17 2)))
176 (encode-universal-time second minute hour day month year 0))))
178 (defun stringify (thing)
179 (typecase thing
180 (string thing)
181 (symbol (symbol-name thing))
182 (t (princ-to-string thing))))
184 (defun parameters-alist (&rest args &key &allow-other-keys)
185 "Construct an ALIST based on all keyword arguments passed to the
186 function. Keywords are converted to their lowercase symbol name and
187 values are converted to strings."
188 (loop for (key value) on args by #'cddr
189 when value
190 collect (cons (if (symbolp key)
191 (string-downcase (symbol-name key))
192 key)
193 (stringify value))))
195 (defun last-entry (array)
196 "If ARRAY has one ore more entries, return the last one. Otherwise,
197 return NIL."
198 (and (plusp (length array))
199 (aref array (1- (length array)))))
201 (defun file-size (file)
202 (with-open-file (stream file :element-type 'octet)
203 (file-length stream)))
205 (defvar +unix-time-difference+
206 (encode-universal-time 0 0 0 1 1 1970 0))
208 (defun unix-time (&optional (universal-time (get-universal-time)))
209 (- universal-time +unix-time-difference+))
211 (defun octet-vector (&rest octets)
212 (make-array (length octets) :element-type 'octet
213 :initial-contents octets))
215 (defun keywordify (string-designator)
216 (intern (string string-designator) :keyword))
218 (defun make-octet-vector (size)
219 (make-array size :element-type 'octet))
221 (defun now+ (delta)
222 (+ (get-universal-time) delta))
224 (defun now- (delta)
225 (- (get-universal-time) delta))
227 (defun copy-n-octets (count input output)
228 "Copy the first N octets from the stream INPUT to the stream OUTPUT."
229 (let ((buffer (make-octet-vector 4096)))
230 (multiple-value-bind (loops rest)
231 (truncate count 4096)
232 (dotimes (i loops)
233 (read-sequence buffer input)
234 (write-sequence buffer output))
235 (let ((trailing-count (read-sequence buffer input :end rest)))
236 (assert (= trailing-count rest))
237 (write-sequence buffer output :end rest)))))
239 (defun starts-with (prefix string)
240 (and (<= (length prefix) (length string))
241 (string= prefix string :end2 (length prefix))))
243 (defun ends-with (suffix string)
244 (and (<= (length suffix) (length string))
245 (string= suffix string :start2 (- (length string)
246 (length suffix)))))
248 ;;; Getting stream/file subset vectors
250 (defparameter *file-buffer-size* 8192)
252 (defun make-file-buffer ()
253 (make-octet-vector *file-buffer-size*))
255 (defun read-exactly-n-octets (stream n &optional buffer)
256 "Read exactly N octets from STREAM into BUFFER. If fewer than N
257 octets are read, signal an CL:END-OF-FILE error. If BUFFER is not
258 supplied or is NIL, create a fresh buffer of length N and return it."
259 (unless buffer
260 (setf buffer (make-octet-vector n)))
261 (let ((end (min (length buffer) n)))
262 (let ((count (read-sequence buffer stream :end end)))
263 (unless (= n count)
264 (error 'end-of-file :stream stream))
265 buffer)))
267 (defun read-complete-file-buffer (stream &optional buffer)
268 "Read a complete buffer of size *FILE-BUFFER-SIZE*."
269 (read-exactly-n-octets stream *file-buffer-size* buffer))
271 (defun merge-file-buffers (buffers size)
272 "Create one big vector from BUFFERS and TRAILER."
273 (let ((output (make-octet-vector size))
274 (start 0))
275 (dotimes (i (ceiling size *file-buffer-size*))
276 (replace output (pop buffers) :start1 start)
277 (incf start *file-buffer-size*))
278 output))
280 (defun skip-stream-octets (stream count)
281 "Read and discard COUNT octets from STREAM."
282 (let ((buffer (make-file-buffer)))
283 (multiple-value-bind (loops rest)
284 (truncate count *file-buffer-size*)
285 (dotimes (i loops)
286 (read-complete-file-buffer stream buffer))
287 (read-exactly-n-octets stream rest buffer)))
290 (defun drained-stream-vector (stream)
291 "Read octets from STREAM until EOF and them as an octet vector."
292 (let ((buffers '())
293 (size 0))
294 (loop
295 (let* ((buffer (make-file-buffer))
296 (count (read-sequence buffer stream)))
297 (incf size count)
298 (push buffer buffers)
299 (when (/= count *file-buffer-size*)
300 (return (merge-file-buffers (nreverse buffers) size)))))))
303 (defun partial-stream-vector (stream n)
304 "Read N octets from STREAM and return them in an octet vector."
305 (let ((buffers '()))
306 (multiple-value-bind (loops rest)
307 (truncate n *file-buffer-size*)
308 (dotimes (i loops)
309 (let ((buffer (make-file-buffer)))
310 (read-complete-file-buffer stream buffer)
311 (push buffer buffers)))
312 (push (read-exactly-n-octets stream rest) buffers)
313 (merge-file-buffers (nreverse buffers) n))))
315 (defun stream-subset-vector (stream start end)
316 (unless start
317 (setf start 0))
318 (when (minusp start)
319 (error "START must be non-negative"))
320 (when (and end (< end start))
321 (error "END must be greater than START"))
322 (when (plusp start)
323 (skip-stream-octets stream start))
324 (if (not end)
325 (drained-stream-vector stream)
326 (partial-stream-vector stream (- end start))))
328 (defun file-subset-vector (file start end)
329 (with-open-file (stream file :element-type 'octet)
330 (stream-subset-vector stream start end)))
332 (defun alist-plist (alist)
333 (loop for (key . value) in alist
334 collect key collect value))