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 passwdListPath = flag.String("passwd-list", "", "Path to FIFO for login listing")
110 passwdCheck = flag.Bool("passwd-check", false, "Run password checker")
112 logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
113 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
114 version = flag.Bool("version", false, "Print version information")
115 warranty = flag.Bool("warranty", false, "Print warranty information")
118 pypiURLParsed *url.URL
121 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
122 path := filepath.Join(*root, pkgName)
123 if _, err := os.Stat(path); os.IsNotExist(err) {
124 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
125 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
126 http.Error(w, err.Error(), http.StatusInternalServerError)
129 log.Println(r.RemoteAddr, "mkdir", pkgName)
134 func listRoot(w http.ResponseWriter, r *http.Request) {
135 files, err := ioutil.ReadDir(*root)
137 log.Println("error", r.RemoteAddr, "root", err)
138 http.Error(w, err.Error(), http.StatusInternalServerError)
141 var result bytes.Buffer
142 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
143 for _, file := range files {
144 if file.Mode().IsDir() {
145 result.WriteString(fmt.Sprintf(
147 *refreshURLPath+file.Name()+"/",
152 result.WriteString(HTMLEnd)
153 w.Write(result.Bytes())
157 w http.ResponseWriter,
160 autorefresh, gpgUpdate bool,
162 dirPath := filepath.Join(*root, pkgName)
164 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
167 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
170 fis, err := ioutil.ReadDir(dirPath)
172 log.Println("error", r.RemoteAddr, "list", pkgName, err)
173 http.Error(w, err.Error(), http.StatusInternalServerError)
176 files := make(map[string]struct{}, len(fis)/2)
177 for _, fi := range fis {
178 files[fi.Name()] = struct{}{}
180 var result bytes.Buffer
181 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
182 for _, algo := range knownHashAlgos {
183 for fn := range files {
185 // Skip expensive I/O when shutting down
186 http.Error(w, "shutting down", http.StatusInternalServerError)
189 if !strings.HasSuffix(fn, "."+algo) {
193 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
195 log.Println("error", r.RemoteAddr, "list", fn, err)
196 http.Error(w, err.Error(), http.StatusInternalServerError)
199 fnClean := strings.TrimSuffix(fn, "."+algo)
200 delete(files, fnClean)
202 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
203 gpgSigAttr = " data-gpg-sig=true"
204 delete(files, fnClean+GPGSigExt)
206 result.WriteString(fmt.Sprintf(
208 strings.Join([]string{
209 *refreshURLPath, pkgName, "/", fnClean,
210 "#", algo, "=", hex.EncodeToString(digest),
217 result.WriteString(HTMLEnd)
218 w.Write(result.Bytes())
221 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
222 log.Println(r.RemoteAddr, "get", filename)
223 path := filepath.Join(*root, pkgName, filename)
224 if _, err := os.Stat(path); os.IsNotExist(err) {
225 if !refreshDir(w, r, pkgName, filename, false) {
229 http.ServeFile(w, r, path)
232 func handler(w http.ResponseWriter, r *http.Request) {
238 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
239 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
240 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
241 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
243 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
244 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
248 http.Error(w, "unknown action", http.StatusBadRequest)
251 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
253 http.Error(w, "invalid path", http.StatusBadRequest)
260 listDir(w, r, parts[0], autorefresh, gpgUpdate)
263 servePkg(w, r, parts[0], parts[1])
268 http.Error(w, "unknown action", http.StatusBadRequest)
275 fmt.Println(Warranty)
279 fmt.Println("GoCheese", Version, "built with", runtime.Version())
284 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
286 log.SetFlags(log.Lshortfile)
289 log.SetOutput(os.Stdout)
293 if !goodIntegrity() {
300 if passwdReader(os.Stdin) {
307 if *passwdPath != "" {
310 fd, err := os.OpenFile(
323 if *passwdListPath != "" {
326 fd, err := os.OpenFile(
328 os.O_WRONLY|os.O_APPEND,
340 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
341 log.Fatalln("Both -tls-cert and -tls-key are required")
345 pypiURLParsed, err = url.Parse(*pypiURL)
349 tlsConfig := tls.Config{
350 ClientSessionCache: tls.NewLRUClientSessionCache(16),
351 NextProtos: []string{"h2", "http/1.1"},
353 pypiHTTPTransport = http.Transport{
354 ForceAttemptHTTP2: true,
355 TLSClientConfig: &tlsConfig,
357 if *pypiCertHash != "" {
358 ourDgst, err := hex.DecodeString(*pypiCertHash)
362 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
363 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
364 theirDgst := sha256.Sum256(spki)
365 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
366 return errors.New("certificate's SPKI digest mismatch")
372 server := &http.Server{
373 ReadTimeout: time.Minute,
374 WriteTimeout: time.Minute,
376 http.HandleFunc(*norefreshURLPath, handler)
377 http.HandleFunc(*refreshURLPath, handler)
378 if *gpgUpdateURLPath != "" {
379 http.HandleFunc(*gpgUpdateURLPath, handler)
383 server.SetKeepAlivesEnabled(false)
385 server.ConnState = connStater
386 err := server.Serve(ln)
387 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
394 ln, err := net.Listen("tcp", *bind)
398 ln = netutil.LimitListener(ln, *maxClients)
400 needsShutdown := make(chan os.Signal, 0)
401 exitErr := make(chan error, 0)
402 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
403 go func(s *http.Server) {
406 log.Println("shutting down")
407 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
408 exitErr <- s.Shutdown(ctx)
413 "GoCheese", Version, "listens:",
419 err = server.Serve(ln)
421 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
423 if err != http.ErrServerClosed {
426 if err := <-exitErr; err != nil {