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 <meta name="pypi:repository-version" content="1.0">
54 <title>Links for %s</title>
58 HTMLEnd = " </body>\n</html>\n"
59 HTMLElement = " <a href=\"%s\"%s>%s</a>\n"
60 InternalFlag = ".internal"
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 HashAlgoSHA256 = "sha256"
78 HashAlgoBLAKE2b256 = "blake2_256"
79 HashAlgoSHA512 = "sha512"
84 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
85 normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
87 knownHashAlgos []string = []string{
94 root = flag.String("root", "./packages", "Path to packages directory")
95 bind = flag.String("bind", "[::]:8080", "Address to bind to")
96 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
97 doUCSPI = flag.Bool("ucspi", false, "Work as UCSPI-TCP service")
99 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
100 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
102 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
103 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
104 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
106 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
107 pypiCertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
109 passwdPath = flag.String("passwd", "", "Path to FIFO for upload authentication")
110 passwdListPath = flag.String("passwd-list", "", "Path to FIFO for login listing")
111 passwdCheck = flag.Bool("passwd-check", false, "Run password checker")
113 logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
114 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
115 version = flag.Bool("version", false, "Print version information")
116 warranty = flag.Bool("warranty", false, "Print warranty information")
119 pypiURLParsed *url.URL
122 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
123 path := filepath.Join(*root, pkgName)
124 if _, err := os.Stat(path); os.IsNotExist(err) {
125 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
126 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
127 http.Error(w, err.Error(), http.StatusInternalServerError)
130 log.Println(r.RemoteAddr, "mkdir", pkgName)
135 func listRoot(w http.ResponseWriter, r *http.Request) {
136 files, err := ioutil.ReadDir(*root)
138 log.Println("error", r.RemoteAddr, "root", err)
139 http.Error(w, err.Error(), http.StatusInternalServerError)
142 var result bytes.Buffer
143 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
144 for _, file := range files {
145 if file.Mode().IsDir() {
146 result.WriteString(fmt.Sprintf(
148 *refreshURLPath+file.Name()+"/",
153 result.WriteString(HTMLEnd)
154 w.Write(result.Bytes())
158 w http.ResponseWriter,
161 autorefresh, gpgUpdate bool,
163 dirPath := filepath.Join(*root, pkgName)
165 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
168 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
171 fis, err := ioutil.ReadDir(dirPath)
173 log.Println("error", r.RemoteAddr, "list", pkgName, err)
174 http.Error(w, err.Error(), http.StatusInternalServerError)
177 files := make(map[string]struct{}, len(fis)/2)
178 for _, fi := range fis {
179 files[fi.Name()] = struct{}{}
181 var result bytes.Buffer
182 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
183 for _, algo := range knownHashAlgos {
184 for fn := range files {
186 // Skip expensive I/O when shutting down
187 http.Error(w, "shutting down", http.StatusInternalServerError)
190 if !strings.HasSuffix(fn, "."+algo) {
194 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
196 log.Println("error", r.RemoteAddr, "list", fn, err)
197 http.Error(w, err.Error(), http.StatusInternalServerError)
200 fnClean := strings.TrimSuffix(fn, "."+algo)
201 delete(files, fnClean)
203 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
204 gpgSigAttr = " data-gpg-sig=true"
205 delete(files, fnClean+GPGSigExt)
207 result.WriteString(fmt.Sprintf(
209 strings.Join([]string{
210 *refreshURLPath, pkgName, "/", fnClean,
211 "#", algo, "=", hex.EncodeToString(digest),
218 result.WriteString(HTMLEnd)
219 w.Write(result.Bytes())
222 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
223 log.Println(r.RemoteAddr, "get", filename)
224 path := filepath.Join(*root, pkgName, filename)
225 if _, err := os.Stat(path); os.IsNotExist(err) {
226 if !refreshDir(w, r, pkgName, filename, false) {
230 http.ServeFile(w, r, path)
233 func handler(w http.ResponseWriter, r *http.Request) {
239 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
240 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
241 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
242 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
244 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
245 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
249 http.Error(w, "unknown action", http.StatusBadRequest)
252 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
254 http.Error(w, "invalid path", http.StatusBadRequest)
261 listDir(w, r, parts[0], autorefresh, gpgUpdate)
264 servePkg(w, r, parts[0], parts[1])
269 http.Error(w, "unknown action", http.StatusBadRequest)
276 fmt.Println(Warranty)
280 fmt.Println("GoCheese", Version, "built with", runtime.Version())
285 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
287 log.SetFlags(log.Lshortfile)
290 log.SetOutput(os.Stdout)
294 if !goodIntegrity() {
301 if passwdReader(os.Stdin) {
308 if *passwdPath != "" {
311 fd, err := os.OpenFile(
324 if *passwdListPath != "" {
327 fd, err := os.OpenFile(
329 os.O_WRONLY|os.O_APPEND,
341 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
342 log.Fatalln("Both -tls-cert and -tls-key are required")
346 pypiURLParsed, err = url.Parse(*pypiURL)
350 tlsConfig := tls.Config{
351 ClientSessionCache: tls.NewLRUClientSessionCache(16),
352 NextProtos: []string{"h2", "http/1.1"},
354 pypiHTTPTransport = http.Transport{
355 ForceAttemptHTTP2: true,
356 TLSClientConfig: &tlsConfig,
358 if *pypiCertHash != "" {
359 ourDgst, err := hex.DecodeString(*pypiCertHash)
363 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
364 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
365 theirDgst := sha256.Sum256(spki)
366 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
367 return errors.New("certificate's SPKI digest mismatch")
373 server := &http.Server{
374 ReadTimeout: time.Minute,
375 WriteTimeout: time.Minute,
377 http.HandleFunc(*norefreshURLPath, handler)
378 http.HandleFunc(*refreshURLPath, handler)
379 if *gpgUpdateURLPath != "" {
380 http.HandleFunc(*gpgUpdateURLPath, handler)
384 server.SetKeepAlivesEnabled(false)
386 server.ConnState = connStater
387 err := server.Serve(ln)
388 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
395 ln, err := net.Listen("tcp", *bind)
399 ln = netutil.LimitListener(ln, *maxClients)
401 needsShutdown := make(chan os.Signal, 0)
402 exitErr := make(chan error, 0)
403 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
404 go func(s *http.Server) {
407 log.Println("shutting down")
408 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
409 exitErr <- s.Shutdown(ctx)
414 "GoCheese", Version, "listens:",
420 err = server.Serve(ln)
422 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
424 if err != http.ErrServerClosed {
427 if err := <-exitErr; err != nil {