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"
47 HTMLBegin = `<!DOCTYPE html>
50 <title>Links for %s</title>
54 HTMLEnd = " </body>\n</html>\n"
55 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
56 InternalFlag = ".internal"
59 Warranty = `This program is free software: you can redistribute it and/or modify
60 it under the terms of the GNU General Public License as published by
61 the Free Software Foundation, version 3 of the License.
63 This program is distributed in the hope that it will be useful,
64 but WITHOUT ANY WARRANTY; without even the implied warranty of
65 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
66 GNU General Public License for more details.
68 You should have received a copy of the GNU General Public License
69 along with this program. If not, see <http://www.gnu.org/licenses/>.`
73 HashAlgoSHA256 = "sha256"
74 HashAlgoBLAKE2b256 = "blake2_256"
75 HashAlgoSHA512 = "sha512"
80 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
81 normalizationRe = regexp.MustCompilePOSIX("[-_.]+")
83 knownHashAlgos []string = []string{
90 root = flag.String("root", "./packages", "Path to packages directory")
91 bind = flag.String("bind", "[::]:8080", "Address to bind to")
92 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
93 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
94 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
95 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
96 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
97 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
98 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
99 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
100 fsck = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
101 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
102 version = flag.Bool("version", false, "Print version information")
103 warranty = flag.Bool("warranty", false, "Print warranty information")
106 pypiURLParsed *url.URL
109 func mkdirForPkg(w http.ResponseWriter, r *http.Request, pkgName string) bool {
110 path := filepath.Join(*root, pkgName)
111 if _, err := os.Stat(path); os.IsNotExist(err) {
112 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
113 log.Println("error", r.RemoteAddr, "mkdir", pkgName, err)
114 http.Error(w, err.Error(), http.StatusInternalServerError)
117 log.Println(r.RemoteAddr, "mkdir", pkgName)
122 func listRoot(w http.ResponseWriter, r *http.Request) {
123 files, err := ioutil.ReadDir(*root)
125 log.Println("error", r.RemoteAddr, "root", err)
126 http.Error(w, err.Error(), http.StatusInternalServerError)
129 var result bytes.Buffer
130 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
131 for _, file := range files {
132 if file.Mode().IsDir() {
133 result.WriteString(fmt.Sprintf(
135 *refreshURLPath+file.Name()+"/",
140 result.WriteString(HTMLEnd)
141 w.Write(result.Bytes())
145 w http.ResponseWriter,
148 autorefresh, gpgUpdate bool,
150 dirPath := filepath.Join(*root, pkgName)
152 if !refreshDir(w, r, pkgName, "", gpgUpdate) {
155 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, pkgName, "", false) {
158 fis, err := ioutil.ReadDir(dirPath)
160 log.Println("error", r.RemoteAddr, "list", pkgName, err)
161 http.Error(w, err.Error(), http.StatusInternalServerError)
164 files := make(map[string]struct{}, len(fis)/2)
165 for _, fi := range fis {
166 files[fi.Name()] = struct{}{}
168 var result bytes.Buffer
169 result.WriteString(fmt.Sprintf(HTMLBegin, pkgName))
170 for _, algo := range knownHashAlgos {
171 for fn, _ := range files {
173 // Skip expensive I/O when shutting down
174 http.Error(w, "shutting down", http.StatusInternalServerError)
177 if !strings.HasSuffix(fn, "."+algo) {
181 digest, err := ioutil.ReadFile(filepath.Join(dirPath, fn))
183 log.Println("error", r.RemoteAddr, "list", fn, err)
184 http.Error(w, err.Error(), http.StatusInternalServerError)
187 fnClean := strings.TrimSuffix(fn, "."+algo)
188 delete(files, fnClean)
190 if _, err = os.Stat(filepath.Join(dirPath, fnClean+GPGSigExt)); err == nil {
191 gpgSigAttr = " data-gpg-sig=true"
192 delete(files, fnClean+GPGSigExt)
194 result.WriteString(fmt.Sprintf(
196 strings.Join([]string{
197 *refreshURLPath, pkgName, "/", fnClean,
198 "#", algo, "=", hex.EncodeToString(digest),
205 result.WriteString(HTMLEnd)
206 w.Write(result.Bytes())
209 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
210 log.Println(r.RemoteAddr, "get", filename)
211 path := filepath.Join(*root, pkgName, filename)
212 if _, err := os.Stat(path); os.IsNotExist(err) {
213 if !refreshDir(w, r, pkgName, filename, false) {
217 http.ServeFile(w, r, path)
220 func handler(w http.ResponseWriter, r *http.Request) {
226 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
227 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
228 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
229 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
231 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
232 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
236 http.Error(w, "unknown action", http.StatusBadRequest)
239 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
241 http.Error(w, "invalid path", http.StatusBadRequest)
248 listDir(w, r, parts[0], autorefresh, gpgUpdate)
251 servePkg(w, r, parts[0], parts[1])
256 http.Error(w, "unknown action", http.StatusBadRequest)
263 fmt.Println(Warranty)
267 fmt.Println("GoCheese version", Version, "built with", runtime.Version())
271 if !goodIntegrity() {
280 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
281 log.Fatalln("Both -tls-cert and -tls-key are required")
284 pypiURLParsed, err = url.Parse(*pypiURL)
289 log.Println("root:", *root)
290 log.Println("bind:", *bind)
291 log.Println("pypi:", *pypiURL)
293 ln, err := net.Listen("tcp", *bind)
297 ln = netutil.LimitListener(ln, *maxClients)
298 server := &http.Server{
299 ReadTimeout: time.Minute,
300 WriteTimeout: time.Minute,
302 http.HandleFunc(*norefreshURLPath, handler)
303 http.HandleFunc(*refreshURLPath, handler)
304 if *gpgUpdateURLPath != "" {
305 http.HandleFunc(*gpgUpdateURLPath, handler)
308 needsRefreshPasswd := make(chan os.Signal, 0)
309 needsShutdown := make(chan os.Signal, 0)
310 exitErr := make(chan error, 0)
311 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
312 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
314 for range needsRefreshPasswd {
315 log.Println("refreshing passwords")
319 go func(s *http.Server) {
322 log.Println("shutting down")
323 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
324 exitErr <- s.Shutdown(ctx)
329 err = server.Serve(ln)
331 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
333 if err != http.ErrServerClosed {
336 if err := <-exitErr; err != nil {