0.9.11.31: misc win32 improvements
[sbcl.git] / contrib / asdf-install / installer.lisp
1 (in-package :asdf-install)
2
3 (defvar *proxy* (posix-getenv "http_proxy"))
4 (defvar *cclan-mirror*
5   (or (posix-getenv "CCLAN_MIRROR")
6       "http://ftp.linux.org.uk/pub/lisp/cclan/"))
7
8 (defun directorify (name)
9   ;; input name may or may not have a training #\/, but we know we
10   ;; want a directory
11   (let ((path (pathname name)))
12     (if (pathname-name path)
13         (merge-pathnames
14          (make-pathname :directory `(:relative ,(pathname-name path)))
15          (make-pathname :directory (pathname-directory path)
16                         :host (pathname-host path)))
17         path)))
18
19 (defvar *sbcl-home* (directorify (posix-getenv "SBCL_HOME")))
20 (defvar *dot-sbcl*
21   (merge-pathnames (make-pathname :directory '(:relative ".sbcl"))
22                    (user-homedir-pathname)))
23
24 (defparameter *trusted-uids* nil)
25
26 (defvar *locations*
27   `((,(merge-pathnames "site/" *sbcl-home*)
28      ,(merge-pathnames "site-systems/" *sbcl-home*)
29      "System-wide install")
30     (,(merge-pathnames "site/" *dot-sbcl*)
31      ,(merge-pathnames "systems/" *dot-sbcl*)
32      "Personal installation")))
33
34 (let* ((*package* (find-package :asdf-install-customize))
35        (file (probe-file (merge-pathnames
36                           (make-pathname :name ".asdf-install")
37                           (user-homedir-pathname)))))
38   (when file (load file)))
39
40 (define-condition download-error (error)
41   ((url :initarg :url :reader download-url)
42    (response :initarg :response :reader download-response))
43   (:report (lambda (c s)
44              (format s "Server responded ~A for GET ~A"
45                      (download-response c) (download-url c)))))
46
47 (define-condition signature-error (error)
48   ((cause :initarg :cause :reader signature-error-cause))
49   (:report (lambda (c s)
50              (format s "Cannot verify package signature:  ~A"
51                      (signature-error-cause c)))))
52
53 (define-condition gpg-error (error)
54   ((message :initarg :message :reader gpg-error-message))
55   (:report (lambda (c s)
56              (format s "GPG failed with error status:~%~S"
57                      (gpg-error-message c)))))
58
59 (define-condition no-signature (gpg-error) ())
60 (define-condition key-not-found (gpg-error)
61   ((key-id :initarg :key-id :reader key-id))
62   (:report (lambda (c s)
63              (format s "No key found for key id 0x~A.  Try some command like ~%  gpg  --recv-keys 0x~A"
64                      (key-id c) (key-id c)))))
65
66 (define-condition key-not-trusted (gpg-error)
67   ((key-id :initarg :key-id :reader key-id)
68    (key-user-name :initarg :key-user-name :reader key-user-name))
69   (:report (lambda (c s)
70              (format s "GPG warns that the key id 0x~A (~A) is not fully trusted"
71                      (key-id c) (key-user-name c)))))
72 (define-condition author-not-trusted (gpg-error)
73   ((key-id :initarg :key-id :reader key-id)
74    (key-user-name :initarg :key-user-name :reader key-user-name))
75   (:report (lambda (c s)
76              (format s "~A (key id ~A) is not on your package supplier list"
77                      (key-user-name c) (key-id c)))))
78
79 (defun url-host (url)
80   (assert (string-equal url "http://" :end1 7))
81   (let* ((port-start (position #\: url :start 7))
82          (host-end (min (or (position #\/ url :start 7) (length url))
83                         (or port-start (length url)))))
84     (subseq url 7 host-end)))
85
86 (defun url-port (url)
87   (assert (string-equal url "http://" :end1 7))
88   (let ((port-start (position #\: url :start 7)))
89     (if port-start (parse-integer url :start (1+ port-start) :junk-allowed t) 80)))
90
91 (defun request-uri (url)
92   (assert (string-equal url "http://" :end1 7))
93   (if *proxy*
94       url
95       (let ((path-start (position #\/ url :start 7)))
96         (subseq url path-start))))
97
98 (defun url-connection (url)
99   (let ((s (make-instance 'inet-socket :type :stream :protocol :tcp))
100         (host (url-host url))
101         (port (url-port url))
102         result)
103     (declare (ignore port))
104     (unwind-protect
105         (progn
106           (socket-connect
107            s (car (host-ent-addresses (get-host-by-name (url-host (or *proxy* url)))))
108            (url-port (or  *proxy* url)))
109           (let ((stream (socket-make-stream s :input t :output t :buffering :full
110                                             :element-type :default :external-format :iso-8859-1)))
111             ;; we are exceedingly unportable about proper line-endings here.
112             ;; Anyone wishing to run this under non-SBCL should take especial care
113             (format stream "GET ~A HTTP/1.0~c~%~
114                             Host: ~A~c~%~
115                             Cookie: CCLAN-SITE=~A~c~%~c~%"
116                     (request-uri url) #\Return
117                     host #\Return
118                     *cclan-mirror* #\Return #\Return)
119             (force-output stream)
120             (setf result
121                   (list
122                    (let* ((l (read-line stream))
123                           (space (position #\Space l)))
124                      (parse-integer l :start (1+ space) :junk-allowed t))
125                    (loop for line = (read-line stream nil nil)
126                          until (or (null line) (eql (elt line 0) (code-char 13)))
127                          collect
128                          (let ((colon (position #\: line)))
129                            (cons (intern (string-upcase (subseq line 0 colon)) :keyword)
130                                  (string-trim (list #\Space (code-char 13))
131                                               (subseq line (1+ colon))))))
132                    stream))))
133       (when (and (null result)
134                  (socket-open-p s))
135         (socket-close s)))))
136
137
138 (defun copy-stream (in out)
139   (let ((buf (make-array 8192 :element-type (stream-element-type in))))
140     (loop for pos = (read-sequence buf in)
141           until (zerop pos)
142           do (write-sequence buf out :end pos))))
143
144 (defun download-files-for-package (package-name-or-url file-name)
145   (let ((url
146          (if (= (mismatch package-name-or-url "http://") 7)
147              package-name-or-url
148              (format nil "http://www.cliki.net/~A?download"
149                      package-name-or-url))))
150     (destructuring-bind (response headers stream)
151         (block got
152           (loop
153            (destructuring-bind (response headers stream) (url-connection url)
154              (unless (member response '(301 302))
155                (return-from got (list response headers stream)))
156              (close stream)
157              (setf url (cdr (assoc :location headers))))))
158       (if (>= response 400)
159         (error 'download-error :url url :response response))
160       (let ((length (parse-integer
161                      (or (cdr (assoc :content-length headers)) "")
162                      :junk-allowed t)))
163         (format t "Downloading ~A bytes from ~A ..."
164                 (if length length "some unknown number of") url)
165         (force-output)
166         (with-open-file (out file-name :direction :output
167                              :element-type '(unsigned-byte 8))
168           (if length
169               (let ((buf (make-array length :element-type '(unsigned-byte 8))))
170                 (read-sequence buf stream)
171                 (write-sequence buf out))
172               (copy-stream stream out))))
173       (close stream)
174       (terpri)
175       (restart-case
176           (verify-gpg-signature/url url file-name)
177         (skip-gpg-check ()
178           :report "Don't check GPG signature for this package"
179           nil)))))
180
181 (defun read-until-eof (stream)
182   (with-output-to-string (o)
183     (copy-stream stream o)))
184
185 (defun verify-gpg-signature/string (string file-name)
186   (let* ((proc
187           (sb-ext:run-program
188            "gpg"
189            (list
190             "--status-fd" "1" "--verify" "-"
191             (namestring file-name))
192            :output :stream :error :stream :search t
193            :input (make-string-input-stream string) :wait t))
194          (err (read-until-eof (process-error proc)))
195          tags)
196     (loop for l = (read-line (process-output proc) nil nil)
197           while l
198           when (> (mismatch l "[GNUPG:]") 6)
199           do (destructuring-bind (_ tag &rest data) (asdf::split l)
200                (declare (ignore _))
201                (pushnew (cons (intern tag :keyword)
202                               data) tags)))
203     ;; test for obvious key/sig problems
204     (let ((errsig (assoc :errsig tags)))
205       (and errsig (error 'key-not-found :key-id (second errsig) :gpg-err err)))
206     (let ((badsig (assoc :badsig tags)))
207       (and badsig (error 'key-not-found :key-id (second badsig) :gpg-err err)))
208     (let* ((good (assoc :goodsig tags))
209            (id (second good))
210            (name (format nil "~{~A~^ ~}" (nthcdr 2 good))))
211       ;; good signature, but perhaps not trusted
212       (unless (or (assoc :trust_ultimate tags)
213                   (assoc :trust_fully tags))
214         (cerror "Install the package anyway"
215                 'key-not-trusted
216                 :key-user-name name
217                 :key-id id :gpg-err err))
218       (loop
219        (when
220            (restart-case
221                (or (assoc id *trusted-uids* :test #'equal)
222                    (error 'author-not-trusted
223                           :key-user-name name
224                           :key-id id :gpg-err nil))
225              (add-key ()
226                :report "Add to package supplier list"
227                (pushnew (list id name) *trusted-uids*)))
228          (return))))))
229
230
231
232 (defun verify-gpg-signature/url (url file-name)
233   (destructuring-bind (response headers stream)
234       (url-connection (concatenate 'string url ".asc"))
235     (unwind-protect
236          (if (= response 200)
237              (let ((data (make-string (parse-integer
238                                        (cdr (assoc :content-length headers))
239                                        :junk-allowed t))))
240                (read-sequence data stream)
241                (verify-gpg-signature/string data file-name))
242              (error 'download-error :url  (concatenate 'string url ".asc")
243                     :response response))
244       (close stream))))
245
246 (defun where ()
247   (format t "Install where?~%")
248   (loop for (source system name) in *locations*
249         for i from 1
250         do (format t "~A) ~A: ~%   System in ~A~%   Files in ~A ~%"
251                    i name system source))
252   (format t " --> ") (force-output)
253   (let ((response (read)))
254     (when (> response 0)
255       (elt *locations* (1- response)))))
256
257 (defun install-package (source system packagename)
258   "Returns a list of asdf system names for installed asdf systems"
259   (ensure-directories-exist source)
260     (ensure-directories-exist system)
261   (let* ((tar
262           (with-output-to-string (o)
263             (or
264              (sb-ext:run-program #-darwin "tar"
265                                  #+darwin "gnutar"
266                                  (list "-C" (namestring source)
267                                        "-xzvf" (namestring packagename))
268                                  :output o
269                                  :search t
270                                  :wait t)
271              (error "can't untar"))))
272          (dummy (princ tar))
273          (pos-slash (position #\/ tar))
274          (*default-pathname-defaults*
275           (merge-pathnames
276            (make-pathname :directory
277                           `(:relative ,(subseq tar 0 pos-slash)))
278            source)))
279     (declare (ignore dummy))
280     (loop for asd in (directory
281                       (make-pathname :name :wild :type "asd"))
282           do (let ((target (merge-pathnames
283                             (make-pathname :name (pathname-name asd)
284                                            :type (pathname-type asd))
285                             system)))
286                (when (probe-file target)
287                  (sb-posix:unlink target))
288                #-win32
289                (sb-posix:symlink asd target))
290           collect (pathname-name asd))))
291
292 (defvar *temporary-files*)
293 (defun temp-file-name (p)
294   (let* ((pos-slash (position #\/ p :from-end t))
295          (pos-dot (position #\. p :start (or pos-slash 0))))
296     (merge-pathnames
297      (make-pathname
298       :name (subseq p (if pos-slash (1+ pos-slash) 0) pos-dot)
299       :type "asdf-install-tmp"))))
300
301
302 ;; this is the external entry point
303 (defun install (&rest packages)
304   (let ((*temporary-files* nil)
305         (*trusted-uids*
306          (let ((p (merge-pathnames "trusted-uids.lisp" *dot-sbcl*)))
307            (when (probe-file p)
308              (with-open-file (f p) (read f))))))
309     (unwind-protect
310          (destructuring-bind (source system name) (where)
311            (declare (ignore name))
312            (labels ((one-iter (packages)
313                       (dolist (asd
314                                 (loop for p in (mapcar 'string packages)
315                                       unless (probe-file p)
316                                       do (let ((tmp (temp-file-name p)))
317                                            (pushnew tmp *temporary-files*)
318                                            (download-files-for-package p tmp)
319                                            (setf p tmp))
320                                       end
321                                       do (format t "Installing ~A in ~A,~A~%"
322                                                  p source system)
323                                       append (install-package source system p)))
324                         (handler-bind
325                             ((asdf:missing-dependency
326                               (lambda (c)
327                                 (format t
328                                         "Downloading package ~A, required by ~A~%"
329                                         (asdf::missing-requires c)
330                                         (asdf:component-name
331                                          (asdf::missing-required-by c)))
332                                 (one-iter (list
333                                            (symbol-name
334                                             (asdf::missing-requires c))))
335                                 (invoke-restart 'retry))))
336                           (loop
337                            (multiple-value-bind (ret restart-p)
338                                (with-simple-restart
339                                    (retry "Retry installation")
340                                  (asdf:operate 'asdf:load-op asd))
341                              (declare (ignore ret))
342                              (unless restart-p (return))))))))
343              (one-iter packages)))
344       (let ((p (merge-pathnames "trusted-uids.lisp" *dot-sbcl*)))
345         (ensure-directories-exist p)
346         (with-open-file (out p :direction :output :if-exists :supersede)
347           (with-standard-io-syntax
348             (prin1 *trusted-uids* out))))
349       (dolist (l *temporary-files*)
350         (when (probe-file l) (delete-file l))))))
351
352 (defun uninstall (system &optional (prompt t))
353   (let* ((asd (asdf:system-definition-pathname system))
354          (system (asdf:find-system system))
355          (dir (asdf::pathname-sans-name+type
356                (asdf::resolve-symlinks asd))))
357     (when (or (not prompt)
358               (y-or-n-p
359                "Delete system ~A~%asd file: ~A~%sources: ~A~%Are you sure?"
360                system asd dir))
361       (delete-file asd)
362       (asdf:run-shell-command "rm -r ~A" (namestring dir)))))
363
364 ;;; some day we will also do UPGRADE, but we need to sort out version
365 ;;; numbering a bit better first