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
44 "golang.org/x/net/netutil"
48 HTMLBegin = `<!DOCTYPE html>
51 <title>Links for %s</title>
55 HTMLEnd = " </body>\n</html>\n"
56 HTMLElement = " <a href=\"%s\"%s>%s</a><br/>\n"
57 SHA256Prefix = "sha256="
59 InternalFlag = ".internal"
61 GPGSigAttr = " data-gpg-sig=true"
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 pkgPyPI = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
78 Version string = "UNKNOWN"
80 root = flag.String("root", "./packages", "Path to packages directory")
81 bind = flag.String("bind", "[::]:8080", "Address to bind to")
82 tlsCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
83 tlsKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
84 norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
85 refreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
86 gpgUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
87 pypiURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
88 passwdPath = flag.String("passwd", "passwd", "Path to file with authenticators")
89 passwdCheck = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
90 fsck = flag.Bool("fsck", false, "Check integrity of all packages")
91 maxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
92 version = flag.Bool("version", false, "Print version information")
93 warranty = flag.Bool("warranty", false, "Print warranty information")
97 normalizationRe *regexp.Regexp = regexp.MustCompilePOSIX("[-_.]+")
100 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
101 path := filepath.Join(*root, dir)
102 if _, err := os.Stat(path); os.IsNotExist(err) {
103 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
104 http.Error(w, err.Error(), http.StatusInternalServerError)
107 log.Println(r.RemoteAddr, "mkdir", dir)
113 w http.ResponseWriter,
119 if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
122 resp, err := http.Get(*pypiURL + dir + "/")
124 http.Error(w, err.Error(), http.StatusBadGateway)
127 body, err := ioutil.ReadAll(resp.Body)
130 http.Error(w, err.Error(), http.StatusBadGateway)
133 if !mkdirForPkg(w, r, dir) {
136 dirPath := filepath.Join(*root, dir)
137 var submatches []string
143 for _, lineRaw := range bytes.Split(body, []byte("\n")) {
144 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
145 if len(submatches) == 0 {
149 filename = submatches[2]
150 if pkgURL, err = url.Parse(uri); err != nil {
151 http.Error(w, err.Error(), http.StatusInternalServerError)
154 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
156 http.Error(w, err.Error(), http.StatusBadGateway)
160 path = filepath.Join(dirPath, filename)
161 if filename == filenameGet {
163 // Skip heavy remote call, when shutting down
164 http.Error(w, "shutting down", http.StatusInternalServerError)
167 log.Println(r.RemoteAddr, "pypi download", filename)
168 resp, err = http.Get(pkgURL.String())
170 http.Error(w, err.Error(), http.StatusBadGateway)
173 defer resp.Body.Close()
174 hasher := sha256.New()
175 dst, err := TempFile(dirPath)
177 http.Error(w, err.Error(), http.StatusInternalServerError)
180 wr := io.MultiWriter(hasher, dst)
181 if _, err = io.Copy(wr, resp.Body); err != nil {
182 os.Remove(dst.Name())
184 http.Error(w, err.Error(), http.StatusInternalServerError)
187 if bytes.Compare(hasher.Sum(nil), digest) != 0 {
188 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
189 os.Remove(dst.Name())
191 http.Error(w, err.Error(), http.StatusBadGateway)
194 if err = dst.Sync(); err != nil {
195 os.Remove(dst.Name())
197 http.Error(w, err.Error(), http.StatusInternalServerError)
201 if err = os.Rename(dst.Name(), path); err != nil {
202 http.Error(w, err.Error(), http.StatusInternalServerError)
205 if err = DirSync(dirPath); err != nil {
206 http.Error(w, err.Error(), http.StatusInternalServerError)
210 if filename == filenameGet || gpgUpdate {
211 if _, err = os.Stat(path); err == nil {
212 if resp, err := http.Get(pkgURL.String() + GPGSigExt); err == nil {
213 sig, err := ioutil.ReadAll(resp.Body)
216 if err = WriteFileSync(dirPath, path+GPGSigExt, sig); err != nil {
217 http.Error(w, err.Error(), http.StatusInternalServerError)
220 log.Println(r.RemoteAddr, "pypi downloaded signature", filename)
225 path = path + SHA256Ext
226 _, err = os.Stat(path)
230 if !os.IsNotExist(err) {
231 http.Error(w, err.Error(), http.StatusInternalServerError)
234 log.Println(r.RemoteAddr, "pypi touch", filename)
235 if err = WriteFileSync(dirPath, path, digest); err != nil {
236 http.Error(w, err.Error(), http.StatusInternalServerError)
243 func listRoot(w http.ResponseWriter, r *http.Request) {
244 files, err := ioutil.ReadDir(*root)
246 http.Error(w, err.Error(), http.StatusInternalServerError)
249 var result bytes.Buffer
250 result.WriteString(fmt.Sprintf(HTMLBegin, "root"))
251 for _, file := range files {
252 if file.Mode().IsDir() {
253 result.WriteString(fmt.Sprintf(
255 *refreshURLPath+file.Name()+"/",
260 result.WriteString(HTMLEnd)
261 w.Write(result.Bytes())
265 w http.ResponseWriter,
271 dirPath := filepath.Join(*root, dir)
273 if !refreshDir(w, r, dir, "", gpgUpdate) {
276 } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "", false) {
279 files, err := ioutil.ReadDir(dirPath)
281 http.Error(w, err.Error(), http.StatusInternalServerError)
284 var result bytes.Buffer
285 result.WriteString(fmt.Sprintf(HTMLBegin, dir))
287 var gpgSigAttr string
288 var filenameClean string
289 for _, file := range files {
290 if !strings.HasSuffix(file.Name(), SHA256Ext) {
294 // Skip expensive I/O when shutting down
295 http.Error(w, "shutting down", http.StatusInternalServerError)
298 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
300 http.Error(w, err.Error(), http.StatusInternalServerError)
303 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
304 if _, err = os.Stat(filepath.Join(dirPath, filenameClean+GPGSigExt)); os.IsNotExist(err) {
307 gpgSigAttr = GPGSigAttr
309 result.WriteString(fmt.Sprintf(
311 strings.Join([]string{
312 *refreshURLPath, dir, "/",
313 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
319 result.WriteString(HTMLEnd)
320 w.Write(result.Bytes())
323 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
324 log.Println(r.RemoteAddr, "get", filename)
325 path := filepath.Join(*root, dir, filename)
326 if _, err := os.Stat(path); os.IsNotExist(err) {
327 if !refreshDir(w, r, dir, filename, false) {
331 http.ServeFile(w, r, path)
334 func serveUpload(w http.ResponseWriter, r *http.Request) {
336 username, password, ok := r.BasicAuth()
338 log.Println(r.RemoteAddr, "unauthenticated", username)
339 http.Error(w, "unauthenticated", http.StatusUnauthorized)
342 auther, ok := passwords[username]
343 if !ok || !auther.Auth(password) {
344 log.Println(r.RemoteAddr, "unauthenticated", username)
345 http.Error(w, "unauthenticated", http.StatusUnauthorized)
351 if err = r.ParseMultipartForm(1 << 20); err != nil {
352 http.Error(w, err.Error(), http.StatusBadRequest)
355 pkgNames, exists := r.MultipartForm.Value["name"]
356 if !exists || len(pkgNames) != 1 {
357 http.Error(w, "single name is expected in request", http.StatusBadRequest)
360 dir := normalizationRe.ReplaceAllString(pkgNames[0], "-")
361 dirPath := filepath.Join(*root, dir)
362 var digestExpected []byte
363 if digestExpectedHex, exists := r.MultipartForm.Value["sha256_digest"]; exists {
364 digestExpected, err = hex.DecodeString(digestExpectedHex[0])
366 http.Error(w, "bad sha256_digest: "+err.Error(), http.StatusBadRequest)
370 gpgSigsExpected := make(map[string]struct{})
372 // Checking is it internal package
373 if _, err = os.Stat(filepath.Join(dirPath, InternalFlag)); err != nil {
374 log.Println(r.RemoteAddr, "non-internal package", dir)
375 http.Error(w, "unknown internal package", http.StatusUnauthorized)
379 for _, file := range r.MultipartForm.File["content"] {
380 filename := file.Filename
381 gpgSigsExpected[filename+GPGSigExt] = struct{}{}
382 log.Println(r.RemoteAddr, "put", filename, "by", username)
383 path := filepath.Join(dirPath, filename)
384 if _, err = os.Stat(path); err == nil {
385 log.Println(r.RemoteAddr, "already exists", filename)
386 http.Error(w, "already exists", http.StatusBadRequest)
389 if !mkdirForPkg(w, r, dir) {
392 src, err := file.Open()
395 http.Error(w, err.Error(), http.StatusInternalServerError)
398 dst, err := TempFile(dirPath)
400 http.Error(w, err.Error(), http.StatusInternalServerError)
403 hasher := sha256.New()
404 wr := io.MultiWriter(hasher, dst)
405 if _, err = io.Copy(wr, src); err != nil {
406 os.Remove(dst.Name())
408 http.Error(w, err.Error(), http.StatusInternalServerError)
411 if err = dst.Sync(); err != nil {
412 os.Remove(dst.Name())
414 http.Error(w, err.Error(), http.StatusInternalServerError)
418 digest := hasher.Sum(nil)
419 if digestExpected != nil {
420 if bytes.Compare(digestExpected, digest) == 0 {
421 log.Println(r.RemoteAddr, filename, "good checksum received")
423 log.Println(r.RemoteAddr, filename, "bad checksum received")
424 http.Error(w, "bad checksum", http.StatusBadRequest)
425 os.Remove(dst.Name())
429 if err = os.Rename(dst.Name(), path); err != nil {
430 http.Error(w, err.Error(), http.StatusInternalServerError)
433 if err = DirSync(dirPath); err != nil {
434 http.Error(w, err.Error(), http.StatusInternalServerError)
437 if err = WriteFileSync(dirPath, path+SHA256Ext, digest); err != nil {
438 http.Error(w, err.Error(), http.StatusInternalServerError)
442 for _, file := range r.MultipartForm.File["gpg_signature"] {
443 filename := file.Filename
444 if _, exists := gpgSigsExpected[filename]; !exists {
445 http.Error(w, "unexpected GPG signature filename", http.StatusBadRequest)
448 delete(gpgSigsExpected, filename)
449 log.Println(r.RemoteAddr, "put", filename, "by", username)
450 path := filepath.Join(dirPath, filename)
451 if _, err = os.Stat(path); err == nil {
452 log.Println(r.RemoteAddr, "already exists", filename)
453 http.Error(w, "already exists", http.StatusBadRequest)
456 src, err := file.Open()
458 http.Error(w, err.Error(), http.StatusInternalServerError)
461 sig, err := ioutil.ReadAll(src)
464 http.Error(w, err.Error(), http.StatusInternalServerError)
467 if err = WriteFileSync(dirPath, path, sig); err != nil {
468 http.Error(w, err.Error(), http.StatusInternalServerError)
474 func handler(w http.ResponseWriter, r *http.Request) {
480 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
481 path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
482 } else if strings.HasPrefix(r.URL.Path, *refreshURLPath) {
483 path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
485 } else if strings.HasPrefix(r.URL.Path, *gpgUpdateURLPath) {
486 path = strings.TrimPrefix(r.URL.Path, *gpgUpdateURLPath)
490 http.Error(w, "unknown action", http.StatusBadRequest)
493 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
495 http.Error(w, "invalid path", http.StatusBadRequest)
502 listDir(w, r, parts[0], autorefresh, gpgUpdate)
505 servePkg(w, r, parts[0], parts[1])
510 http.Error(w, "unknown action", http.StatusBadRequest)
514 func goodIntegrity() bool {
515 dirs, err := ioutil.ReadDir(*root)
519 hasher := sha256.New()
520 digest := make([]byte, sha256.Size)
524 for _, dir := range dirs {
525 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
529 for _, file := range files {
530 if !strings.HasSuffix(file.Name(), SHA256Ext) {
533 pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
534 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
536 if os.IsNotExist(err) {
542 data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
546 if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
547 log.Println(pkgName, "GOOD")
550 log.Println(pkgName, "BAD")
561 fmt.Println(Warranty)
565 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
569 if !goodIntegrity() {
578 if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
579 log.Fatalln("Both -tls-cert and -tls-key are required")
582 log.Println("root:", *root, "bind:", *bind)
584 ln, err := net.Listen("tcp", *bind)
588 ln = netutil.LimitListener(ln, *maxClients)
589 server := &http.Server{
590 ReadTimeout: time.Minute,
591 WriteTimeout: time.Minute,
593 http.HandleFunc(*norefreshURLPath, handler)
594 http.HandleFunc(*refreshURLPath, handler)
595 http.HandleFunc(*gpgUpdateURLPath, handler)
597 needsRefreshPasswd := make(chan os.Signal, 0)
598 needsShutdown := make(chan os.Signal, 0)
599 exitErr := make(chan error, 0)
600 signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
601 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
603 for range needsRefreshPasswd {
604 log.Println("Refreshing passwords")
608 go func(s *http.Server) {
611 log.Println("Shutting down")
612 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
613 exitErr <- s.Shutdown(ctx)
618 err = server.Serve(ln)
620 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
622 if err != http.ErrServerClosed {
625 if err := <-exitErr; err != nil {