2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019-2021 Sergey Matveev <stargrave@stargrave.org>
4 2019-2021 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
45 "golang.org/x/net/netutil"
50 HTMLBegin = `<!DOCTYPE html>
53 <title>Links for %s</title>
57 HTMLEnd = " </body>\n</html>\n"
58 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
59 InternalFlag = ".internal"
62 Warranty = `This program is free software: you can redistribute it and/or modify
63 it under the terms of the GNU General Public License as published by
64 the Free Software Foundation, version 3 of the License.
66 This program is distributed in the hope that it will be useful,
67 but WITHOUT ANY WARRANTY; without even the implied warranty of
68 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 GNU General Public License for more details.
71 You should have received a copy of the GNU General Public License
72 along with this program. If not, see <http://www.gnu.org/licenses/>.`
76 HashAlgoSHA256 = "sha256"
77 HashAlgoBLAKE2b256 = "blake2_256"
78 HashAlgoSHA512 = "sha512"
83 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
84 normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
86 knownHashAlgos []string = []string{
93 root = flag.String("root", "./packages", "Path to packages directory")
94 bind = flag.String("bind", "[::]:8080", "Address to bind to")
95 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
96 doUCSPI = flag.Bool("ucspi", false, "Work as UCSPI-TCP service")
98 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
99 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
101 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
102 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
103 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
105 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
106 pypiCertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
108 passwdPath = flag.String("passwd", "", "Path to FIFO for upload authentication")
109 passwdCheck = flag.Bool("passwd-check", false, "Run password checker")
111 logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
112 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
113 version = flag.Bool("version", false, "Print version information")
114 warranty = flag.Bool("warranty", false, "Print warranty information")
117 pypiURLParsed *url.URL
120 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
121 path := filepath.Join(*root, pkgName)
122 if _, err := os.Stat(path); os.IsNotExist(err) {
123 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
124 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
125 http.Error(w, err.Error(), http.StatusInternalServerError)
128 log.Println(r.RemoteAddr, "mkdir", pkgName)
133 func listRoot(w http.ResponseWriter, r *http.Request) {
134 files, err := ioutil.ReadDir(*root)
136 log.Println("error", r.RemoteAddr, "root", err)
137 http.Error(w, err.Error(), http.StatusInternalServerError)
140 var result bytes.Buffer
141 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
142 for _, file := range files {
143 if file.Mode().IsDir() {
144 result.WriteString(fmt.Sprintf(
146 *refreshURLPath+file.Name()+"/",
151 result.WriteString(HTMLEnd)
152 w.Write(result.Bytes())
156 w http.ResponseWriter,
159 autorefresh, gpgUpdate bool,
161 dirPath := filepath.Join(*root, pkgName)
163 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
166 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
169 fis, err := ioutil.ReadDir(dirPath)
171 log.Println("error", r.RemoteAddr, "list", pkgName, err)
172 http.Error(w, err.Error(), http.StatusInternalServerError)
175 files := make(map[string]struct{}, len(fis)/2)
176 for _, fi := range fis {
177 files[fi.Name()] = struct{}{}
179 var result bytes.Buffer
180 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
181 for _, algo := range knownHashAlgos {
182 for fn := range files {
184 // Skip expensive I/O when shutting down
185 http.Error(w, "shutting down", http.StatusInternalServerError)
188 if !strings.HasSuffix(fn, "."+algo) {
192 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
194 log.Println("error", r.RemoteAddr, "list", fn, err)
195 http.Error(w, err.Error(), http.StatusInternalServerError)
198 fnClean := strings.TrimSuffix(fn, "."+algo)
199 delete(files, fnClean)
201 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
202 gpgSigAttr = " data-gpg-sig=true"
203 delete(files, fnClean+GPGSigExt)
205 result.WriteString(fmt.Sprintf(
207 strings.Join([]string{
208 *refreshURLPath, pkgName, "/", fnClean,
209 "#", algo, "=", hex.EncodeToString(digest),
216 result.WriteString(HTMLEnd)
217 w.Write(result.Bytes())
220 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
221 log.Println(r.RemoteAddr, "get", filename)
222 path := filepath.Join(*root, pkgName, filename)
223 if _, err := os.Stat(path); os.IsNotExist(err) {
224 if !refreshDir(w, r, pkgName, filename, false) {
228 http.ServeFile(w, r, path)
231 func handler(w http.ResponseWriter, r *http.Request) {
237 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
238 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
239 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
240 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
242 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
243 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
247 http.Error(w, "unknown action", http.StatusBadRequest)
250 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
252 http.Error(w, "invalid path", http.StatusBadRequest)
259 listDir(w, r, parts[0], autorefresh, gpgUpdate)
262 servePkg(w, r, parts[0], parts[1])
267 http.Error(w, "unknown action", http.StatusBadRequest)
274 fmt.Println(Warranty)
278 fmt.Println("GoCheese", Version, "built with", runtime.Version())
283 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
285 log.SetFlags(log.Lshortfile)
288 log.SetOutput(os.Stdout)
292 if !goodIntegrity() {
299 if passwdReader(os.Stdin) {
306 if *passwdPath != "" {
309 fd, err := os.OpenFile(*passwdPath, os.O_RDONLY, os.FileMode(0666))
319 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
320 log.Fatalln("Both -tls-cert and -tls-key are required")
324 pypiURLParsed, err = url.Parse(*pypiURL)
328 tlsConfig := tls.Config{
329 ClientSessionCache: tls.NewLRUClientSessionCache(16),
330 NextProtos: []string{"h2", "http/1.1"},
332 pypiHTTPTransport = http.Transport{
333 ForceAttemptHTTP2: true,
334 TLSClientConfig: &tlsConfig,
336 if *pypiCertHash != "" {
337 ourDgst, err := hex.DecodeString(*pypiCertHash)
341 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
342 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
343 theirDgst := sha256.Sum256(spki)
344 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
345 return errors.New("certificate's SPKI digest mismatch")
351 server := &http.Server{
352 ReadTimeout: time.Minute,
353 WriteTimeout: time.Minute,
355 http.HandleFunc(*norefreshURLPath, handler)
356 http.HandleFunc(*refreshURLPath, handler)
357 if *gpgUpdateURLPath != "" {
358 http.HandleFunc(*gpgUpdateURLPath, handler)
362 server.SetKeepAlivesEnabled(false)
364 server.ConnState = connStater
365 err := server.Serve(ln)
366 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
373 ln, err := net.Listen("tcp", *bind)
377 ln = netutil.LimitListener(ln, *maxClients)
379 needsShutdown := make(chan os.Signal, 0)
380 exitErr := make(chan error, 0)
381 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
382 go func(s *http.Server) {
385 log.Println("shutting down")
386 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
387 exitErr <- s.Shutdown(ctx)
392 "GoCheese", Version, "listens:",
398 err = server.Serve(ln)
400 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
402 if err != http.ErrServerClosed {
405 if err := <-exitErr; err != nil {