2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019 Sergey Matveev <stargrave@stargrave.org>
4 2019 Elena Balakhonova <balakhonova_e@riseup.net>
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, version 3 of the License.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 // Python private package repository and caching proxy
44 "golang.org/x/net/netutil"
48 HTMLBegin = `<!DOCTYPE html>
51 <title>Links for %s</title>
55 HTMLEnd = " </body>\n</html>\n"
56 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
57 SHA256Prefix = "sha256="
59 InternalFlag = ".internal"
61 GPGSigAttr = " data-gpg-sig=true"
63 Warranty = `This program is free software: you can redistribute it and/or modify
64 it under the terms of the GNU General Public License as published by
65 the Free Software Foundation, version 3 of the License.
67 This program is distributed in the hope that it will be useful,
68 but WITHOUT ANY WARRANTY; without even the implied warranty of
69 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
70 GNU General Public License for more details.
72 You should have received a copy of the GNU General Public License
73 along with this program. If not, see <http://www.gnu.org/licenses/>.`
77 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
78 Version string = "UNKNOWN"
80 root = flag.String("root", "./packages", "Path to packages directory")
81 bind = flag.String("bind", "[::]:8080", "Address to bind to")
82 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
83 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
84 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
85 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
86 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
87 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
88 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
89 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
90 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
91 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
92 version = flag.Bool("version", false, "Print version information")
93 warranty = flag.Bool("warranty", false, "Print warranty information")
97 normalizationRe *regexp.Regexp = regexp.MustCompilePOSIX("[-_.]+")
100 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
101 path := filepath.Join(*root, dir)
102 if _, err := os.Stat(path); os.IsNotExist(err) {
103 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
104 http.Error(w, err.Error(), http.StatusInternalServerError)
107 log.Println(r.RemoteAddr, "mkdir", dir)
113 w http.ResponseWriter,
119 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
122 resp, err := http.Get(*pypiURL + dir + "/")
124 http.Error(w, err.Error(), http.StatusBadGateway)
127 body, err := ioutil.ReadAll(resp.Body)
130 http.Error(w, err.Error(), http.StatusBadGateway)
133 if !mkdirForPkg(w, r, dir) {
136 dirPath := filepath.Join(*root, dir)
137 var submatches []string
143 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
144 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
145 if len(submatches) == 0 {
149 filename = submatches[2]
150 if pkgURL, err = url.Parse(uri); err != nil {
151 http.Error(w, err.Error(), http.StatusInternalServerError)
154 if !strings.HasPrefix(pkgURL.Fragment, SHA256Prefix) {
155 log.Println(r.RemoteAddr, "pypi", filename, "no SHA256 digest provided")
156 http.Error(w, "no SHA256 digest provided", http.StatusBadGateway)
159 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
161 http.Error(w, err.Error(), http.StatusBadGateway)
165 path = filepath.Join(dirPath, filename)
166 if filename == filenameGet {
168 // Skip heavy remote call, when shutting down
169 http.Error(w, "shutting down", http.StatusInternalServerError)
172 log.Println(r.RemoteAddr, "pypi download", filename)
173 resp, err = http.Get(pkgURL.String())
175 http.Error(w, err.Error(), http.StatusBadGateway)
178 defer resp.Body.Close()
179 hasher := sha256.New()
180 dst, err := TempFile(dirPath)
182 http.Error(w, err.Error(), http.StatusInternalServerError)
185 wr := io.MultiWriter(hasher, dst)
186 if _, err = io.Copy(wr, resp.Body); err != nil {
187 os.Remove(dst.Name())
189 http.Error(w, err.Error(), http.StatusInternalServerError)
192 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
193 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
194 os.Remove(dst.Name())
196 http.Error(w, err.Error(), http.StatusBadGateway)
199 if err = dst.Sync(); err != nil {
200 os.Remove(dst.Name())
202 http.Error(w, err.Error(), http.StatusInternalServerError)
206 if err = os.Rename(dst.Name(), path); err != nil {
207 http.Error(w, err.Error(), http.StatusInternalServerError)
210 if err = DirSync(dirPath); err != nil {
211 http.Error(w, err.Error(), http.StatusInternalServerError)
215 if filename == filenameGet || gpgUpdate {
216 if _, err = os.Stat(path); err != nil {
219 resp, err := http.Get(pkgURL.String() + GPGSigExt)
223 if resp.StatusCode != http.StatusOK {
227 sig, err := ioutil.ReadAll(resp.Body)
232 if err = WriteFileSync(dirPath, path+GPGSigExt, sig); err != nil {
233 http.Error(w, err.Error(), http.StatusInternalServerError)
236 log.Println(r.RemoteAddr, "pypi downloaded signature", filename)
239 path = path + SHA256Ext
240 _, err = os.Stat(path)
244 if !os.IsNotExist(err) {
245 http.Error(w, err.Error(), http.StatusInternalServerError)
248 log.Println(r.RemoteAddr, "pypi touch", filename)
249 if err = WriteFileSync(dirPath, path, digest); err != nil {
250 http.Error(w, err.Error(), http.StatusInternalServerError)
257 func listRoot(w http.ResponseWriter, r *http.Request) {
258 files, err := ioutil.ReadDir(*root)
260 http.Error(w, err.Error(), http.StatusInternalServerError)
263 var result bytes.Buffer
264 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
265 for _, file := range files {
266 if file.Mode().IsDir() {
267 result.WriteString(fmt.Sprintf(
269 *refreshURLPath+file.Name()+"/",
274 result.WriteString(HTMLEnd)
275 w.Write(result.Bytes())
279 w http.ResponseWriter,
285 dirPath := filepath.Join(*root, dir)
287 if !refreshDir(w, r, dir, "", gpgUpdate) {
290 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
293 files, err := ioutil.ReadDir(dirPath)
295 http.Error(w, err.Error(), http.StatusInternalServerError)
298 var result bytes.Buffer
299 result.WriteString(fmt.Sprintf(HTMLBegin, dir))
301 var gpgSigAttr string
302 var filenameClean string
303 for _, file := range files {
304 if !strings.HasSuffix(file.Name(), SHA256Ext) {
308 // Skip expensive I/O when shutting down
309 http.Error(w, "shutting down", http.StatusInternalServerError)
312 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
314 http.Error(w, err.Error(), http.StatusInternalServerError)
317 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
318 if _, err = os.Stat(filepath.Join(dirPath, filenameClean+GPGSigExt)); os.IsNotExist(err) {
321 gpgSigAttr = GPGSigAttr
323 result.WriteString(fmt.Sprintf(
325 strings.Join([]string{
326 *refreshURLPath, dir, "/",
327 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
333 result.WriteString(HTMLEnd)
334 w.Write(result.Bytes())
337 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
338 log.Println(r.RemoteAddr, "get", filename)
339 path := filepath.Join(*root, dir, filename)
340 if _, err := os.Stat(path); os.IsNotExist(err) {
341 if !refreshDir(w, r, dir, filename, false) {
345 http.ServeFile(w, r, path)
348 func serveUpload(w http.ResponseWriter, r *http.Request) {
350 username, password, ok := r.BasicAuth()
352 log.Println(r.RemoteAddr, "unauthenticated", username)
353 http.Error(w, "unauthenticated", http.StatusUnauthorized)
356 auther, ok := passwords[username]
357 if !ok || !auther.Auth(password) {
358 log.Println(r.RemoteAddr, "unauthenticated", username)
359 http.Error(w, "unauthenticated", http.StatusUnauthorized)
365 if err = r.ParseMultipartForm(1 << 20); err != nil {
366 http.Error(w, err.Error(), http.StatusBadRequest)
369 pkgNames, exists := r.MultipartForm.Value["name"]
370 if !exists || len(pkgNames) != 1 {
371 http.Error(w, "single name is expected in request", http.StatusBadRequest)
374 dir := normalizationRe.ReplaceAllString(pkgNames[0], "-")
375 dirPath := filepath.Join(*root, dir)
376 var digestExpected []byte
377 if digestExpectedHex, exists := r.MultipartForm.Value["sha256_digest"]; exists {
378 digestExpected, err = hex.DecodeString(digestExpectedHex[0])
380 http.Error(w, "bad sha256_digest: "+err.Error(), http.StatusBadRequest)
384 gpgSigsExpected := make(map[string]struct{})
386 // Checking is it internal package
387 if _, err = os.Stat(filepath.Join(dirPath, InternalFlag)); err != nil {
388 log.Println(r.RemoteAddr, "non-internal package", dir)
389 http.Error(w, "unknown internal package", http.StatusUnauthorized)
393 for _, file := range r.MultipartForm.File["content"] {
394 filename := file.Filename
395 gpgSigsExpected[filename+GPGSigExt] = struct{}{}
396 log.Println(r.RemoteAddr, "put", filename, "by", username)
397 path := filepath.Join(dirPath, filename)
398 if _, err = os.Stat(path); err == nil {
399 log.Println(r.RemoteAddr, "already exists", filename)
400 http.Error(w, "already exists", http.StatusBadRequest)
403 if !mkdirForPkg(w, r, dir) {
406 src, err := file.Open()
409 http.Error(w, err.Error(), http.StatusInternalServerError)
412 dst, err := TempFile(dirPath)
414 http.Error(w, err.Error(), http.StatusInternalServerError)
417 hasher := sha256.New()
418 wr := io.MultiWriter(hasher, dst)
419 if _, err = io.Copy(wr, src); err != nil {
420 os.Remove(dst.Name())
422 http.Error(w, err.Error(), http.StatusInternalServerError)
425 if err = dst.Sync(); err != nil {
426 os.Remove(dst.Name())
428 http.Error(w, err.Error(), http.StatusInternalServerError)
432 digest := hasher.Sum(nil)
433 if digestExpected != nil {
434 if bytes.Compare(digestExpected, digest) == 0 {
435 log.Println(r.RemoteAddr, filename, "good checksum received")
437 log.Println(r.RemoteAddr, filename, "bad checksum received")
438 http.Error(w, "bad checksum", http.StatusBadRequest)
439 os.Remove(dst.Name())
443 if err = os.Rename(dst.Name(), path); err != nil {
444 http.Error(w, err.Error(), http.StatusInternalServerError)
447 if err = DirSync(dirPath); err != nil {
448 http.Error(w, err.Error(), http.StatusInternalServerError)
451 if err = WriteFileSync(dirPath, path+SHA256Ext, digest); err != nil {
452 http.Error(w, err.Error(), http.StatusInternalServerError)
456 for _, file := range r.MultipartForm.File["gpg_signature"] {
457 filename := file.Filename
458 if _, exists := gpgSigsExpected[filename]; !exists {
459 http.Error(w, "unexpected GPG signature filename", http.StatusBadRequest)
462 delete(gpgSigsExpected, filename)
463 log.Println(r.RemoteAddr, "put", filename, "by", username)
464 path := filepath.Join(dirPath, filename)
465 if _, err = os.Stat(path); err == nil {
466 log.Println(r.RemoteAddr, "already exists", filename)
467 http.Error(w, "already exists", http.StatusBadRequest)
470 src, err := file.Open()
472 http.Error(w, err.Error(), http.StatusInternalServerError)
475 sig, err := ioutil.ReadAll(src)
478 http.Error(w, err.Error(), http.StatusInternalServerError)
481 if err = WriteFileSync(dirPath, path, sig); err != nil {
482 http.Error(w, err.Error(), http.StatusInternalServerError)
488 func handler(w http.ResponseWriter, r *http.Request) {
494 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
495 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
496 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
497 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
499 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
500 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
504 http.Error(w, "unknown action", http.StatusBadRequest)
507 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
509 http.Error(w, "invalid path", http.StatusBadRequest)
516 listDir(w, r, parts[0], autorefresh, gpgUpdate)
519 servePkg(w, r, parts[0], parts[1])
524 http.Error(w, "unknown action", http.StatusBadRequest)
528 func goodIntegrity() bool {
529 dirs, err := ioutil.ReadDir(*root)
533 hasher := sha256.New()
534 digest := make([]byte, sha256.Size)
538 for _, dir := range dirs {
539 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
543 for _, file := range files {
544 if !strings.HasSuffix(file.Name(), SHA256Ext) {
547 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
548 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
550 if os.IsNotExist(err) {
556 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
560 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
561 fmt.Println(pkgName, "GOOD")
564 fmt.Println(pkgName, "BAD")
575 fmt.Println(Warranty)
579 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
583 if !goodIntegrity() {
592 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
593 log.Fatalln("Both -tls-cert and -tls-key are required")
596 log.Println("root:", *root, "bind:", *bind)
598 ln, err := net.Listen("tcp", *bind)
602 ln = netutil.LimitListener(ln, *maxClients)
603 server := &http.Server{
604 ReadTimeout: time.Minute,
605 WriteTimeout: time.Minute,
607 http.HandleFunc(*norefreshURLPath, handler)
608 http.HandleFunc(*refreshURLPath, handler)
609 http.HandleFunc(*gpgUpdateURLPath, handler)
611 needsRefreshPasswd := make(chan os.Signal, 0)
612 needsShutdown := make(chan os.Signal, 0)
613 exitErr := make(chan error, 0)
614 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
615 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
617 for range needsRefreshPasswd {
618 log.Println("Refreshing passwords")
622 go func(s *http.Server) {
625 log.Println("Shutting down")
626 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
627 exitErr <- s.Shutdown(ctx)
632 err = server.Serve(ln)
634 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
636 if err != http.ErrServerClosed {
639 if err := <-exitErr; err != nil {