Debian Codegraph @

contrib/ecl-curl/ecl-curl.lisp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: C -*-
2 ;;;
3 ;;; ecl-curl.lisp - download of files via http
4 ;;;
5 ;;; (c) 2011, Juan Jose Garcia-Ripoll
6 ;;;
7 ;;; THIS CODE IS BASED ON ASDF-INSTALL. AS SUCH IT RETAINS THE FOLLOWING
8 ;;; COPYRIGHT NOTICE
9 ;;;
10 ;;; The original ASDF-INSTALL code (the files Makefile, README,
11 ;;; asdf-install.asd, defpackage.lisp, and installer.lisp) was written by
12 ;;; Daniel Barlow <[email protected]> and is distributed with SBCL and
13 ;;; therefore in the public domain. The SBCL Common Lisp implementation
14 ;;; can be obtained from Sourceforge: <http://sbcl.sf.net/>.
15 ;;;
16 ;;; The initial port of ASDF-INSTALL to other Lisps was done by Dr. Edmund
17 ;;; Weitz <[email protected]> and included the file port.lisp and some
18 ;;; changes to the files mentioned above. More code was provided by Marco
19 ;;; Baringer <[email protected]> (OpenMCL port), James Anderson
20 ;;; <[email protected]> (MCL port, including the file digitool.lisp),
21 ;;; Kiyoshi Mizumaru <[email protected]>, Robert P. Goldman
22 ;;; <[email protected]>, and Raymond Toy <[email protected]>
23 ;;; (bugfixes). Marco Antoniotti <[email protected]> added support for
24 ;;; MK:DEFSYSTEM which includes the files load-asdf-install.lisp,
25 ;;; loader.lisp, and finally split-sequence.lisp which has its own
26 ;;; copyright notice. ASDF-Install is currently maintained by Gary King
27 ;;; <[email protected]> and is hosted on Common-Lisp.net.
28 ;;;
29 ;;; The complete code distributed with this archive (asdf-install.tar.gz)
30 ;;; is copyrighted by the above-mentioned authors and governed by the
31 ;;; following license.
32 ;;;
33 ;;; Redistribution and use in source and binary forms, with or without
34 ;;; modification, are permitted provided that the following conditions are
35 ;;; met:
36 ;;;
37 ;;; * Redistributions of source code must retain the above copyright
38 ;;; notice, this list of conditions and the following disclaimer.
39 ;;;
40 ;;; * Redistributions in binary form must reproduce the above
41 ;;; copyright notice, this list of conditions and the following
42 ;;; disclaimer in the documentation and/or other materials
43 ;;; provided with the distribution.
44 ;;;
45 ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS 'AS IS' AND ANY EXPRESSED OR
46 ;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
47 ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48 ;;; DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT,
49 ;;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
50 ;;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
51 ;;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 ;;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
53 ;;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
54 ;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
55 ;;; POSSIBILITY OF SUCH DAMAGE.
56
57 (require :sockets)
58
59 (defpackage #:ecl-curl
60 (:use #:sb-bsd-sockets #:cl)
61 (:export #:download-url-to-file
62 #:download-error
63 #:download-url
64 #:download-response))
65
66 (in-package "ECL-CURL")
67
68 ;;;---------------------------------------------------------------------------
69 ;;; CONDITIONS
70 ;;;
71
72 (define-condition http-transfer-error (error)
73 ((url :initarg :url :reader download-url)))
74
75 (define-condition download-error (http-transfer-error)
76 ((response :initarg :response :reader download-response))
77 (:report (lambda (c s)
78 (format s "Server responded ~A for GET ~A"
79 (download-response c) (download-url c)))))
80
81 ;;;---------------------------------------------------------------------------
82 ;;; PORTABILITY LAYER
83 ;;;
84
85 (defvar *stream-buffer-size* 8192)
86
87 (defun copy-stream (from to)
88 "Copy into TO from FROM until end of the input stream, in blocks of
89 *stream-buffer-size*. The streams should have the same element type."
90 (unless (subtypep (stream-element-type to) (stream-element-type from))
91 (error "Incompatible streams ~A and ~A." from to))
92 (let ((buf (make-array *stream-buffer-size*
93 :element-type (stream-element-type from))))
94 (loop
95 (let ((pos #-(or :clisp :cmu) (read-sequence buf from)
96 #+:clisp (ext:read-byte-sequence buf from :no-hang nil)
97 #+:cmu (sys:read-n-bytes from buf 0 *stream-buffer-size* nil)))
98 (when (zerop pos) (return))
99 (write-sequence buf to :end pos)))))
100
101 (defun make-stream-from-url (url)
102 (let ((s (make-instance 'sb-bsd-sockets:inet-socket
103 :type :stream
104 :protocol :tcp)))
105 (sb-bsd-sockets:socket-connect
106 s (car (sb-bsd-sockets:host-ent-addresses
107 (sb-bsd-sockets:get-host-by-name (url-host url))))
108 (url-port url))
109 (sb-bsd-sockets:socket-make-stream
110 s
111 :input t
112 :output t
113 :buffering :full
114 :external-format #+unicode :iso-8859-1 #-unicode :default)))
115
116 ;;;---------------------------------------------------------------------------
117 ;;; URL handling.
118 ;;;
119
120 (defun url-host (url)
121 (assert (string-equal url "http://" :end1 7))
122 (let* ((port-start (position #\: url :start 7))
123 (host-end (min (or (position #\/ url :start 7) (length url))
124 (or port-start (length url)))))
125 (subseq url 7 host-end)))
126
127 (defun url-port (url)
128 (assert (string-equal url "http://" :end1 7))
129 (let ((port-start (position #\: url :start 7)))
130 (if port-start
131 (parse-integer url :start (1+ port-start) :junk-allowed t) 80)))
132
133 ; This is from Juri Pakaste's <[email protected]> base64.lisp
134 (defparameter *encode-table*
135 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
136
137 (defun base64-encode (string)
138 (let ((result (make-array
139 (list (* 4 (truncate (/ (+ 2 (length string)) 3))))
140 :element-type 'base-char)))
141 (do ((sidx 0 (+ sidx 3))
142 (didx 0 (+ didx 4))
143 (chars 2 2)
144 (value nil nil))
145 ((>= sidx (length string)) t)
146 (setf value (ash (logand #xFF (char-code (char string sidx))) 8))
147 (dotimes (n 2)
148 (when (< (+ sidx n 1) (length string))
149 (setf value
150 (logior value
151 (logand #xFF (char-code (char string (+ sidx n 1))))))
152 (incf chars))
153 (when (= n 0)
154 (setf value (ash value 8))))
155 (setf (elt result (+ didx 3))
156 (elt *encode-table* (if (> chars 3) (logand value #x3F) 64)))
157 (setf value (ash value -6))
158 (setf (elt result (+ didx 2))
159 (elt *encode-table* (if (> chars 2) (logand value #x3F) 64)))
160 (setf value (ash value -6))
161 (setf (elt result (+ didx 1))
162 (elt *encode-table* (logand value #x3F)))
163 (setf value (ash value -6))
164 (setf (elt result didx)
165 (elt *encode-table* (logand value #x3F))))
166 result))
167
168 (defvar *proxy* (ext:getenv "http_proxy"))
169
170 (defvar *proxy-user* nil)
171
172 (defvar *proxy-passwd* nil)
173
174 (defun request-uri (url)
175 (assert (string-equal url "http://" :end1 7))
176 (if *proxy*
177 url
178 (let ((path-start (position #\/ url :start 7)))
179 (if path-start
180 (subseq url path-start)
181 "/index.html"))))
182
183 ;;;---------------------------------------------------------------------------
184 ;;; CONNECTION & HEADRE
185 ;;;
186
187 (defun header-pair (name headers)
188 "Searchers headers for name _without_ case sensitivity. Headers should be an alist mapping symbols to values; name a symbol. Returns the \(name value\) pair if name is found or nil if it is not."
189 (assoc name headers
190 :test (lambda (a b)
191 (string-equal (symbol-name a) (symbol-name b)))))
192
193 (defun header-value (name headers)
194 "Searchers headers for name _without_ case sensitivity. Headers should be an alist mapping symbols to values; name a symbol. Returns the value if name is found or nil if it is not."
195 (cdr (header-pair name headers)))
196
197 (defun url-connection (url)
198 (let ((stream (make-stream-from-url (or *proxy* url)))
199 (host (url-host url)))
200 (format stream "GET ~A HTTP/1.0~C~CHost: ~A~C~C"
201 (request-uri url) #\Return #\Linefeed
202 host #\Return #\Linefeed)
203 (when (and *proxy-passwd* *proxy-user*)
204 (format stream "Proxy-Authorization: Basic ~A~C~C"
205 (base64-encode (format nil "~A:~A" *proxy-user* *proxy-passwd*))
206 #\Return #\Linefeed))
207 (format stream "~C~C" #\Return #\Linefeed)
208 (force-output stream)
209 (values
210 (let* ((l (read-line stream))
211 (space (position #\Space l)))
212 (parse-integer l :start (1+ space) :junk-allowed t))
213 (loop for line = (read-line stream)
214 until (or (null line)
215 (zerop (length line))
216 (eql (elt line 0) (code-char 13)))
217 collect
218 (let ((colon (position #\: line)))
219 (cons (intern (string-upcase (subseq line 0 colon)) :keyword)
220 (string-trim (list #\Space (code-char 13))
221 (subseq line (1+ colon))))))
222 stream)))
223
224 ;;;---------------------------------------------------------------------------
225 ;;; DOWNLOAD
226 ;;;
227
228 (defun download-url-to-file (url file-name &key quiet)
229 "Resolves url and then downloads it to file-name; returns the url actually used."
230 (multiple-value-bind (response headers stream)
231 (loop
232 (multiple-value-bind (response headers stream)
233 (url-connection url)
234 (unless (member response '(301 302))
235 (return (values response headers stream)))
236 (close stream)
237 (setf url (header-value :location headers))))
238 (when (>= response 400)
239 (error 'download-error :url url :response response))
240 (let ((length (parse-integer (or (header-value :content-length headers) "")
241 :junk-allowed t)))
242 (unless quiet
243 (format t "~&;;; Downloading ~A bytes from ~A to ~A ...~%"
244 (or length "some unknown number of")
245 url
246 file-name))
247 (force-output)
248 (let ((ok? nil) (o nil))
249 (unwind-protect
250 (progn
251 (setf o (open file-name
252 :direction :output :if-exists :supersede
253 :external-format
254 #-unicode :default
255 #+unicode :latin-1))
256 (if length
257 (let ((buf (make-array length
258 :element-type
259 (stream-element-type stream))))
260 (read-sequence buf stream)
261 (write-sequence buf o))
262 (copy-stream stream o))
263 (setf ok? t))
264 (when o (close o :abort (null ok?))))))
265 (close stream))
266 (values url))
267
268 (provide '#:ecl-curl)