Change how request parameters are passed.
[zs3.git] / utils.lisp
blobcf25d5f09b5bedb0edfaf3a69a7e96488a3e1213
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 (defun http-date-string (&optional (time (get-universal-time)))
38 "Return a HTTP-style date string."
39 (multiple-value-bind (second minute hour day month year day-of-week)
40 (decode-universal-time time 0)
41 (let ((*print-pretty* nil))
42 (format nil "~A, ~2,'0D ~A ~4,'0D ~2,'0D:~2,'0D:~2,'0D GMT"
43 (aref *days* day-of-week)
44 day
45 (aref *months* (1- month))
46 year
47 hour
48 minute
49 second))))
51 (defun iso8601-date-string (&optional (time (get-universal-time)))
52 "Return a HTTP-style date string."
53 (multiple-value-bind (second minute hour day month year day-of-week)
54 (decode-universal-time time 0)
55 (let ((*print-pretty* nil))
56 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0DZ"
57 year month day hour minute second))))
59 (defun string-octets (string)
60 "Return the UTF-8 encoding of STRING as a vector of octets."
61 (flexi-streams:string-to-octets string :external-format :utf-8))
63 (defun string64 (string)
64 (cl-base64:usb8-array-to-base64-string (string-octets string)))
66 (defun url-decode (string)
67 (with-output-to-string (out)
68 (let ((code 0))
69 (labels ((in-string (char)
70 (case char
71 (#\%
72 #'h1)
74 (write-char char out)
75 #'in-string)))
76 (weight (char)
77 (let ((weight (digit-char-p char 16)))
78 (unless weight
79 (error "~S is not a hex digit" char))
80 weight))
81 (h1 (char)
82 (setf code (ash (weight char) 4))
83 #'h2)
84 (h2 (char)
85 (incf code (weight char))
86 (write-char (code-char code) out)
87 #'in-string))
88 (let ((state #'in-string))
89 (loop for char across string
90 do (setf state (funcall state char))))))))
92 ;;; The following two functions were adatpted from Drakma source. The
93 ;;; only change is to escape space as "%20", not #\+
95 (defun url-encode (string)
96 "Returns a URL-encoded version of the string STRING using the
97 LispWorks external format EXTERNAL-FORMAT."
98 (let ((*print-pretty* nil))
99 (with-output-to-string (out)
100 (loop for octet across (string-octets (or string ""))
101 for char = (code-char octet)
102 do (cond ((or (char<= #\0 char #\9)
103 (char<= #\a char #\z)
104 (char<= #\A char #\Z)
105 (find char "$-_.!*'()," :test #'char=))
106 (write-char char out))
107 ((char= char #\Space)
108 (write-string "%20" out))
109 (t (format out "%~2,'0x" (char-code char))))))))
111 (defun alist-to-url-encoded-string (alist)
112 "ALIST is supposed to be an alist of name/value pairs where both
113 names and values are strings. This function returns a string where
114 this list is represented as for the content type
115 `application/x-www-form-urlencoded', i.e. the values are URL-encoded
116 using the external format EXTERNAL-FORMAT, the pairs are joined with a
117 #\\& character, and each name is separated from its value with a #\\=
118 character."
119 (let ((*print-pretty* nil))
120 (with-output-to-string (out)
121 (loop for first = t then nil
122 for (name . value) in alist
123 unless first do (write-char #\& out)
124 do (format out "~A=~A"
125 (url-encode name)
126 (url-encode value))))))
128 (defun save (response file)
129 "Write a sequence of octets RESPONSE to FILE."
130 (with-open-file (stream file :direction :output
131 :if-exists :supersede
132 :element-type '(unsigned-byte 8))
133 (write-sequence response stream))
134 (probe-file file))
136 (defun parse-amazon-timestamp (string)
137 "Convert the ISO 8601-format STRING to a universal time."
138 (flet ((number-at (start length)
139 (parse-integer string :start start :end (+ start length))))
140 (let ((year (number-at 0 4))
141 (month (number-at 5 2))
142 (day (number-at 8 2))
143 (hour (number-at 11 2))
144 (minute (number-at 14 2))
145 (second (number-at 17 2)))
146 (encode-universal-time second minute hour day month year 0))))
148 (defun stringify (thing)
149 (typecase thing
150 (string thing)
151 (symbol (symbol-name thing))
152 (t (princ-to-string thing))))
154 (defun parameters-alist (&rest args &key &allow-other-keys)
155 "Construct an ALIST based on all keyword arguments passed to the
156 function. Keywords are converted to their lowercase symbol name and
157 values are converted to strings."
158 (loop for (key value) on args by #'cddr
159 when value
160 collect (cons (if (symbolp key)
161 (string-downcase (symbol-name key))
162 key)
163 (stringify value))))
165 (defun last-entry (array)
166 "If ARRAY has one ore more entries, return the last one. Otherwise,
167 return NIL."
168 (and (plusp (length array))
169 (aref array (1- (length array)))))
171 (defun file-size (file)
172 (with-open-file (stream file :element-type '(unsigned-byte 8))
173 (file-length stream)))
175 (defvar +unix-time-difference+
176 (encode-universal-time 0 0 0 1 1 1970 0))
178 (defun unix-time (&optional (universal-time (get-universal-time)))
179 (- universal-time +unix-time-difference+))
181 (defun octet-vector (&rest octets)
182 (make-array (length octets) :element-type '(unsigned-byte 8)
183 :initial-contents octets))
185 (defun keywordify (string-designator)
186 (intern (string string-designator) :keyword))
188 (defun make-octet-vector (size)
189 (make-array size :element-type '(unsigned-byte 8)))
191 (defun now+ (delta)
192 (+ (get-universal-time) delta))
194 (defun now- (delta)
195 (- (get-universal-time) delta))
197 (defun copy-n-octets (count input output)
198 "Copy the first N octets from the stream INPUT to the stream OUTPUT."
199 (let ((buffer (make-octet-vector 4096)))
200 (multiple-value-bind (loops rest)
201 (truncate count 4096)
202 (dotimes (i loops)
203 (read-sequence buffer input)
204 (write-sequence buffer output))
205 (let ((trailing-count (read-sequence buffer input :end rest)))
206 (assert (= trailing-count rest))
207 (write-sequence buffer output :end rest)))))
209 (defun starts-with (prefix string)
210 (and (<= (length prefix) (length string))
211 (string= prefix string :end2 (length prefix))))
213 (defun ends-with (suffix string)
214 (and (<= (length suffix) (length string))
215 (string= suffix string :start2 (- (length string)
216 (length suffix)))))
218 ;;; Getting stream/file subset vectors
220 (defparameter *file-buffer-size* 8192)
222 (defun make-file-buffer ()
223 (make-octet-vector *file-buffer-size*))
225 (defun read-exactly-n-octets (stream n &optional buffer)
226 "Read exactly N octets from STREAM into BUFFER. If fewer than N
227 octets are read, signal an CL:END-OF-FILE error. If BUFFER is not
228 supplied or is NIL, create a fresh buffer of length N and return it."
229 (unless buffer
230 (setf buffer (make-octet-vector n)))
231 (let ((end (min (length buffer) n)))
232 (let ((count (read-sequence buffer stream :end end)))
233 (unless (= n count)
234 (error 'end-of-file :stream stream))
235 buffer)))
237 (defun read-complete-file-buffer (stream &optional buffer)
238 "Read a complete buffer of size *FILE-BUFFER-SIZE*."
239 (read-exactly-n-octets stream *file-buffer-size* buffer))
241 (defun merge-file-buffers (buffers size)
242 "Create one big vector from BUFFERS and TRAILER."
243 (let ((output (make-octet-vector size))
244 (start 0))
245 (dotimes (i (ceiling size *file-buffer-size*))
246 (replace output (pop buffers) :start1 start)
247 (incf start *file-buffer-size*))
248 output))
250 (defun skip-stream-octets (stream count)
251 "Read and discard COUNT octets from STREAM."
252 (let ((buffer (make-file-buffer)))
253 (multiple-value-bind (loops rest)
254 (truncate count *file-buffer-size*)
255 (dotimes (i loops)
256 (read-complete-file-buffer stream buffer))
257 (read-exactly-n-octets stream rest buffer)))
260 (defun drained-stream-vector (stream)
261 "Read octets from STREAM until EOF and them as an octet vector."
262 (let ((buffers '())
263 (size 0))
264 (loop
265 (let* ((buffer (make-file-buffer))
266 (count (read-sequence buffer stream)))
267 (incf size count)
268 (push buffer buffers)
269 (when (/= count *file-buffer-size*)
270 (return (merge-file-buffers (nreverse buffers) size)))))))
273 (defun partial-stream-vector (stream n)
274 "Read N octets from STREAM and return them in an octet vector."
275 (let ((buffers '()))
276 (multiple-value-bind (loops rest)
277 (truncate n *file-buffer-size*)
278 (dotimes (i loops)
279 (let ((buffer (make-file-buffer)))
280 (read-complete-file-buffer stream buffer)
281 (push buffer buffers)))
282 (push (read-exactly-n-octets stream rest) buffers)
283 (merge-file-buffers (nreverse buffers) n))))
285 (defun stream-subset-vector (stream start end)
286 (unless start
287 (setf start 0))
288 (when (minusp start)
289 (error "START must be non-negative"))
290 (when (and end (< end start))
291 (error "END must be greater than START"))
292 (when (plusp start)
293 (skip-stream-octets stream start))
294 (if (not end)
295 (stream-octets-until-eof stream)
296 (partial-stream-vector stream (- end start))))
298 (defun file-subset-vector (file start end)
299 (with-open-file (stream file :element-type '(unsigned-byte 8))
300 (stream-subset-vector stream start end)))