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 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
96 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
97 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
98 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
99 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
100 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
101 pypiCertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
102 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
103 logTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
104 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
105 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
106 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
107 version = flag.Bool("version", false, "Print version information")
108 warranty = flag.Bool("warranty", false, "Print warranty information")
111 pypiURLParsed *url.URL
114 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
115 path := filepath.Join(*root, pkgName)
116 if _, err := os.Stat(path); os.IsNotExist(err) {
117 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
118 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
119 http.Error(w, err.Error(), http.StatusInternalServerError)
122 log.Println(r.RemoteAddr, "mkdir", pkgName)
127 func listRoot(w http.ResponseWriter, r *http.Request) {
128 files, err := ioutil.ReadDir(*root)
130 log.Println("error", r.RemoteAddr, "root", err)
131 http.Error(w, err.Error(), http.StatusInternalServerError)
134 var result bytes.Buffer
135 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
136 for _, file := range files {
137 if file.Mode().IsDir() {
138 result.WriteString(fmt.Sprintf(
140 *refreshURLPath+file.Name()+"/",
145 result.WriteString(HTMLEnd)
146 w.Write(result.Bytes())
150 w http.ResponseWriter,
153 autorefresh, gpgUpdate bool,
155 dirPath := filepath.Join(*root, pkgName)
157 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
160 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
163 fis, err := ioutil.ReadDir(dirPath)
165 log.Println("error", r.RemoteAddr, "list", pkgName, err)
166 http.Error(w, err.Error(), http.StatusInternalServerError)
169 files := make(map[string]struct{}, len(fis)/2)
170 for _, fi := range fis {
171 files[fi.Name()] = struct{}{}
173 var result bytes.Buffer
174 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
175 for _, algo := range knownHashAlgos {
176 for fn := range files {
178 // Skip expensive I/O when shutting down
179 http.Error(w, "shutting down", http.StatusInternalServerError)
182 if !strings.HasSuffix(fn, "."+algo) {
186 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
188 log.Println("error", r.RemoteAddr, "list", fn, err)
189 http.Error(w, err.Error(), http.StatusInternalServerError)
192 fnClean := strings.TrimSuffix(fn, "."+algo)
193 delete(files, fnClean)
195 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
196 gpgSigAttr = " data-gpg-sig=true"
197 delete(files, fnClean+GPGSigExt)
199 result.WriteString(fmt.Sprintf(
201 strings.Join([]string{
202 *refreshURLPath, pkgName, "/", fnClean,
203 "#", algo, "=", hex.EncodeToString(digest),
210 result.WriteString(HTMLEnd)
211 w.Write(result.Bytes())
214 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
215 log.Println(r.RemoteAddr, "get", filename)
216 path := filepath.Join(*root, pkgName, filename)
217 if _, err := os.Stat(path); os.IsNotExist(err) {
218 if !refreshDir(w, r, pkgName, filename, false) {
222 http.ServeFile(w, r, path)
225 func handler(w http.ResponseWriter, r *http.Request) {
231 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
232 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
233 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
234 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
236 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
237 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
241 http.Error(w, "unknown action", http.StatusBadRequest)
244 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
246 http.Error(w, "invalid path", http.StatusBadRequest)
253 listDir(w, r, parts[0], autorefresh, gpgUpdate)
256 servePkg(w, r, parts[0], parts[1])
261 http.Error(w, "unknown action", http.StatusBadRequest)
268 fmt.Println(Warranty)
272 fmt.Println("GoCheese", Version, "built with", runtime.Version())
277 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
279 log.SetFlags(log.Lshortfile)
281 log.SetOutput(os.Stdout)
284 if !goodIntegrity() {
295 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
296 log.Fatalln("Both -tls-cert and -tls-key are required")
300 pypiURLParsed, err = url.Parse(*pypiURL)
305 tlsConfig := tls.Config{
306 ClientSessionCache: tls.NewLRUClientSessionCache(16),
307 NextProtos: []string{"h2", "http/1.1"},
309 pypiHTTPTransport = http.Transport{
310 ForceAttemptHTTP2: true,
311 TLSClientConfig: &tlsConfig,
313 if *pypiCertHash != "" {
314 ourDgst, err := hex.DecodeString(*pypiCertHash)
318 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
319 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
320 theirDgst := sha256.Sum256(spki)
321 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
322 return errors.New("certificate's SPKI digest mismatch")
328 ln, err := net.Listen("tcp", *bind)
332 ln = netutil.LimitListener(ln, *maxClients)
333 server := &http.Server{
334 ReadTimeout: time.Minute,
335 WriteTimeout: time.Minute,
337 http.HandleFunc(*norefreshURLPath, handler)
338 http.HandleFunc(*refreshURLPath, handler)
339 if *gpgUpdateURLPath != "" {
340 http.HandleFunc(*gpgUpdateURLPath, handler)
343 needsRefreshPasswd := make(chan os.Signal, 0)
344 needsShutdown := make(chan os.Signal, 0)
345 exitErr := make(chan error, 0)
346 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
347 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
349 for range needsRefreshPasswd {
350 log.Println("refreshing passwords")
354 go func(s *http.Server) {
357 log.Println("shutting down")
358 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
359 exitErr <- s.Shutdown(ctx)
364 "GoCheese", Version, "listens:",
370 err = server.Serve(ln)
372 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
374 if err != http.ErrServerClosed {
377 if err := <-exitErr; err != nil {