publish.scm 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2015 David Thompson <davet@gnu.org>
  3. ;;; Copyright © 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix scripts publish)
  20. #:use-module ((system repl server) #:prefix repl:)
  21. #:use-module (ice-9 binary-ports)
  22. #:use-module (ice-9 format)
  23. #:use-module (ice-9 match)
  24. #:use-module (ice-9 regex)
  25. #:use-module (ice-9 rdelim)
  26. #:use-module (ice-9 threads)
  27. #:use-module (rnrs bytevectors)
  28. #:use-module (srfi srfi-1)
  29. #:use-module (srfi srfi-2)
  30. #:use-module (srfi srfi-9)
  31. #:use-module (srfi srfi-9 gnu)
  32. #:use-module (srfi srfi-19)
  33. #:use-module (srfi srfi-26)
  34. #:use-module (srfi srfi-34)
  35. #:use-module (srfi srfi-37)
  36. #:use-module (web http)
  37. #:use-module (web request)
  38. #:use-module (web response)
  39. #:use-module (web server)
  40. #:use-module (web uri)
  41. #:autoload (sxml simple) (sxml->xml)
  42. #:use-module (guix base32)
  43. #:use-module (guix base64)
  44. #:use-module (guix config)
  45. #:use-module (guix derivations)
  46. #:use-module (gcrypt hash)
  47. #:use-module (guix pki)
  48. #:use-module (gcrypt pk-crypto)
  49. #:use-module (guix workers)
  50. #:use-module (guix store)
  51. #:use-module ((guix serialization) #:select (write-file))
  52. #:use-module (zlib)
  53. #:autoload (lzlib) (call-with-lzip-output-port
  54. make-lzip-output-port)
  55. #:use-module (guix cache)
  56. #:use-module (guix ui)
  57. #:use-module (guix scripts)
  58. #:use-module ((guix utils)
  59. #:select (with-atomic-file-output compressed-file?))
  60. #:use-module ((guix build utils)
  61. #:select (dump-port mkdir-p find-files))
  62. #:use-module ((guix build syscalls) #:select (set-thread-name))
  63. #:export (%public-key
  64. %private-key
  65. signed-string
  66. guix-publish))
  67. (define (show-help)
  68. (format #t (G_ "Usage: guix publish [OPTION]...
  69. Publish ~a over HTTP.\n") %store-directory)
  70. (display (G_ "
  71. -p, --port=PORT listen on PORT"))
  72. (display (G_ "
  73. --listen=HOST listen on the network interface for HOST"))
  74. (display (G_ "
  75. -u, --user=USER change privileges to USER as soon as possible"))
  76. (display (G_ "
  77. -C, --compression[=METHOD:LEVEL]
  78. compress archives with METHOD at LEVEL"))
  79. (display (G_ "
  80. -c, --cache=DIRECTORY cache published items to DIRECTORY"))
  81. (display (G_ "
  82. --workers=N use N workers to bake items"))
  83. (display (G_ "
  84. --ttl=TTL announce narinfos can be cached for TTL seconds"))
  85. (display (G_ "
  86. --nar-path=PATH use PATH as the prefix for nar URLs"))
  87. (display (G_ "
  88. --public-key=FILE use FILE as the public key for signatures"))
  89. (display (G_ "
  90. --private-key=FILE use FILE as the private key for signatures"))
  91. (display (G_ "
  92. -r, --repl[=PORT] spawn REPL server on PORT"))
  93. (newline)
  94. (display (G_ "
  95. -h, --help display this help and exit"))
  96. (display (G_ "
  97. -V, --version display version information and exit"))
  98. (newline)
  99. (show-bug-report-information))
  100. (define (getaddrinfo* host)
  101. "Like 'getaddrinfo', but properly report errors."
  102. (catch 'getaddrinfo-error
  103. (lambda ()
  104. (getaddrinfo host))
  105. (lambda (key error)
  106. (leave (G_ "lookup of host '~a' failed: ~a~%")
  107. host (gai-strerror error)))))
  108. ;; Nar compression parameters.
  109. (define-record-type <compression>
  110. (compression type level)
  111. compression?
  112. (type compression-type)
  113. (level compression-level))
  114. (define %no-compression
  115. (compression 'none 0))
  116. (define %default-gzip-compression
  117. ;; Since we compress on the fly, default to fast compression.
  118. (compression 'gzip 3))
  119. (define (default-compression type)
  120. (compression type 3))
  121. (define (actual-compressions item requested)
  122. "Return the actual compressions used for ITEM, which may be %NO-COMPRESSION
  123. if ITEM is already compressed."
  124. (if (compressed-file? item)
  125. (list %no-compression)
  126. requested))
  127. (define %options
  128. (list (option '(#\h "help") #f #f
  129. (lambda _
  130. (show-help)
  131. (exit 0)))
  132. (option '(#\V "version") #f #f
  133. (lambda _
  134. (show-version-and-exit "guix publish")))
  135. (option '(#\u "user") #t #f
  136. (lambda (opt name arg result)
  137. (alist-cons 'user arg result)))
  138. (option '(#\p "port") #t #f
  139. (lambda (opt name arg result)
  140. (alist-cons 'port (string->number* arg) result)))
  141. (option '("listen") #t #f
  142. (lambda (opt name arg result)
  143. (match (getaddrinfo* arg)
  144. ((info _ ...)
  145. (alist-cons 'address (addrinfo:addr info)
  146. result))
  147. (()
  148. (leave (G_ "lookup of host '~a' returned nothing")
  149. name)))))
  150. (option '(#\C "compression") #f #t
  151. (lambda (opt name arg result)
  152. (let* ((colon (string-index arg #\:))
  153. (type (cond
  154. (colon (string-take arg colon))
  155. ((string->number arg) "gzip")
  156. (else arg)))
  157. (level (if colon
  158. (string->number*
  159. (string-drop arg (+ 1 colon)))
  160. (or (string->number arg) 3))))
  161. (match level
  162. (0
  163. (alist-cons 'compression %no-compression result))
  164. (level
  165. (match (string->compression-type type)
  166. ((? symbol? type)
  167. (alist-cons 'compression
  168. (compression type level)
  169. result))
  170. (_
  171. (warning (G_ "~a: unsupported compression type~%")
  172. type)
  173. result)))))))
  174. (option '(#\c "cache") #t #f
  175. (lambda (opt name arg result)
  176. (alist-cons 'cache arg result)))
  177. (option '("workers") #t #f
  178. (lambda (opt name arg result)
  179. (alist-cons 'workers (string->number* arg)
  180. result)))
  181. (option '("ttl") #t #f
  182. (lambda (opt name arg result)
  183. (let ((duration (string->duration arg)))
  184. (unless duration
  185. (leave (G_ "~a: invalid duration~%") arg))
  186. (alist-cons 'narinfo-ttl (time-second duration)
  187. result))))
  188. (option '("nar-path") #t #f
  189. (lambda (opt name arg result)
  190. (alist-cons 'nar-path arg result)))
  191. (option '("public-key") #t #f
  192. (lambda (opt name arg result)
  193. (alist-cons 'public-key-file arg result)))
  194. (option '("private-key" "secret-key") #t #f
  195. (lambda (opt name arg result)
  196. (alist-cons 'private-key-file arg result)))
  197. (option '(#\r "repl") #f #t
  198. (lambda (opt name arg result)
  199. ;; If port unspecified, use default Guile REPL port.
  200. (let ((port (and arg (string->number* arg))))
  201. (alist-cons 'repl (or port 37146) result))))))
  202. (define %default-options
  203. `((port . 8080)
  204. ;; By default, serve nars under "/nar".
  205. (nar-path . "nar")
  206. (public-key-file . ,%public-key-file)
  207. (private-key-file . ,%private-key-file)
  208. ;; Default number of workers when caching is enabled.
  209. (workers . ,(current-processor-count))
  210. (address . ,(make-socket-address AF_INET INADDR_ANY 0))
  211. (repl . #f)))
  212. ;; The key pair used to sign narinfos.
  213. (define %private-key
  214. (make-parameter #f))
  215. (define %public-key
  216. (make-parameter #f))
  217. (define %nix-cache-info
  218. `(("StoreDir" . ,%store-directory)
  219. ("WantMassQuery" . 0)
  220. ("Priority" . 100)))
  221. (define (signed-string s)
  222. "Sign the hash of the string S with the daemon's key. Return a canonical
  223. sexp for the signature."
  224. (let* ((public-key (%public-key))
  225. (hash (bytevector->hash-data (sha256 (string->utf8 s))
  226. #:key-type (key-type public-key))))
  227. (signature-sexp hash (%private-key) public-key)))
  228. (define base64-encode-string
  229. (compose base64-encode string->utf8))
  230. (define* (store-item->recutils store-item
  231. #:key
  232. (nar-path "nar")
  233. (compression %no-compression)
  234. file-size)
  235. "Return the 'Compression' and 'URL' fields of the narinfo for STORE-ITEM,
  236. with COMPRESSION, starting at NAR-PATH."
  237. (let ((url (encode-and-join-uri-path
  238. `(,@(split-and-decode-uri-path nar-path)
  239. ,@(match compression
  240. (($ <compression> 'none)
  241. '())
  242. (($ <compression> type)
  243. (list (symbol->string type))))
  244. ,(basename store-item)))))
  245. (format #f "URL: ~a~%Compression: ~a~%~@[FileSize: ~a~%~]"
  246. url (compression-type compression) file-size)))
  247. (define* (narinfo-string store store-path key
  248. #:key (compressions (list %no-compression))
  249. (nar-path "nar") (file-sizes '()))
  250. "Generate a narinfo key/value string for STORE-PATH; an exception is raised
  251. if STORE-PATH is invalid. Produce a URL that corresponds to COMPRESSION. The
  252. narinfo is signed with KEY. NAR-PATH specifies the prefix for nar URLs.
  253. Optionally, FILE-SIZES is a list of compression/integer pairs, where the
  254. integer is size in bytes of the compressed NAR; it informs the client of how
  255. much needs to be downloaded."
  256. (let* ((path-info (query-path-info store store-path))
  257. (compressions (actual-compressions store-path compressions))
  258. (hash (bytevector->nix-base32-string
  259. (path-info-hash path-info)))
  260. (size (path-info-nar-size path-info))
  261. (file-sizes `((,%no-compression . ,size) ,@file-sizes))
  262. (references (string-join
  263. (map basename (path-info-references path-info))
  264. " "))
  265. (deriver (path-info-deriver path-info))
  266. (base-info (format #f
  267. "\
  268. StorePath: ~a
  269. ~{~a~}\
  270. NarHash: sha256:~a
  271. NarSize: ~d
  272. References: ~a~%"
  273. store-path
  274. (map (lambda (compression)
  275. (let ((size (assoc-ref file-sizes
  276. compression)))
  277. (store-item->recutils store-path
  278. #:file-size size
  279. #:nar-path nar-path
  280. #:compression
  281. compression)))
  282. compressions)
  283. hash size references))
  284. ;; Do not render a "Deriver" or "System" line if we are rendering
  285. ;; info for a derivation.
  286. (info (if (not deriver)
  287. base-info
  288. (catch 'system-error
  289. (lambda ()
  290. (let ((drv (read-derivation-from-file deriver)))
  291. (format #f "~aSystem: ~a~%Deriver: ~a~%"
  292. base-info (derivation-system drv)
  293. (basename deriver))))
  294. (lambda args
  295. ;; DERIVER might be missing, but that's fine:
  296. ;; it's only used for <substitutable> where it's
  297. ;; optional. 'System' is currently unused.
  298. (if (= ENOENT (system-error-errno args))
  299. base-info
  300. (apply throw args))))))
  301. (signature (base64-encode-string
  302. (canonical-sexp->string (signed-string info)))))
  303. (format #f "~aSignature: 1;~a;~a~%" info (gethostname) signature)))
  304. (define* (not-found request
  305. #:key (phrase "Resource not found")
  306. ttl)
  307. "Render 404 response for REQUEST."
  308. (values (build-response #:code 404
  309. #:headers (if ttl
  310. `((cache-control (max-age . ,ttl)))
  311. '()))
  312. (string-append phrase ": "
  313. (uri-path (request-uri request)))))
  314. (define (render-nix-cache-info)
  315. "Render server information."
  316. (values '((content-type . (text/plain)))
  317. (lambda (port)
  318. (for-each (match-lambda
  319. ((key . value)
  320. (format port "~a: ~a~%" key value)))
  321. %nix-cache-info))))
  322. (define* (render-narinfo store request hash
  323. #:key ttl (compressions (list %no-compression))
  324. (nar-path "nar"))
  325. "Render metadata for the store path corresponding to HASH. If TTL is true,
  326. advertise it as the maximum validity period (in seconds) via the
  327. 'Cache-Control' header. This allows 'guix substitute' to cache it for an
  328. appropriate duration. NAR-PATH specifies the prefix for nar URLs."
  329. (let ((store-path (hash-part->path store hash)))
  330. (if (string-null? store-path)
  331. (not-found request #:phrase "")
  332. (values `((content-type . (application/x-nix-narinfo))
  333. ,@(if ttl
  334. `((cache-control (max-age . ,ttl)))
  335. '()))
  336. (cut display
  337. (narinfo-string store store-path (%private-key)
  338. #:nar-path nar-path
  339. #:compressions compressions)
  340. <>)))))
  341. (define* (nar-cache-file directory item
  342. #:key (compression %no-compression))
  343. (string-append directory "/"
  344. (symbol->string (compression-type compression))
  345. "/" (basename item) ".nar"))
  346. (define* (narinfo-cache-file directory item
  347. #:key (compression %no-compression))
  348. (string-append directory "/"
  349. (symbol->string (compression-type compression))
  350. "/" (basename item)
  351. ".narinfo"))
  352. (define (hash-part-mapping-cache-file directory hash)
  353. (string-append directory "/hashes/" hash))
  354. (define run-single-baker
  355. (let ((baking (make-weak-value-hash-table))
  356. (mutex (make-mutex)))
  357. (lambda (item thunk)
  358. "Run THUNK, which is supposed to bake ITEM, but make sure only one
  359. thread is baking ITEM at a given time."
  360. (define selected?
  361. (with-mutex mutex
  362. (and (not (hash-ref baking item))
  363. (begin
  364. (hash-set! baking item (current-thread))
  365. #t))))
  366. (when selected?
  367. (dynamic-wind
  368. (const #t)
  369. thunk
  370. (lambda ()
  371. (with-mutex mutex
  372. (hash-remove! baking item))))))))
  373. (define-syntax-rule (single-baker item exp ...)
  374. "Bake ITEM by evaluating EXP, but make sure there's only one baker for ITEM
  375. at a time."
  376. (run-single-baker item (lambda () exp ...)))
  377. (define (narinfo-files cache)
  378. "Return the list of .narinfo files under CACHE."
  379. (if (file-is-directory? cache)
  380. (find-files cache
  381. (lambda (file stat)
  382. (string-suffix? ".narinfo" file)))
  383. '()))
  384. (define (nar-expiration-time ttl)
  385. "Return the narinfo expiration time (in seconds since the Epoch). The
  386. expiration time is +inf.0 when passed an item that is still in the store; in
  387. other cases, it is the last-access time of the item plus TTL.
  388. This policy allows us to keep cached nars that correspond to valid store
  389. items. Failing that, we could eventually have to recompute them and return
  390. 404 in the meantime."
  391. (let ((expiration-time (file-expiration-time ttl)))
  392. (lambda (file)
  393. (let ((item (string-append (%store-prefix) "/"
  394. (basename file ".narinfo"))))
  395. ;; Note: We don't need to use 'valid-path?' here because FILE would
  396. ;; not exist if ITEM were not valid in the first place.
  397. (if (file-exists? item)
  398. +inf.0
  399. (expiration-time file))))))
  400. (define (hash-part->path* store hash cache)
  401. "Like 'hash-part->path' but cached results under CACHE. This ensures we can
  402. still map HASH to the corresponding store file name, even if said store item
  403. vanished from the store in the meantime."
  404. (let ((cached (hash-part-mapping-cache-file cache hash)))
  405. (catch 'system-error
  406. (lambda ()
  407. (call-with-input-file cached read-string))
  408. (lambda args
  409. (if (= ENOENT (system-error-errno args))
  410. (match (hash-part->path store hash)
  411. ("" "")
  412. (result
  413. (mkdir-p (dirname cached))
  414. (call-with-output-file (string-append cached ".tmp")
  415. (lambda (port)
  416. (display result port)))
  417. (rename-file (string-append cached ".tmp") cached)
  418. result))
  419. (apply throw args))))))
  420. (define* (render-narinfo/cached store request hash
  421. #:key ttl (compressions (list %no-compression))
  422. (nar-path "nar")
  423. cache pool)
  424. "Respond to the narinfo request for REQUEST. If the narinfo is available in
  425. CACHE, then send it; otherwise, return 404 and \"bake\" that nar and narinfo
  426. requested using POOL."
  427. (define (delete-entry narinfo)
  428. ;; Delete NARINFO and the corresponding nar from CACHE.
  429. (let* ((nar (string-append (string-drop-right narinfo
  430. (string-length ".narinfo"))
  431. ".nar"))
  432. (base (basename narinfo ".narinfo"))
  433. (hash (string-take base (string-index base #\-)))
  434. (mapping (hash-part-mapping-cache-file cache hash)))
  435. (delete-file* narinfo)
  436. (delete-file* nar)
  437. (delete-file* mapping)))
  438. (let* ((item (hash-part->path* store hash cache))
  439. (compressions (actual-compressions item compressions))
  440. (cached (and (not (string-null? item))
  441. (narinfo-cache-file cache item
  442. #:compression
  443. (first compressions)))))
  444. (cond ((string-null? item)
  445. (not-found request))
  446. ((file-exists? cached)
  447. ;; Narinfo is in cache, send it.
  448. (values `((content-type . (application/x-nix-narinfo))
  449. ,@(if ttl
  450. `((cache-control (max-age . ,ttl)))
  451. '()))
  452. (lambda (port)
  453. (display (call-with-input-file cached
  454. read-string)
  455. port))))
  456. ((and (file-exists? item) ;cheaper than the 'valid-path?' RPC
  457. (valid-path? store item))
  458. ;; Nothing in cache: bake the narinfo and nar in the background and
  459. ;; return 404.
  460. (eventually pool
  461. (single-baker item
  462. ;; Check whether CACHED has been produced in the meantime.
  463. (unless (file-exists? cached)
  464. ;; (format #t "baking ~s~%" item)
  465. (bake-narinfo+nar cache item
  466. #:ttl ttl
  467. #:compressions compressions
  468. #:nar-path nar-path)))
  469. (when ttl
  470. (single-baker 'cache-cleanup
  471. (maybe-remove-expired-cache-entries cache
  472. narinfo-files
  473. #:entry-expiration
  474. (nar-expiration-time ttl)
  475. #:delete-entry delete-entry
  476. #:cleanup-period ttl))))
  477. (not-found request
  478. #:phrase "We're baking it"
  479. #:ttl 300)) ;should be available within 5m
  480. (else
  481. (not-found request #:phrase "")))))
  482. (define (compress-nar cache item compression)
  483. "Save in directory CACHE the nar for ITEM compressed with COMPRESSION."
  484. (define nar
  485. (nar-cache-file cache item #:compression compression))
  486. (mkdir-p (dirname nar))
  487. (match (compression-type compression)
  488. ('gzip
  489. ;; Note: the file port gets closed along with the gzip port.
  490. (call-with-gzip-output-port (open-output-file (string-append nar ".tmp"))
  491. (lambda (port)
  492. (write-file item port))
  493. #:level (compression-level compression)
  494. #:buffer-size (* 128 1024))
  495. (rename-file (string-append nar ".tmp") nar))
  496. ('lzip
  497. ;; Note: the file port gets closed along with the lzip port.
  498. (call-with-lzip-output-port (open-output-file (string-append nar ".tmp"))
  499. (lambda (port)
  500. (write-file item port))
  501. #:level (compression-level compression))
  502. (rename-file (string-append nar ".tmp") nar))
  503. ('none
  504. ;; Cache nars even when compression is disabled so that we can
  505. ;; guarantee the TTL (see <https://bugs.gnu.org/28664>.)
  506. (with-atomic-file-output nar
  507. (lambda (port)
  508. (write-file item port))))))
  509. (define* (bake-narinfo+nar cache item
  510. #:key ttl (compressions (list %no-compression))
  511. (nar-path "/nar"))
  512. "Write the narinfo and nar for ITEM to CACHE."
  513. (define (compressed-nar-size compression)
  514. (let* ((nar (nar-cache-file cache item #:compression compression))
  515. (stat (stat nar #f)))
  516. (and stat
  517. (cons compression (stat:size stat)))))
  518. (let ((compression (actual-compressions item compressions)))
  519. (for-each (cut compress-nar cache item <>) compressions)
  520. (match compressions
  521. ((main others ...)
  522. (let ((narinfo (narinfo-cache-file cache item
  523. #:compression main)))
  524. (with-atomic-file-output narinfo
  525. (lambda (port)
  526. ;; Open a new connection to the store. We cannot reuse the main
  527. ;; thread's connection to the store since we would end up sending
  528. ;; stuff concurrently on the same channel.
  529. (with-store store
  530. (let ((sizes (filter-map compressed-nar-size compression)))
  531. (display (narinfo-string store item
  532. (%private-key)
  533. #:nar-path nar-path
  534. #:compressions compressions
  535. #:file-sizes sizes)
  536. port)))))
  537. ;; Make narinfo files for OTHERS hard links to NARINFO such that the
  538. ;; atime-based cache eviction considers either all the nars or none
  539. ;; of them as candidates.
  540. (for-each (lambda (other)
  541. (let ((other (narinfo-cache-file cache item
  542. #:compression other)))
  543. (link narinfo other)))
  544. others))))))
  545. ;; XXX: Declare the 'X-Nar-Compression' HTTP header, which is in fact for
  546. ;; internal consumption: it allows us to pass the compression info to
  547. ;; 'http-write', as part of the workaround to <http://bugs.gnu.org/21093>.
  548. (declare-header! "X-Nar-Compression"
  549. (lambda (str)
  550. (match (call-with-input-string str read)
  551. (('compression type level)
  552. (compression type level))))
  553. compression?
  554. (lambda (compression port)
  555. (match compression
  556. (($ <compression> type level)
  557. (write `(compression ,type ,level) port)))))
  558. (define* (render-nar store request store-item
  559. #:key (compression %no-compression))
  560. "Render archive of the store path corresponding to STORE-ITEM."
  561. (let ((store-path (string-append %store-directory "/" store-item)))
  562. ;; The ISO-8859-1 charset *must* be used otherwise HTTP clients will
  563. ;; interpret the byte stream as UTF-8 and arbitrarily change invalid byte
  564. ;; sequences.
  565. (if (valid-path? store store-path)
  566. (values `((content-type . (application/x-nix-archive
  567. (charset . "ISO-8859-1")))
  568. (x-nar-compression . ,compression))
  569. ;; XXX: We're not returning the actual contents, deferring
  570. ;; instead to 'http-write'. This is a hack to work around
  571. ;; <http://bugs.gnu.org/21093>.
  572. store-path)
  573. (not-found request))))
  574. (define* (render-nar/cached store cache request store-item
  575. #:key ttl (compression %no-compression))
  576. "Respond to REQUEST with a nar for STORE-ITEM. If the nar is in CACHE,
  577. return it; otherwise, return 404. When TTL is true, use it as the
  578. 'Cache-Control' expiration time."
  579. (let ((cached (nar-cache-file cache store-item
  580. #:compression compression)))
  581. (if (file-exists? cached)
  582. (values `((content-type . (application/octet-stream
  583. (charset . "ISO-8859-1")))
  584. ,@(if ttl
  585. `((cache-control (max-age . ,ttl)))
  586. '())
  587. ;; XXX: We're not returning the actual contents, deferring
  588. ;; instead to 'http-write'. This is a hack to work around
  589. ;; <http://bugs.gnu.org/21093>.
  590. (x-raw-file . ,cached))
  591. #f)
  592. (not-found request))))
  593. (define (render-content-addressed-file store request
  594. name algo hash)
  595. "Return the content of the result of the fixed-output derivation NAME that
  596. has the given HASH of type ALGO."
  597. ;; TODO: Support other hash algorithms.
  598. (if (and (eq? algo 'sha256) (= 32 (bytevector-length hash)))
  599. (let ((item (fixed-output-path name hash
  600. #:hash-algo algo
  601. #:recursive? #f)))
  602. (if (valid-path? store item)
  603. (values `((content-type . (application/octet-stream
  604. (charset . "ISO-8859-1")))
  605. ;; XXX: We're not returning the actual contents,
  606. ;; deferring instead to 'http-write'. This is a hack to
  607. ;; work around <http://bugs.gnu.org/21093>.
  608. (x-raw-file . ,item))
  609. #f)
  610. (not-found request)))
  611. (not-found request)))
  612. (define (render-log-file store request name)
  613. "Render the log file for NAME, the base name of a store item. Don't attempt
  614. to compress or decompress the log file; just return it as-is."
  615. (define (response-headers file)
  616. ;; XXX: We're not returning the actual contents, deferring instead to
  617. ;; 'http-write'. This is a hack to work around
  618. ;; <http://bugs.gnu.org/21093>.
  619. (cond ((string-suffix? ".gz" file)
  620. `((content-type . (text/plain (charset . "UTF-8")))
  621. (content-encoding . (gzip))
  622. (x-raw-file . ,file)))
  623. ((string-suffix? ".bz2" file)
  624. `((content-type . (application/x-bzip2
  625. (charset . "ISO-8859-1")))
  626. (x-raw-file . ,file)))
  627. (else ;uncompressed
  628. `((content-type . (text/plain (charset . "UTF-8")))
  629. (x-raw-file . ,file)))))
  630. (let ((log (log-file store
  631. (string-append (%store-prefix) "/" name))))
  632. (if log
  633. (values (response-headers log) log)
  634. (not-found request))))
  635. (define (render-home-page request)
  636. "Render the home page."
  637. (values `((content-type . (text/html (charset . "UTF-8"))))
  638. (call-with-output-string
  639. (lambda (port)
  640. (sxml->xml '(html
  641. (head (title "GNU Guix Substitute Server"))
  642. (body
  643. (h1 "GNU Guix Substitute Server")
  644. (p "Hi, "
  645. (a (@ (href
  646. "https://guix.gnu.org/manual/en/html_node/Invoking-guix-publish.html"))
  647. (tt "guix publish"))
  648. " speaking. Welcome!")))
  649. port)))))
  650. (define (extract-narinfo-hash str)
  651. "Return the hash within the narinfo resource string STR, or false if STR
  652. is invalid."
  653. (and (string-suffix? ".narinfo" str)
  654. (let ((base (string-drop-right str 8)))
  655. (and (string-every %nix-base32-charset base)
  656. base))))
  657. (define (get-request? request)
  658. "Return #t if REQUEST uses the GET method."
  659. (eq? (request-method request) 'GET))
  660. (define (request-path-components request)
  661. "Split the URI path of REQUEST into a list of component strings. For
  662. example: \"/foo/bar\" yields '(\"foo\" \"bar\")."
  663. (split-and-decode-uri-path (uri-path (request-uri request))))
  664. ;;;
  665. ;;; Server.
  666. ;;;
  667. (define %http-write
  668. (@@ (web server http) http-write))
  669. (match (list (major-version) (minor-version) (micro-version))
  670. (("2" "2" "5") ;Guile 2.2.5
  671. (let ()
  672. (define %read-line (@ (ice-9 rdelim) %read-line))
  673. (define bad-header (@@ (web http) bad-header))
  674. ;; XXX: Work around <https://bugs.gnu.org/36350> by reverting to the
  675. ;; definition of 'read-header-line' as found in 2.2.4 and earlier.
  676. (define (read-header-line port)
  677. "Read an HTTP header line and return it without its final CRLF or LF.
  678. Raise a 'bad-header' exception if the line does not end in CRLF or LF,
  679. or if EOF is reached."
  680. (match (%read-line port)
  681. (((? string? line) . #\newline)
  682. ;; '%read-line' does not consider #\return a delimiter; so if it's
  683. ;; there, remove it. We are more tolerant than the RFC in that we
  684. ;; tolerate LF-only endings.
  685. (if (string-suffix? "\r" line)
  686. (string-drop-right line 1)
  687. line))
  688. ((line . _) ;EOF or missing delimiter
  689. (bad-header 'read-header-line line))))
  690. (set! (@@ (web http) read-header-line) read-header-line)))
  691. (_ #t))
  692. (define (strip-headers response)
  693. "Return RESPONSE's headers minus 'Content-Length' and our internal headers."
  694. (fold alist-delete
  695. (response-headers response)
  696. '(content-length x-raw-file x-nar-compression)))
  697. (define (sans-content-length response)
  698. "Return RESPONSE without its 'content-length' header."
  699. (set-field response (response-headers)
  700. (strip-headers response)))
  701. (define (with-content-length response length)
  702. "Return RESPONSE with a 'content-length' header set to LENGTH."
  703. (set-field response (response-headers)
  704. (alist-cons 'content-length length
  705. (strip-headers response))))
  706. (define-syntax-rule (swallow-EPIPE exp ...)
  707. "Swallow EPIPE errors raised by EXP..."
  708. (catch 'system-error
  709. (lambda ()
  710. exp ...)
  711. (lambda args
  712. (if (= EPIPE (system-error-errno args))
  713. (values)
  714. (apply throw args)))))
  715. (define-syntax-rule (swallow-zlib-error exp ...)
  716. "Swallow 'zlib-error' exceptions raised by EXP..."
  717. (catch 'zlib-error
  718. (lambda ()
  719. exp ...)
  720. (const #f)))
  721. (define (nar-response-port response compression)
  722. "Return a port on which to write the body of RESPONSE, the response of a
  723. /nar request, according to COMPRESSION."
  724. (match compression
  725. (($ <compression> 'gzip level)
  726. ;; Note: We cannot used chunked encoding here because
  727. ;; 'make-gzip-output-port' wants a file port.
  728. (make-gzip-output-port (response-port response)
  729. #:level level
  730. #:buffer-size (* 64 1024)))
  731. (($ <compression> 'lzip level)
  732. (make-lzip-output-port (response-port response)
  733. #:level level))
  734. (($ <compression> 'none)
  735. (response-port response))
  736. (#f
  737. (response-port response))))
  738. (define (http-write server client response body)
  739. "Write RESPONSE and BODY to CLIENT, possibly in a separate thread to avoid
  740. blocking."
  741. (match (response-content-type response)
  742. (('application/x-nix-archive . _)
  743. ;; Sending the the whole archive can take time so do it in a separate
  744. ;; thread so that the main thread can keep working in the meantime.
  745. (call-with-new-thread
  746. (lambda ()
  747. (set-thread-name "publish nar")
  748. (let* ((compression (assoc-ref (response-headers response)
  749. 'x-nar-compression))
  750. (response (write-response (sans-content-length response)
  751. client))
  752. (port (begin
  753. (force-output client)
  754. (nar-response-port response compression))))
  755. ;; XXX: Given our ugly workaround for <http://bugs.gnu.org/21093> in
  756. ;; 'render-nar', BODY here is just the file name of the store item.
  757. ;; We call 'write-file' from here because we know that's the only
  758. ;; way to avoid building the whole nar in memory, which could
  759. ;; quickly become a real problem. As a bonus, we even do
  760. ;; sendfile(2) directly from the store files to the socket.
  761. (swallow-zlib-error
  762. (swallow-EPIPE
  763. (write-file (utf8->string body) port)))
  764. (swallow-zlib-error
  765. (close-port port))
  766. (values)))))
  767. (_
  768. (match (assoc-ref (response-headers response) 'x-raw-file)
  769. ((? string? file)
  770. ;; Send a raw file in a separate thread.
  771. (call-with-new-thread
  772. (lambda ()
  773. (set-thread-name "publish file")
  774. (catch 'system-error
  775. (lambda ()
  776. (call-with-input-file file
  777. (lambda (input)
  778. (let* ((size (stat:size (stat input)))
  779. (response (write-response (with-content-length response
  780. size)
  781. client))
  782. (output (response-port response)))
  783. (setsockopt client SOL_SOCKET SO_SNDBUF (* 128 1024))
  784. (if (file-port? output)
  785. (sendfile output input size)
  786. (dump-port input output))
  787. (close-port output)
  788. (values)))))
  789. (lambda args
  790. ;; If the file was GC'd behind our back, that's fine. Likewise if
  791. ;; the client closes the connection.
  792. (unless (memv (system-error-errno args)
  793. (list ENOENT EPIPE ECONNRESET))
  794. (apply throw args))
  795. (values))))))
  796. (#f
  797. ;; Handle other responses sequentially.
  798. (%http-write server client response body))))))
  799. (define-server-impl concurrent-http-server
  800. ;; A variant of Guile's built-in HTTP server that offloads possibly long
  801. ;; responses to a different thread.
  802. (@@ (web server http) http-open)
  803. (@@ (web server http) http-read)
  804. http-write
  805. (@@ (web server http) http-close))
  806. (define (string->compression-type string)
  807. "Return a symbol denoting the compression method expressed by STRING; return
  808. #f if STRING doesn't match any supported method."
  809. (match string
  810. ("gzip" 'gzip)
  811. ("lzip" 'lzip)
  812. (_ #f)))
  813. (define (effective-compression requested-type compressions)
  814. "Given the REQUESTED-TYPE for compression and the set of chosen COMPRESSION
  815. methods, return the applicable compression."
  816. (or (find (match-lambda
  817. (($ <compression> type)
  818. (and (eq? type requested-type)
  819. compression)))
  820. compressions)
  821. (default-compression requested-type)))
  822. (define* (make-request-handler store
  823. #:key
  824. cache pool
  825. narinfo-ttl
  826. (nar-path "nar")
  827. (compressions (list %no-compression)))
  828. (define compression-type?
  829. string->compression-type)
  830. (define nar-path?
  831. (let ((expected (split-and-decode-uri-path nar-path)))
  832. (cut equal? expected <>)))
  833. (lambda (request body)
  834. (format #t "~a ~a~%"
  835. (request-method request)
  836. (uri-path (request-uri request)))
  837. (if (get-request? request) ;reject POST, PUT, etc.
  838. (match (request-path-components request)
  839. ;; /nix-cache-info
  840. (("nix-cache-info")
  841. (render-nix-cache-info))
  842. ;; /
  843. ((or () ("index.html"))
  844. (render-home-page request))
  845. ;; /<hash>.narinfo
  846. (((= extract-narinfo-hash (? string? hash)))
  847. (if cache
  848. (render-narinfo/cached store request hash
  849. #:cache cache
  850. #:pool pool
  851. #:ttl narinfo-ttl
  852. #:nar-path nar-path
  853. #:compressions compressions)
  854. (render-narinfo store request hash
  855. #:ttl narinfo-ttl
  856. #:nar-path nar-path
  857. #:compressions compressions)))
  858. ;; /nar/file/NAME/sha256/HASH
  859. (("file" name "sha256" hash)
  860. (guard (c ((invalid-base32-character? c)
  861. (not-found request)))
  862. (let ((hash (nix-base32-string->bytevector hash)))
  863. (render-content-addressed-file store request
  864. name 'sha256 hash))))
  865. ;; /log/OUTPUT
  866. (("log" name)
  867. (render-log-file store request name))
  868. ;; Use different URLs depending on the compression type. This
  869. ;; guarantees that /nar URLs remain valid even when 'guix publish'
  870. ;; is restarted with different compression parameters.
  871. ;; /nar/gzip/<store-item>
  872. ((components ... (? compression-type? type) store-item)
  873. (if (nar-path? components)
  874. (let* ((compression-type (string->compression-type type))
  875. (compression (effective-compression compression-type
  876. compressions)))
  877. (if cache
  878. (render-nar/cached store cache request store-item
  879. #:ttl narinfo-ttl
  880. #:compression compression)
  881. (render-nar store request store-item
  882. #:compression compression)))
  883. (not-found request)))
  884. ;; /nar/<store-item>
  885. ((components ... store-item)
  886. (if (nar-path? components)
  887. (if cache
  888. (render-nar/cached store cache request store-item
  889. #:ttl narinfo-ttl
  890. #:compression %no-compression)
  891. (render-nar store request store-item
  892. #:compression %no-compression))
  893. (not-found request)))
  894. (x (not-found request)))
  895. (not-found request))))
  896. (define* (run-publish-server socket store
  897. #:key
  898. (compressions (list %no-compression))
  899. (nar-path "nar") narinfo-ttl
  900. cache pool)
  901. (run-server (make-request-handler store
  902. #:cache cache
  903. #:pool pool
  904. #:nar-path nar-path
  905. #:narinfo-ttl narinfo-ttl
  906. #:compressions compressions)
  907. concurrent-http-server
  908. `(#:socket ,socket)))
  909. (define (open-server-socket address)
  910. "Return a TCP socket bound to ADDRESS, a socket address."
  911. (let ((sock (socket (sockaddr:fam address) SOCK_STREAM 0)))
  912. (setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
  913. (bind sock address)
  914. sock))
  915. (define (gather-user-privileges user)
  916. "Switch to the identity of USER, a user name."
  917. (catch 'misc-error
  918. (lambda ()
  919. (let ((user (getpw user)))
  920. (setgroups #())
  921. (setgid (passwd:gid user))
  922. (setuid (passwd:uid user))))
  923. (lambda (key proc message args . rest)
  924. (leave (G_ "user '~a' not found: ~a~%")
  925. user (apply format #f message args)))))
  926. ;;;
  927. ;;; Entry point.
  928. ;;;
  929. (define-command (guix-publish . args)
  930. (category packaging)
  931. (synopsis "publish build results over HTTP")
  932. (with-error-handling
  933. (let* ((opts (args-fold* args %options
  934. (lambda (opt name arg result)
  935. (leave (G_ "~A: unrecognized option~%") name))
  936. (lambda (arg result)
  937. (leave (G_ "~A: extraneous argument~%") arg))
  938. %default-options))
  939. (user (assoc-ref opts 'user))
  940. (port (assoc-ref opts 'port))
  941. (ttl (assoc-ref opts 'narinfo-ttl))
  942. (compressions (match (filter-map (match-lambda
  943. (('compression . compression)
  944. compression)
  945. (_ #f))
  946. opts)
  947. (()
  948. ;; Default to fast & low compression.
  949. (list %default-gzip-compression))
  950. (lst (reverse lst))))
  951. (address (let ((addr (assoc-ref opts 'address)))
  952. (make-socket-address (sockaddr:fam addr)
  953. (sockaddr:addr addr)
  954. port)))
  955. (socket (open-server-socket address))
  956. (nar-path (assoc-ref opts 'nar-path))
  957. (repl-port (assoc-ref opts 'repl))
  958. (cache (assoc-ref opts 'cache))
  959. (workers (assoc-ref opts 'workers))
  960. ;; Read the key right away so that (1) we fail early on if we can't
  961. ;; access them, and (2) we can then drop privileges.
  962. (public-key (read-file-sexp (assoc-ref opts 'public-key-file)))
  963. (private-key (read-file-sexp (assoc-ref opts 'private-key-file))))
  964. (when user
  965. ;; Now that we've read the key material and opened the socket, we can
  966. ;; drop privileges.
  967. (gather-user-privileges user))
  968. (when (zero? (getuid))
  969. (warning (G_ "server running as root; \
  970. consider using the '--user' option!~%")))
  971. (parameterize ((%public-key public-key)
  972. (%private-key private-key))
  973. (info (G_ "publishing ~a on ~a, port ~d~%")
  974. %store-directory
  975. (inet-ntop (sockaddr:fam address) (sockaddr:addr address))
  976. (sockaddr:port address))
  977. (for-each (lambda (compression)
  978. (info (G_ "using '~a' compression method, level ~a~%")
  979. (compression-type compression)
  980. (compression-level compression)))
  981. compressions)
  982. (when repl-port
  983. (repl:spawn-server (repl:make-tcp-server-socket #:port repl-port)))
  984. ;; Set the name of the main thread.
  985. (set-thread-name "guix publish")
  986. (with-store store
  987. (run-publish-server socket store
  988. #:cache cache
  989. #:pool (and cache (make-pool workers
  990. #:thread-name
  991. "publish worker"))
  992. #:nar-path nar-path
  993. #:compressions compressions
  994. #:narinfo-ttl ttl))))))
  995. ;;; Local Variables:
  996. ;;; eval: (put 'single-baker 'scheme-indent-function 1)
  997. ;;; End: