]> Cypherpunks.ru repositories - gocheese.git/blobdiff - gocheese.go
Better main file filename
[gocheese.git] / gocheese.go
diff --git a/gocheese.go b/gocheese.go
deleted file mode 100644 (file)
index cc30de2..0000000
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
-GoCheese -- Python private package repository and caching proxy
-Copyright (C) 2019-2021 Sergey Matveev <stargrave@stargrave.org>
-              2019-2021 Elena Balakhonova <balakhonova_e@riseup.net>
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, version 3 of the License.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program.  If not, see <http://www.gnu.org/licenses/>.
-*/
-
-// Python private package repository and caching proxy
-package main
-
-import (
-       "bytes"
-       "context"
-       "crypto/sha256"
-       "crypto/tls"
-       "encoding/hex"
-       "errors"
-       "flag"
-       "fmt"
-       "io/ioutil"
-       "log"
-       "net"
-       "net/http"
-       "net/url"
-       "os"
-       "os/signal"
-       "path/filepath"
-       "regexp"
-       "runtime"
-       "strings"
-       "syscall"
-       "time"
-
-       "golang.org/x/net/netutil"
-)
-
-const (
-       Version   = "3.0.0"
-       HTMLBegin = `<!DOCTYPE html>
-<html>
-  <head>
-    <title>Links for %s</title>
-  </head>
-  <body>
-`
-       HTMLEnd      = "  </body>\n</html>\n"
-       HTMLElement  = "    <a href=\"%s\"%s>%s</a><br/>\n"
-       InternalFlag = ".internal"
-       GPGSigExt    = ".asc"
-
-       Warranty = `This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, version 3 of the License.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program.  If not, see <http://www.gnu.org/licenses/>.`
-)
-
-const (
-       HashAlgoSHA256     = "sha256"
-       HashAlgoBLAKE2b256 = "blake2_256"
-       HashAlgoSHA512     = "sha512"
-       HashAlgoMD5        = "md5"
-)
-
-var (
-       pkgPyPI         = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
-       normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
-
-       knownHashAlgos []string = []string{
-               HashAlgoSHA256,
-               HashAlgoBLAKE2b256,
-               HashAlgoSHA512,
-               HashAlgoMD5,
-       }
-
-       root             = flag.String("root", "./packages", "Path to packages directory")
-       bind             = flag.String("bind", "[::]:8080", "Address to bind to")
-       tlsCert          = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
-       tlsKey           = flag.String("tls-key", "", "Path to TLS X.509 private key")
-       norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
-       refreshURLPath   = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
-       gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
-       pypiURL          = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
-       pypiCertHash     = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
-       logTimestamped   = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
-       passwdPath       = flag.String("passwd", "", "Path to FIFO for upload authentication")
-       passwdCheck      = flag.Bool("passwd-check", false, "Run password checker")
-       fsck             = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
-       maxClients       = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
-       version          = flag.Bool("version", false, "Print version information")
-       warranty         = flag.Bool("warranty", false, "Print warranty information")
-
-       killed        bool
-       pypiURLParsed *url.URL
-)
-
-func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
-       path := filepath.Join(*root, pkgName)
-       if _, err := os.Stat(path); os.IsNotExist(err) {
-               if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
-                       log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
-                       http.Error(w, err.Error(), http.StatusInternalServerError)
-                       return false
-               }
-               log.Println(r.RemoteAddr, "mkdir", pkgName)
-       }
-       return true
-}
-
-func listRoot(w http.ResponseWriter, r *http.Request) {
-       files, err := ioutil.ReadDir(*root)
-       if err != nil {
-               log.Println("error", r.RemoteAddr, "root", err)
-               http.Error(w, err.Error(), http.StatusInternalServerError)
-               return
-       }
-       var result bytes.Buffer
-       result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
-       for _, file := range files {
-               if file.Mode().IsDir() {
-                       result.WriteString(fmt.Sprintf(
-                               HTMLElement,
-                               *refreshURLPath+file.Name()+"/",
-                               "", file.Name(),
-                       ))
-               }
-       }
-       result.WriteString(HTMLEnd)
-       w.Write(result.Bytes())
-}
-
-func listDir(
-       w http.ResponseWriter,
-       r *http.Request,
-       pkgName string,
-       autorefresh, gpgUpdate bool,
-) {
-       dirPath := filepath.Join(*root, pkgName)
-       if autorefresh {
-               if !refreshDir(w, r, pkgName, "", gpgUpdate) {
-                       return
-               }
-       } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
-               return
-       }
-       fis, err := ioutil.ReadDir(dirPath)
-       if err != nil {
-               log.Println("error", r.RemoteAddr, "list", pkgName, err)
-               http.Error(w, err.Error(), http.StatusInternalServerError)
-               return
-       }
-       files := make(map[string]struct{}, len(fis)/2)
-       for _, fi := range fis {
-               files[fi.Name()] = struct{}{}
-       }
-       var result bytes.Buffer
-       result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
-       for _, algo := range knownHashAlgos {
-               for fn := range files {
-                       if killed {
-                               // Skip expensive I/O when shutting down
-                               http.Error(w, "shutting down", http.StatusInternalServerError)
-                               return
-                       }
-                       if !strings.HasSuffix(fn, "."+algo) {
-                               continue
-                       }
-                       delete(files, fn)
-                       digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
-                       if err != nil {
-                               log.Println("error", r.RemoteAddr, "list", fn, err)
-                               http.Error(w, err.Error(), http.StatusInternalServerError)
-                               return
-                       }
-                       fnClean := strings.TrimSuffix(fn, "."+algo)
-                       delete(files, fnClean)
-                       gpgSigAttr := ""
-                       if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
-                               gpgSigAttr = " data-gpg-sig=true"
-                               delete(files, fnClean+GPGSigExt)
-                       }
-                       result.WriteString(fmt.Sprintf(
-                               HTMLElement,
-                               strings.Join([]string{
-                                       *refreshURLPath, pkgName, "/", fnClean,
-                                       "#", algo, "=", hex.EncodeToString(digest),
-                               }, ""),
-                               gpgSigAttr,
-                               fnClean,
-                       ))
-               }
-       }
-       result.WriteString(HTMLEnd)
-       w.Write(result.Bytes())
-}
-
-func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
-       log.Println(r.RemoteAddr, "get", filename)
-       path := filepath.Join(*root, pkgName, filename)
-       if _, err := os.Stat(path); os.IsNotExist(err) {
-               if !refreshDir(w, r, pkgName, filename, false) {
-                       return
-               }
-       }
-       http.ServeFile(w, r, path)
-}
-
-func handler(w http.ResponseWriter, r *http.Request) {
-       switch r.Method {
-       case "GET":
-               var path string
-               var autorefresh bool
-               var gpgUpdate bool
-               if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
-                       path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
-               } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
-                       path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
-                       autorefresh = true
-               } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
-                       path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
-                       autorefresh = true
-                       gpgUpdate = true
-               } else {
-                       http.Error(w, "unknown action", http.StatusBadRequest)
-                       return
-               }
-               parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
-               if len(parts) > 2 {
-                       http.Error(w, "invalid path", http.StatusBadRequest)
-                       return
-               }
-               if len(parts) == 1 {
-                       if parts[0] == "" {
-                               listRoot(w, r)
-                       } else {
-                               listDir(w, r, parts[0], autorefresh, gpgUpdate)
-                       }
-               } else {
-                       servePkg(w, r, parts[0], parts[1])
-               }
-       case "POST":
-               serveUpload(w, r)
-       default:
-               http.Error(w, "unknown action", http.StatusBadRequest)
-       }
-}
-
-func main() {
-       flag.Parse()
-       if *warranty {
-               fmt.Println(Warranty)
-               return
-       }
-       if *version {
-               fmt.Println("GoCheese", Version, "built with", runtime.Version())
-               return
-       }
-
-       if *logTimestamped {
-               log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
-       } else {
-               log.SetFlags(log.Lshortfile)
-       }
-       log.SetOutput(os.Stdout)
-
-       if *fsck {
-               if !goodIntegrity() {
-                       os.Exit(1)
-               }
-               return
-       }
-
-       if *passwdCheck {
-               if passwdReader(os.Stdin) {
-                       os.Exit(0)
-               } else {
-                       os.Exit(1)
-               }
-       }
-
-       if *passwdPath != "" {
-               go func() {
-                       for {
-                               fd, err := os.OpenFile(*passwdPath, os.O_RDONLY, os.FileMode(0666))
-                               if err != nil {
-                                       log.Fatalln(err)
-                               }
-                               passwdReader(fd)
-                               fd.Close()
-                       }
-               }()
-       }
-
-       if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
-               log.Fatalln("Both -tls-cert and -tls-key are required")
-       }
-
-       var err error
-       pypiURLParsed, err = url.Parse(*pypiURL)
-       if err != nil {
-               log.Fatalln(err)
-       }
-       tlsConfig := tls.Config{
-               ClientSessionCache: tls.NewLRUClientSessionCache(16),
-               NextProtos:         []string{"h2", "http/1.1"},
-       }
-       pypiHTTPTransport = http.Transport{
-               ForceAttemptHTTP2: true,
-               TLSClientConfig:   &tlsConfig,
-       }
-       if *pypiCertHash != "" {
-               ourDgst, err := hex.DecodeString(*pypiCertHash)
-               if err != nil {
-                       log.Fatalln(err)
-               }
-               tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
-                       spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
-                       theirDgst := sha256.Sum256(spki)
-                       if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
-                               return errors.New("certificate's SPKI digest mismatch")
-                       }
-                       return nil
-               }
-       }
-
-       ln, err := net.Listen("tcp", *bind)
-       if err != nil {
-               log.Fatal(err)
-       }
-       ln = netutil.LimitListener(ln, *maxClients)
-       server := &http.Server{
-               ReadTimeout:  time.Minute,
-               WriteTimeout: time.Minute,
-       }
-       http.HandleFunc(*norefreshURLPath, handler)
-       http.HandleFunc(*refreshURLPath, handler)
-       if *gpgUpdateURLPath != "" {
-               http.HandleFunc(*gpgUpdateURLPath, handler)
-       }
-
-       needsShutdown := make(chan os.Signal, 0)
-       exitErr := make(chan error, 0)
-       signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
-       go func(s *http.Server) {
-               <-needsShutdown
-               killed = true
-               log.Println("shutting down")
-               ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
-               exitErr <- s.Shutdown(ctx)
-               cancel()
-       }(server)
-
-       log.Println(
-               "GoCheese", Version, "listens:",
-               "root:", *root,
-               "bind:", *bind,
-               "pypi:", *pypiURL,
-       )
-       if *tlsCert == "" {
-               err = server.Serve(ln)
-       } else {
-               err = server.ServeTLS(ln, *tlsCert, *tlsKey)
-       }
-       if err != http.ErrServerClosed {
-               log.Fatal(err)
-       }
-       if err := <-exitErr; err != nil {
-               log.Fatal(err)
-       }
-}