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
43 "golang.org/x/net/netutil"
48 UserAgent = "GoCheese/" + Version
50 Warranty = `This program is free software: you can redistribute it and/or modify
51 it under the terms of the GNU General Public License as published by
52 the Free Software Foundation, version 3 of the License.
54 This program is distributed in the hope that it will be useful,
55 but WITHOUT ANY WARRANTY; without even the implied warranty of
56 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
57 GNU General Public License for more details.
59 You should have received a copy of the GNU General Public License
60 along with this program. If not, see <http://www.gnu.org/licenses/>.`
64 Root = flag.String("root", "./packages", "Path to packages directory")
65 Bind = flag.String("bind", "[::]:8080", "Address to bind to")
66 MaxClients = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
67 DoUCSPI = flag.Bool("ucspi", false, "Work as UCSPI-TCP service")
69 TLSCert = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
70 TLSKey = flag.String("tls-key", "", "Path to TLS X.509 private key")
72 NoRefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
73 RefreshURLPath = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
74 GPGUpdateURLPath = flag.String("gpgupdate", "/gpgupdate/", "GPG forceful refreshing URL path")
75 JSONURLPath = flag.String("json", "/pypi/", "JSON API URL path")
77 PyPIURL = flag.String("pypi", "https://pypi.org/simple/", "Upstream (PyPI) URL")
78 PyPICertHash = flag.String("pypi-cert-hash", "", "Authenticate upstream by its X.509 certificate's SPKI SHA256 hash")
79 JSONURL = flag.String("pypi-json", "https://pypi.org/pypi/", "Enable and use specified JSON API upstream URL")
81 PasswdPath = flag.String("passwd", "", "Path to FIFO for upload authentication")
82 PasswdListPath = flag.String("passwd-list", "", "Path to FIFO for login listing")
83 PasswdCheck = flag.Bool("passwd-check", false, "Run password checker")
85 LogTimestamped = flag.Bool("log-timestamped", false, "Prepend timestmap to log messages")
86 FSCK = flag.Bool("fsck", false, "Check integrity of all packages (errors are in stderr)")
87 DoVersion = flag.Bool("version", false, "Print version information")
88 DoWarranty = flag.Bool("warranty", false, "Print warranty information")
93 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
94 log.Println(r.RemoteAddr, "get", filename)
95 path := filepath.Join(*Root, pkgName, filename)
96 if _, err := os.Stat(path); os.IsNotExist(err) {
97 if !refreshDir(w, r, pkgName, filename, false) {
101 http.ServeFile(w, r, path)
104 func handler(w http.ResponseWriter, r *http.Request) {
105 w.Header().Set("Server", UserAgent)
111 if strings.HasPrefix(r.URL.Path, *NoRefreshURLPath) {
112 path = strings.TrimPrefix(r.URL.Path, *NoRefreshURLPath)
113 } else if strings.HasPrefix(r.URL.Path, *RefreshURLPath) {
114 path = strings.TrimPrefix(r.URL.Path, *RefreshURLPath)
116 } else if strings.HasPrefix(r.URL.Path, *GPGUpdateURLPath) {
117 path = strings.TrimPrefix(r.URL.Path, *GPGUpdateURLPath)
121 http.Error(w, "unknown action", http.StatusBadRequest)
124 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
126 http.Error(w, "invalid path", http.StatusBadRequest)
133 serveListDir(w, r, parts[0], autorefresh, gpgUpdate)
136 servePkg(w, r, parts[0], parts[1])
141 http.Error(w, "unknown action", http.StatusBadRequest)
148 fmt.Println(Warranty)
152 fmt.Println("GoCheese", Version, "built with", runtime.Version())
157 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
159 log.SetFlags(log.Lshortfile)
162 log.SetOutput(os.Stdout)
166 if !goodIntegrity() {
173 if passwdReader(os.Stdin) {
180 if *PasswdPath != "" {
183 fd, err := os.OpenFile(
196 if *PasswdListPath != "" {
199 fd, err := os.OpenFile(
201 os.O_WRONLY|os.O_APPEND,
213 if (*TLSCert != "" && *TLSKey == "") || (*TLSCert == "" && *TLSKey != "") {
214 log.Fatalln("Both -tls-cert and -tls-key are required")
218 PyPIURLParsed, err = url.Parse(*PyPIURL)
222 tlsConfig := tls.Config{
223 ClientSessionCache: tls.NewLRUClientSessionCache(16),
224 NextProtos: []string{"h2", "http/1.1"},
226 PyPIHTTPTransport = http.Transport{
227 ForceAttemptHTTP2: true,
228 TLSClientConfig: &tlsConfig,
230 if *PyPICertHash != "" {
231 ourDgst, err := hex.DecodeString(*PyPICertHash)
235 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
236 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
237 theirDgst := sha256.Sum256(spki)
238 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
239 return errors.New("certificate's SPKI digest mismatch")
245 server := &http.Server{
246 ReadTimeout: time.Minute,
247 WriteTimeout: time.Minute,
249 http.HandleFunc("/", serveHRRoot)
250 http.HandleFunc("/hr/", serveHRPkg)
251 http.HandleFunc(*JSONURLPath, serveJSON)
252 http.HandleFunc(*NoRefreshURLPath, handler)
253 http.HandleFunc(*RefreshURLPath, handler)
254 if *GPGUpdateURLPath != "" {
255 http.HandleFunc(*GPGUpdateURLPath, handler)
259 server.SetKeepAlivesEnabled(false)
261 server.ConnState = connStater
262 err := server.Serve(ln)
263 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
270 ln, err := net.Listen("tcp", *Bind)
274 ln = netutil.LimitListener(ln, *MaxClients)
276 needsShutdown := make(chan os.Signal, 0)
277 exitErr := make(chan error, 0)
278 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
279 go func(s *http.Server) {
282 log.Println("shutting down")
283 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
284 exitErr <- s.Shutdown(ctx)
297 err = server.Serve(ln)
299 err = server.ServeTLS(ln, *TLSCert, *TLSKey)
301 if err != http.ErrServerClosed {
304 if err := <-exitErr; err != nil {