2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019-2023 Sergey Matveev <stargrave@stargrave.org>
4 2019-2023 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
53 Bind = flag.String("bind", DefaultBind, "")
54 MaxClients = flag.Int("maxclients", DefaultMaxClients, "")
55 DoUCSPI = flag.Bool("ucspi", false, "")
57 TLSCert = flag.String("tls-cert", "", "")
58 TLSKey = flag.String("tls-key", "", "")
60 NoRefreshURLPath = flag.String("norefresh", DefaultNoRefreshURLPath, "")
61 RefreshURLPath = flag.String("refresh", DefaultRefreshURLPath, "")
62 JSONURLPath = flag.String("json", DefaultJSONURLPath, "")
64 PyPIURL = flag.String("pypi", DefaultPyPIURL, "")
65 JSONURL = flag.String("pypi-json", DefaultJSONURL, "")
66 PyPICertHash = flag.String("pypi-cert-hash", "", "")
68 PasswdPath = flag.String("passwd", "", "")
69 PasswdListPath = flag.String("passwd-list", "", "")
70 PasswdCheck = flag.Bool("passwd-check", false, "")
72 LogTimestamped = flag.Bool("log-timestamped", false, "")
73 FSCK = flag.Bool("fsck", false, "")
74 DoVersion = flag.Bool("version", false, "")
75 DoWarranty = flag.Bool("warranty", false, "")
80 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
81 log.Println(r.RemoteAddr, "get", filename)
82 path := filepath.Join(Root, pkgName, filename)
83 if _, err := os.Stat(path); os.IsNotExist(err) {
84 if !refreshDir(w, r, pkgName, filename) {
88 http.ServeFile(w, r, path)
91 func handler(w http.ResponseWriter, r *http.Request) {
92 w.Header().Set("Server", UserAgent)
97 if strings.HasPrefix(r.URL.Path, *NoRefreshURLPath) {
98 path = strings.TrimPrefix(r.URL.Path, *NoRefreshURLPath)
99 } else if strings.HasPrefix(r.URL.Path, *RefreshURLPath) {
100 path = strings.TrimPrefix(r.URL.Path, *RefreshURLPath)
103 http.Error(w, "unknown action", http.StatusBadRequest)
106 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
108 http.Error(w, "invalid path", http.StatusBadRequest)
115 serveListDir(w, r, parts[0], autorefresh)
118 servePkg(w, r, parts[0], parts[1])
123 http.Error(w, "unknown action", http.StatusBadRequest)
131 fmt.Println(Warranty)
135 fmt.Println("GoCheese", Version, "built with", runtime.Version())
140 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
142 log.SetFlags(log.Lshortfile)
145 log.SetOutput(os.Stdout)
148 if len(flag.Args()) != 1 {
152 Root = flag.Args()[0]
153 if _, err := os.Stat(Root); err != nil {
158 if !goodIntegrity() {
165 if passwdReader(os.Stdin) {
172 if *PasswdPath != "" {
175 fd, err := os.OpenFile(
188 if *PasswdListPath != "" {
191 fd, err := os.OpenFile(
193 os.O_WRONLY|os.O_APPEND,
205 if (*TLSCert != "" && *TLSKey == "") || (*TLSCert == "" && *TLSKey != "") {
206 log.Fatalln("Both -tls-cert and -tls-key are required")
209 UmaskCur = syscall.Umask(0)
210 syscall.Umask(UmaskCur)
213 PyPIURLParsed, err = url.Parse(*PyPIURL)
217 tlsConfig := tls.Config{
218 ClientSessionCache: tls.NewLRUClientSessionCache(16),
219 NextProtos: []string{"h2", "http/1.1"},
221 PyPIHTTPTransport = http.Transport{
222 ForceAttemptHTTP2: true,
223 TLSClientConfig: &tlsConfig,
225 if *PyPICertHash != "" {
226 ourDgst, err := hex.DecodeString(*PyPICertHash)
230 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
231 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
232 theirDgst := sha256.Sum256(spki)
233 if !bytes.Equal(ourDgst, theirDgst[:]) {
234 return errors.New("certificate's SPKI digest mismatch")
240 server := &http.Server{
241 ReadTimeout: time.Minute,
242 WriteTimeout: time.Minute,
244 http.HandleFunc("/", serveHRRoot)
245 http.HandleFunc("/hr/", serveHRPkg)
246 http.HandleFunc(*JSONURLPath, serveJSON)
247 http.HandleFunc(*NoRefreshURLPath, handler)
248 http.HandleFunc(*RefreshURLPath, handler)
251 server.SetKeepAlivesEnabled(false)
253 server.ConnState = connStater
254 err := server.Serve(ln)
255 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
262 ln, err := net.Listen("tcp", *Bind)
266 ln = netutil.LimitListener(ln, *MaxClients)
268 needsShutdown := make(chan os.Signal, 1)
269 exitErr := make(chan error)
270 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
271 go func(s *http.Server) {
274 log.Println("shutting down")
275 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
276 exitErr <- s.Shutdown(ctx)
288 err = server.Serve(ln)
290 err = server.ServeTLS(ln, *TLSCert, *TLSKey)
292 if err != http.ErrServerClosed {
295 if err := <-exitErr; err != nil {