Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 291 lines (271 sloc) 10.646 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
;;;;
;;;; Copyright (c) 2008 Zachary Beane, All Rights Reserved
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions
;;;; are met:
;;;;
;;;; * Redistributions of source code must retain the above copyright
;;;; notice, this list of conditions and the following disclaimer.
;;;;
;;;; * Redistributions in binary form must reproduce the above
;;;; copyright notice, this list of conditions and the following
;;;; disclaimer in the documentation and/or other materials
;;;; provided with the distribution.
;;;;
;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;
;;;; request.lisp

(in-package #:zs3)

(defvar *s3-endpoint* "s3.amazonaws.com")
(defvar *use-ssl* nil)
(defvar *use-content-md5* t)

(defclass request ()
  ((credentials
    :initarg :credentials
    :accessor credentials
    :documentation "An object that has methods for ACCESS-KEY and
SECRET-KEY. A list of two strings (the keys) suffices.")
   (endpoint
    :initarg :endpoint
    :accessor endpoint)
   (ssl
    :initarg :ssl
    :accessor ssl)
   (method
    :initarg :method
    :accessor method
    :documentation "e.g. :GET, :PUT, :DELETE")
   (bucket
    :initarg :bucket
    :accessor bucket
    :documentation
    "A string naming the bucket to address in the request. If NIL,
request is not directed at a specific bucket.")
   (key
    :initarg :key
    :accessor key
    :documentation
    "A string naming the key to address in the request. If NIL,
request is not directed at a specific key.")
   (sub-resource
    :initarg :sub-resource
    :accessor sub-resource
    :documentation "A sub-resource to address as part of the request,
without a leading \"?\", e.g. \"acl\", \"torrent\". If PARAMETERS
is set, this must be NIL.")
   (parameters
    :initarg :parameters
    :accessor parameters
    :documentation
    "An alist of string key/value pairs to send as CGI-style GET
parameters with the request. If SUB-RESOURCE is set, these must be
NIL.")
   (content-type
    :initarg :content-type
    :accessor content-type)
   (content-md5
    :initarg :content-md5
    :accessor content-md5)
   (content-length
    :initarg :content-length
    :accessor content-length)
   (content
    :initarg :content
    :accessor content)
   (metadata
    :initarg :metadata
    :accessor metadata
    :documentation
    "An alist of Amazon metadata to attach to a request. These should
be straight string key/value pairs, WITHOUT any \"x-amz-meta-\"
prefix.")
   (amz-headers
    :initarg :amz-headers
    :accessor amz-headers
    :documentation
    "An alist of extra Amazon request headers. These should be
straight string key/value pairs, WITHOUT any \"x-amz-\" prefix.")
   (date
    :initarg :date
    :accessor date)
   (signed-string
    :initarg :signed-string
    :accessor signed-string)
   (extra-http-headers
    :initarg :extra-http-headers
    :accessor extra-http-headers
    :documentation "An alist of extra HTTP headers to include in the request."))
  (:default-initargs
   ;; :date and :content-md5 are specially treated, should not be nil
   :credentials *credentials*
   :method :get
   :endpoint *s3-endpoint*
   :ssl *use-ssl*
   :bucket nil
   :key nil
   :sub-resource nil
   :parameters nil
   :content-type nil
   :content-length t
   :content nil
   :metadata nil
   :amz-headers nil
   :extra-http-headers nil))

(defmethod slot-unbound ((class t) (request request) (slot (eql 'date)))
  (setf (date request) (get-universal-time)))

(defmethod slot-unbound ((class t) (request request) (slot (eql 'content-md5)))
  (setf (content-md5 request)
        (and *use-content-md5*
             (pathnamep (content request))
             (file-md5/b64 (content request)))))

(defmethod initialize-instance :after ((request request)
                                       &rest initargs &key
                                       &allow-other-keys)
  (declare (ignore initargs))
  (unless (integerp (content-length request))
    (let ((content (content request)))
      (setf (content-length request)
            (etypecase content
              (null 0)
              (pathname (file-size content))
              (vector (length content)))))))

(defgeneric http-method (request)
  (:method (request)
    (string-upcase (method request))))

(defun puri-canonicalized-path (path)
  (let ((parsed (puri:parse-uri (format nil "http://dummy~A" path))))
    (with-output-to-string (stream)
      (if (puri:uri-path parsed)
          (write-string (puri:uri-path parsed) stream)
          (write-string "/" stream))
      (when (puri:uri-query parsed)
        (write-string "?" stream)
        (write-string (puri:uri-query parsed) stream)))))

(defgeneric signed-path (request)
  (:method (request)
    (let ((*print-pretty* nil))
      (puri-canonicalized-path
       (with-output-to-string (stream)
         (write-char #\/ stream)
         (when (bucket request)
           (write-string (url-encode (name (bucket request))) stream)
           (write-char #\/ stream))
         (when (key request)
           (write-string (url-encode (name (key request))) stream))
         (when (sub-resource request)
           (write-string "?" stream)
           (write-string (url-encode (sub-resource request)) stream)))))))

(defgeneric request-path (request)
  (:method (request)
    (let ((*print-pretty* nil))
      (with-output-to-string (stream)
        (write-char #\/ stream)
        (when (and (bucket request)
                   (string= (endpoint request) *s3-endpoint*))
          (write-string (url-encode (name (bucket request))) stream)
          (write-char #\/ stream))
        (when (key request)
          (write-string (url-encode (name (key request))) stream))
        (when (sub-resource request)
          (write-string "?" stream)
          (write-string (url-encode (sub-resource request)) stream))))))

(defgeneric all-amazon-headers (request)
  (:method (request)
    (nconc
     (loop for ((key . value)) on (amz-headers request)
           collect (cons (format nil "x-amz-~(~A~)" key)
                         value))
     (loop for ((key . value)) on (metadata request)
           collect (cons (format nil "x-amz-meta-~(~A~)" key)
                         value)))))

(defgeneric amazon-header-signing-lines (request)
  (:method (request)
    ;; FIXME: handle values with commas, and repeated headers
    (let* ((headers (all-amazon-headers request))
           (sorted (sort headers #'string< :key #'car)))
      (loop for ((key . value)) on sorted
            collect (format nil "~A:~A" key value)))))

(defgeneric date-string (request)
  (:method (request)
    (http-date-string (date request))))

(defgeneric signature (request)
  (:method (request)
    (let ((digester (make-digester (secret-key request))))
      (flet ((maybe-add-line (string digester)
               (if string
                   (add-line string digester)
                   (add-newline digester))))
        (add-line (http-method request) digester)
        (maybe-add-line (content-md5 request) digester)
        (maybe-add-line (content-type request) digester)
        (add-line (date-string request) digester)
        (dolist (line (amazon-header-signing-lines request))
          (add-line line digester))
        (add-string (signed-path request) digester)
        (setf (signed-string request)
              (get-output-stream-string (signed-stream digester)))
        (digest64 digester)))))
        
(defgeneric drakma-headers (request)
  (:method (request)
    (let ((base
           (list* (cons "Date" (http-date-string (date request)))
                  (cons "Authorization"
                        (format nil "AWS ~A:~A"
                                (access-key request)
                                (signature request)))
                  (all-amazon-headers request))))
      (when (content-md5 request)
        (push (cons "Content-MD5" (content-md5 request)) base))
      (append (extra-http-headers request) base))))

(defgeneric url (request)
  (:method (request)
    (format nil "http~@[s~*~]://~A~A"
            (ssl request)
            (endpoint request)
            (request-path request))))

(defun send-file-content (fun request)
  (with-open-file (stream (content request)
                          :element-type '(unsigned-byte 8))
    (let* ((buffer-size 8000)
           (buffer (make-octet-vector buffer-size)))
      (flet ((read-exactly (size)
               (assert (= size (read-sequence buffer stream)))))
        (multiple-value-bind (loops rest)
            (truncate (content-length request) buffer-size)
          (dotimes (i loops)
            (read-exactly buffer-size)
            (funcall fun buffer t))
          (read-exactly rest)
          (funcall fun (subseq buffer 0 rest) nil))))))

(defgeneric send (request &key want-stream)
  (:method (request &key want-stream)
    (let ((continuation
           (drakma:http-request (url request)
                                :redirect nil
                                :want-stream want-stream
                                :content-type (content-type request)
                                :additional-headers (drakma-headers request)
                                :method (method request)
                                :force-binary t
                                :content-length (content-length request)
                                :parameters (parameters request)
                                :content :continuation)))
      (let ((content (content request)))
        (if (pathnamep content)
            (send-file-content continuation request)
            (funcall continuation content nil))))))
    
(defmethod access-key ((request request))
  (access-key (credentials request)))

(defmethod secret-key ((request request))
  (secret-key (credentials request)))
Something went wrong with that request. Please try again.