2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019-2020 Sergey Matveev <stargrave@stargrave.org>
4 2019-2020 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, pkgName string) bool {
107 path := filepath.Join(*root, pkgName)
108 if _, err := os.Stat(path); os.IsNotExist(err) {
109 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
110 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
111 http.Error(w, err.Error(), http.StatusInternalServerError)
114 log.Println(r.RemoteAddr, "mkdir", pkgName)
119 func listRoot(w http.ResponseWriter, r *http.Request) {
120 files, err := ioutil.ReadDir(*root)
122 log.Println("error", r.RemoteAddr, "root", err)
123 http.Error(w, err.Error(), http.StatusInternalServerError)
126 var result bytes.Buffer
127 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
128 for _, file := range files {
129 if file.Mode().IsDir() {
130 result.WriteString(fmt.Sprintf(
132 *refreshURLPath+file.Name()+"/",
137 result.WriteString(HTMLEnd)
138 w.Write(result.Bytes())
142 w http.ResponseWriter,
145 autorefresh, gpgUpdate bool,
147 dirPath := filepath.Join(*root, pkgName)
149 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
152 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
155 fis, err := ioutil.ReadDir(dirPath)
157 log.Println("error", r.RemoteAddr, "list", pkgName, err)
158 http.Error(w, err.Error(), http.StatusInternalServerError)
161 files := make(map[string]struct{}, len(fis)/2)
162 for _, fi := range fis {
163 files[fi.Name()] = struct{}{}
165 var result bytes.Buffer
166 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
167 for _, algo := range knownHashAlgos {
168 for fn, _ := range files {
170 // Skip expensive I/O when shutting down
171 http.Error(w, "shutting down", http.StatusInternalServerError)
174 if !strings.HasSuffix(fn, "."+algo) {
178 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
180 log.Println("error", r.RemoteAddr, "list", fn, err)
181 http.Error(w, err.Error(), http.StatusInternalServerError)
184 fnClean := strings.TrimSuffix(fn, "."+algo)
185 delete(files, fnClean)
187 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
188 gpgSigAttr = " data-gpg-sig=true"
189 delete(files, fnClean+GPGSigExt)
191 result.WriteString(fmt.Sprintf(
193 strings.Join([]string{
194 *refreshURLPath, pkgName, "/", fnClean,
195 "#", algo, "=", hex.EncodeToString(digest),
202 result.WriteString(HTMLEnd)
203 w.Write(result.Bytes())
206 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
207 log.Println(r.RemoteAddr, "get", filename)
208 path := filepath.Join(*root, pkgName, filename)
209 if _, err := os.Stat(path); os.IsNotExist(err) {
210 if !refreshDir(w, r, pkgName, filename, false) {
214 http.ServeFile(w, r, path)
217 func handler(w http.ResponseWriter, r *http.Request) {
223 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
224 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
225 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
226 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
228 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
229 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
233 http.Error(w, "unknown action", http.StatusBadRequest)
236 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
238 http.Error(w, "invalid path", http.StatusBadRequest)
245 listDir(w, r, parts[0], autorefresh, gpgUpdate)
248 servePkg(w, r, parts[0], parts[1])
253 http.Error(w, "unknown action", http.StatusBadRequest)
260 fmt.Println(Warranty)
264 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
268 if !goodIntegrity() {
277 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
278 log.Fatalln("Both -tls-cert and -tls-key are required")
281 pypiURLParsed, err = url.Parse(*pypiURL)
286 log.Println("root:", *root)
287 log.Println("bind:", *bind)
288 log.Println("pypi:", *pypiURL)
290 ln, err := net.Listen("tcp", *bind)
294 ln = netutil.LimitListener(ln, *maxClients)
295 server := &http.Server{
296 ReadTimeout: time.Minute,
297 WriteTimeout: time.Minute,
299 http.HandleFunc(*norefreshURLPath, handler)
300 http.HandleFunc(*refreshURLPath, handler)
301 if *gpgUpdateURLPath != "" {
302 http.HandleFunc(*gpgUpdateURLPath, handler)
305 needsRefreshPasswd := make(chan os.Signal, 0)
306 needsShutdown := make(chan os.Signal, 0)
307 exitErr := make(chan error, 0)
308 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
309 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
311 for range needsRefreshPasswd {
312 log.Println("refreshing passwords")
316 go func(s *http.Server) {
319 log.Println("shutting down")
320 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
321 exitErr <- s.Shutdown(ctx)
326 err = server.Serve(ln)
328 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
330 if err != http.ErrServerClosed {
333 if err := <-exitErr; err != nil {