2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019 Sergey Matveev <stargrave@stargrave.org>
4 2019 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
42 "golang.org/x/net/netutil"
46 HTMLBegin = `<!DOCTYPE html>
49 <title>Links for %s</title>
53 HTMLEnd = " </body>\n</html>\n"
54 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
55 InternalFlag = ".internal"
58 Warranty = `This program is free software: you can redistribute it and/or modify
59 it under the terms of the GNU General Public License as published by
60 the Free Software Foundation, version 3 of the License.
62 This program is distributed in the hope that it will be useful,
63 but WITHOUT ANY WARRANTY; without even the implied warranty of
64 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65 GNU General Public License for more details.
67 You should have received a copy of the GNU General Public License
68 along with this program. If not, see <http://www.gnu.org/licenses/>.`
72 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
73 normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
75 HashAlgoSHA256 = "sha256"
76 HashAlgoBLAKE2b256 = "blake2_256"
77 HashAlgoSHA512 = "sha512"
79 knownHashAlgos []string = []string{
86 root = flag.String("root", "./packages", "Path to packages directory")
87 bind = flag.String("bind", "[::]:8080", "Address to bind to")
88 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
89 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
90 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
91 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
92 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
93 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
94 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
95 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
96 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
97 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
98 version = flag.Bool("version", false, "Print version information")
99 warranty = flag.Bool("warranty", false, "Print warranty information")
101 Version string = "UNKNOWN"
103 pypiURLParsed *url.URL
106 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
107 path := filepath.Join(*root, dir)
108 if _, err := os.Stat(path); os.IsNotExist(err) {
109 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
110 http.Error(w, err.Error(), http.StatusInternalServerError)
113 log.Println(r.RemoteAddr, "mkdir", dir)
118 func listRoot(w http.ResponseWriter, r *http.Request) {
119 files, err := ioutil.ReadDir(*root)
121 http.Error(w, err.Error(), http.StatusInternalServerError)
124 var result bytes.Buffer
125 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
126 for _, file := range files {
127 if file.Mode().IsDir() {
128 result.WriteString(fmt.Sprintf(
130 *refreshURLPath+file.Name()+"/",
135 result.WriteString(HTMLEnd)
136 w.Write(result.Bytes())
140 w http.ResponseWriter,
146 dirPath := filepath.Join(*root, dir)
148 if !refreshDir(w, r, dir, "", gpgUpdate) {
151 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
154 fis, err := ioutil.ReadDir(dirPath)
156 http.Error(w, err.Error(), http.StatusInternalServerError)
159 files := make(map[string]struct{}, len(fis)/2)
160 for _, fi := range fis {
161 files[fi.Name()] = struct{}{}
163 var result bytes.Buffer
164 result.WriteString(fmt.Sprintf(HTMLBegin, dir))
165 for _, algo := range knownHashAlgos {
166 for fn, _ := range files {
168 // Skip expensive I/O when shutting down
169 http.Error(w, "shutting down", http.StatusInternalServerError)
172 if !strings.HasSuffix(fn, "."+algo) {
176 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
178 http.Error(w, err.Error(), http.StatusInternalServerError)
181 fnClean := strings.TrimSuffix(fn, "."+algo)
182 delete(files, fnClean)
184 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
185 gpgSigAttr = " data-gpg-sig=true"
186 delete(files, fnClean+GPGSigExt)
188 result.WriteString(fmt.Sprintf(
190 strings.Join([]string{
191 *refreshURLPath, dir, "/", fnClean,
192 "#", algo, "=", hex.EncodeToString(digest),
199 result.WriteString(HTMLEnd)
200 w.Write(result.Bytes())
203 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
204 log.Println(r.RemoteAddr, "get", filename)
205 path := filepath.Join(*root, dir, filename)
206 if _, err := os.Stat(path); os.IsNotExist(err) {
207 if !refreshDir(w, r, dir, filename, false) {
211 http.ServeFile(w, r, path)
214 func handler(w http.ResponseWriter, r *http.Request) {
220 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
221 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
222 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
223 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
225 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
226 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
230 http.Error(w, "unknown action", http.StatusBadRequest)
233 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
235 http.Error(w, "invalid path", http.StatusBadRequest)
242 listDir(w, r, parts[0], autorefresh, gpgUpdate)
245 servePkg(w, r, parts[0], parts[1])
250 http.Error(w, "unknown action", http.StatusBadRequest)
257 fmt.Println(Warranty)
261 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
265 if !goodIntegrity() {
274 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
275 log.Fatalln("Both -tls-cert and -tls-key are required")
278 pypiURLParsed, err = url.Parse(*pypiURL)
283 log.Println("root:", *root, "bind:", *bind)
285 ln, err := net.Listen("tcp", *bind)
289 ln = netutil.LimitListener(ln, *maxClients)
290 server := &http.Server{
291 ReadTimeout: time.Minute,
292 WriteTimeout: time.Minute,
294 http.HandleFunc(*norefreshURLPath, handler)
295 http.HandleFunc(*refreshURLPath, handler)
296 if *gpgUpdateURLPath != "" {
297 http.HandleFunc(*gpgUpdateURLPath, handler)
300 needsRefreshPasswd := make(chan os.Signal, 0)
301 needsShutdown := make(chan os.Signal, 0)
302 exitErr := make(chan error, 0)
303 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
304 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
306 for range needsRefreshPasswd {
307 log.Println("Refreshing passwords")
311 go func(s *http.Server) {
314 log.Println("Shutting down")
315 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
316 exitErr <- s.Shutdown(ctx)
321 err = server.Serve(ln)
323 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
325 if err != http.ErrServerClosed {
328 if err := <-exitErr; err != nil {