1 // GoCheese -- Python private package repository and caching proxy
2 // Copyright (C) 2019-2024 Sergey Matveev <stargrave@stargrave.org>
3 // 2019-2024 Elena Balakhonova <balakhonova_e@riseup.net>
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, version 3 of the License.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 // Python private package repository and caching proxy
41 "golang.org/x/net/netutil"
46 UserAgent = "GoCheese/" + Version
51 Bind = flag.String("bind", DefaultBind, "")
52 MaxClients = flag.Int("maxclients", DefaultMaxClients, "")
53 DoUCSPI = flag.Bool("ucspi", false, "")
55 TLSCert = flag.String("tls-cert", "", "")
56 TLSKey = flag.String("tls-key", "", "")
58 NoRefreshURLPath = flag.String("norefresh", DefaultNoRefreshURLPath, "")
59 RefreshURLPath = flag.String("refresh", DefaultRefreshURLPath, "")
60 JSONURLPath = flag.String("json", DefaultJSONURLPath, "")
62 PyPIURL = flag.String("pypi", DefaultPyPIURL, "")
63 JSONURL = flag.String("pypi-json", DefaultJSONURL, "")
64 PyPICertHash = flag.String("pypi-cert-hash", "", "")
66 PasswdPath = flag.String("passwd", "", "")
67 PasswdListPath = flag.String("passwd-list", "", "")
68 PasswdCheck = flag.Bool("passwd-check", false, "")
69 AuthRequired = flag.Bool("auth-required", false, "")
71 LogTimestamped = flag.Bool("log-timestamped", false, "")
72 FSCK = flag.Bool("fsck", false, "")
73 DoVersion = flag.Bool("version", false, "")
74 DoWarranty = flag.Bool("warranty", false, "")
79 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
80 log.Println(r.RemoteAddr, "get", filename)
81 path := filepath.Join(Root, pkgName, filename)
82 if _, err := os.Stat(path); os.IsNotExist(err) {
83 if !refreshDir(w, r, pkgName, filename) {
87 http.ServeFile(w, r, path)
90 func handler(w http.ResponseWriter, r *http.Request) {
91 w.Header().Set("Server", UserAgent)
96 if strings.HasPrefix(r.URL.Path, *NoRefreshURLPath) {
97 path = strings.TrimPrefix(r.URL.Path, *NoRefreshURLPath)
98 } else if strings.HasPrefix(r.URL.Path, *RefreshURLPath) {
99 path = strings.TrimPrefix(r.URL.Path, *RefreshURLPath)
102 http.Error(w, "unknown action", http.StatusBadRequest)
105 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
107 http.Error(w, "invalid path", http.StatusBadRequest)
114 serveListDir(w, r, parts[0], autorefresh)
117 servePkg(w, r, parts[0], parts[1])
122 http.Error(w, "unknown action", http.StatusBadRequest)
130 fmt.Println(Warranty)
134 fmt.Println("GoCheese", Version, "built with", runtime.Version())
139 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
141 log.SetFlags(log.Lshortfile)
144 log.SetOutput(os.Stdout)
147 if len(flag.Args()) != 1 {
151 Root = flag.Args()[0]
152 if _, err := os.Stat(Root); err != nil {
157 if !goodIntegrity() {
164 if passwdReader(os.Stdin) {
171 if *PasswdPath != "" {
174 fd, err := os.OpenFile(
187 if *PasswdListPath != "" {
190 fd, err := os.OpenFile(
192 os.O_WRONLY|os.O_APPEND,
204 if (*TLSCert != "" && *TLSKey == "") || (*TLSCert == "" && *TLSKey != "") {
205 log.Fatal("Both -tls-cert and -tls-key are required")
208 UmaskCur = syscall.Umask(0)
209 syscall.Umask(UmaskCur)
212 PyPIURLParsed, err = url.Parse(*PyPIURL)
216 tlsConfig := tls.Config{
217 ClientSessionCache: tls.NewLRUClientSessionCache(16),
218 NextProtos: []string{"h2", "http/1.1"},
220 PyPIHTTPTransport = http.Transport{
221 ForceAttemptHTTP2: true,
222 TLSClientConfig: &tlsConfig,
224 if *PyPICertHash != "" {
225 ourDgst, err := hex.DecodeString(*PyPICertHash)
229 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
230 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
231 theirDgst := sha256.Sum256(spki)
232 if !bytes.Equal(ourDgst, theirDgst[:]) {
233 return errors.New("certificate's SPKI digest mismatch")
239 server := &http.Server{
240 ReadTimeout: time.Minute,
241 WriteTimeout: time.Minute,
243 http.HandleFunc("/", checkAuth(serveHRRoot))
244 http.HandleFunc("/hr/", checkAuth(serveHRPkg))
245 http.HandleFunc(*JSONURLPath, checkAuth(serveJSON))
246 http.HandleFunc(*NoRefreshURLPath, checkAuth(handler))
247 http.HandleFunc(*RefreshURLPath, checkAuth(handler))
250 server.SetKeepAlivesEnabled(false)
252 server.ConnState = connStater
253 err := server.Serve(ln)
254 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
261 ln, err := net.Listen("tcp", *Bind)
265 ln = netutil.LimitListener(ln, *MaxClients)
267 needsShutdown := make(chan os.Signal, 1)
268 exitErr := make(chan error)
269 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
270 go func(s *http.Server) {
273 log.Println("shutting down")
274 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
275 exitErr <- s.Shutdown(ctx)
287 err = server.Serve(ln)
289 err = server.ServeTLS(ln, *TLSCert, *TLSKey)
291 if err != http.ErrServerClosed {
294 if err := <-exitErr; err != nil {