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 UserAgent = "GoCheese/" + Version
51 HTMLBegin = `<!DOCTYPE html>
54 <meta name="pypi:repository-version" content="1.0">
55 <title>Links for %s</title>
59 HTMLEnd = " </body>\n</html>\n"
60 HTMLElement = " <a href=\"%s\"%s>%s</a>\n"
61 InternalFlag = ".internal"
64 Warranty = `This program is free software: you can redistribute it and/or modify
65 it under the terms of the GNU General Public License as published by
66 the Free Software Foundation, version 3 of the License.
68 This program is distributed in the hope that it will be useful,
69 but WITHOUT ANY WARRANTY; without even the implied warranty of
70 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
71 GNU General Public License for more details.
73 You should have received a copy of the GNU General Public License
74 along with this program. If not, see <http://www.gnu.org/licenses/>.`
78 HashAlgoSHA256 = "sha256"
79 HashAlgoBLAKE2b256 = "blake2_256"
80 HashAlgoSHA512 = "sha512"
85 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
86 normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
88 knownHashAlgos []string = []string{
95 root = flag.String("root", "./packages", "Path to packages directory")
96 bind = flag.String("bind", "[::]:8080", "Address to bind to")
97 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
98 doUCSPI = flag.Bool("ucspi", false, "Work as UCSPI-TCP service")
100 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
101 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
103 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
104 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
105 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
107 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
108 pypiCertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
110 passwdPath = flag.String("passwd", "", "Path to FIFO for upload authentication")
111 passwdListPath = flag.String("passwd-list", "", "Path to FIFO for login listing")
112 passwdCheck = flag.Bool("passwd-check", false, "Run password checker")
114 logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
115 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
116 version = flag.Bool("version", false, "Print version information")
117 warranty = flag.Bool("warranty", false, "Print warranty information")
120 pypiURLParsed *url.URL
123 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
124 path := filepath.Join(*root, pkgName)
125 if _, err := os.Stat(path); os.IsNotExist(err) {
126 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
127 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
128 http.Error(w, err.Error(), http.StatusInternalServerError)
131 log.Println(r.RemoteAddr, "mkdir", pkgName)
136 func listRoot(w http.ResponseWriter, r *http.Request) {
137 files, err := ioutil.ReadDir(*root)
139 log.Println("error", r.RemoteAddr, "root", err)
140 http.Error(w, err.Error(), http.StatusInternalServerError)
143 var result bytes.Buffer
144 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
145 for _, file := range files {
146 if file.Mode().IsDir() {
147 result.WriteString(fmt.Sprintf(
149 *refreshURLPath+file.Name()+"/",
154 result.WriteString(HTMLEnd)
155 w.Write(result.Bytes())
159 w http.ResponseWriter,
162 autorefresh, gpgUpdate bool,
164 dirPath := filepath.Join(*root, pkgName)
166 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
169 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
172 fis, err := ioutil.ReadDir(dirPath)
174 log.Println("error", r.RemoteAddr, "list", pkgName, err)
175 http.Error(w, err.Error(), http.StatusInternalServerError)
178 files := make(map[string]struct{}, len(fis)/2)
179 for _, fi := range fis {
180 files[fi.Name()] = struct{}{}
182 var result bytes.Buffer
183 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
184 for _, algo := range knownHashAlgos {
185 for fn := range files {
187 // Skip expensive I/O when shutting down
188 http.Error(w, "shutting down", http.StatusInternalServerError)
191 if !strings.HasSuffix(fn, "."+algo) {
195 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
197 log.Println("error", r.RemoteAddr, "list", fn, err)
198 http.Error(w, err.Error(), http.StatusInternalServerError)
201 fnClean := strings.TrimSuffix(fn, "."+algo)
202 delete(files, fnClean)
204 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
205 gpgSigAttr = " data-gpg-sig=true"
206 delete(files, fnClean+GPGSigExt)
208 result.WriteString(fmt.Sprintf(
210 strings.Join([]string{
211 *refreshURLPath, pkgName, "/", fnClean,
212 "#", algo, "=", hex.EncodeToString(digest),
219 result.WriteString(HTMLEnd)
220 w.Write(result.Bytes())
223 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
224 log.Println(r.RemoteAddr, "get", filename)
225 path := filepath.Join(*root, pkgName, filename)
226 if _, err := os.Stat(path); os.IsNotExist(err) {
227 if !refreshDir(w, r, pkgName, filename, false) {
231 http.ServeFile(w, r, path)
234 func handler(w http.ResponseWriter, r *http.Request) {
235 w.Header().Set("Server", UserAgent)
241 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
242 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
243 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
244 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
246 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
247 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
251 http.Error(w, "unknown action", http.StatusBadRequest)
254 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
256 http.Error(w, "invalid path", http.StatusBadRequest)
263 listDir(w, r, parts[0], autorefresh, gpgUpdate)
266 servePkg(w, r, parts[0], parts[1])
271 http.Error(w, "unknown action", http.StatusBadRequest)
278 fmt.Println(Warranty)
282 fmt.Println("GoCheese", Version, "built with", runtime.Version())
287 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
289 log.SetFlags(log.Lshortfile)
292 log.SetOutput(os.Stdout)
296 if !goodIntegrity() {
303 if passwdReader(os.Stdin) {
310 if *passwdPath != "" {
313 fd, err := os.OpenFile(
326 if *passwdListPath != "" {
329 fd, err := os.OpenFile(
331 os.O_WRONLY|os.O_APPEND,
343 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
344 log.Fatalln("Both -tls-cert and -tls-key are required")
348 pypiURLParsed, err = url.Parse(*pypiURL)
352 tlsConfig := tls.Config{
353 ClientSessionCache: tls.NewLRUClientSessionCache(16),
354 NextProtos: []string{"h2", "http/1.1"},
356 pypiHTTPTransport = http.Transport{
357 ForceAttemptHTTP2: true,
358 TLSClientConfig: &tlsConfig,
360 if *pypiCertHash != "" {
361 ourDgst, err := hex.DecodeString(*pypiCertHash)
365 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
366 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
367 theirDgst := sha256.Sum256(spki)
368 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
369 return errors.New("certificate's SPKI digest mismatch")
375 server := &http.Server{
376 ReadTimeout: time.Minute,
377 WriteTimeout: time.Minute,
379 http.HandleFunc(*norefreshURLPath, handler)
380 http.HandleFunc(*refreshURLPath, handler)
381 if *gpgUpdateURLPath != "" {
382 http.HandleFunc(*gpgUpdateURLPath, handler)
386 server.SetKeepAlivesEnabled(false)
388 server.ConnState = connStater
389 err := server.Serve(ln)
390 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
397 ln, err := net.Listen("tcp", *bind)
401 ln = netutil.LimitListener(ln, *maxClients)
403 needsShutdown := make(chan os.Signal, 0)
404 exitErr := make(chan error, 0)
405 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
406 go func(s *http.Server) {
409 log.Println("shutting down")
410 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
411 exitErr <- s.Shutdown(ctx)
416 "GoCheese", Version, "listens:",
422 err = server.Serve(ln)
424 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
426 if err != http.ErrServerClosed {
429 if err := <-exitErr; err != nil {