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, "")
70 LogTimestamped = flag.Bool("log-timestamped", false, "")
71 FSCK = flag.Bool("fsck", false, "")
72 DoVersion = flag.Bool("version", false, "")
73 DoWarranty = flag.Bool("warranty", false, "")
78 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
79 log.Println(r.RemoteAddr, "get", filename)
80 path := filepath.Join(Root, pkgName, filename)
81 if _, err := os.Stat(path); os.IsNotExist(err) {
82 if !refreshDir(w, r, pkgName, filename) {
86 http.ServeFile(w, r, path)
89 func handler(w http.ResponseWriter, r *http.Request) {
90 w.Header().Set("Server", UserAgent)
95 if strings.HasPrefix(r.URL.Path, *NoRefreshURLPath) {
96 path = strings.TrimPrefix(r.URL.Path, *NoRefreshURLPath)
97 } else if strings.HasPrefix(r.URL.Path, *RefreshURLPath) {
98 path = strings.TrimPrefix(r.URL.Path, *RefreshURLPath)
101 http.Error(w, "unknown action", http.StatusBadRequest)
104 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
106 http.Error(w, "invalid path", http.StatusBadRequest)
113 serveListDir(w, r, parts[0], autorefresh)
116 servePkg(w, r, parts[0], parts[1])
121 http.Error(w, "unknown action", http.StatusBadRequest)
129 fmt.Println(Warranty)
133 fmt.Println("GoCheese", Version, "built with", runtime.Version())
138 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
140 log.SetFlags(log.Lshortfile)
143 log.SetOutput(os.Stdout)
146 if len(flag.Args()) != 1 {
150 Root = flag.Args()[0]
151 if _, err := os.Stat(Root); err != nil {
156 if !goodIntegrity() {
163 if passwdReader(os.Stdin) {
170 if *PasswdPath != "" {
173 fd, err := os.OpenFile(
186 if *PasswdListPath != "" {
189 fd, err := os.OpenFile(
191 os.O_WRONLY|os.O_APPEND,
203 if (*TLSCert != "" && *TLSKey == "") || (*TLSCert == "" && *TLSKey != "") {
204 log.Fatal("Both -tls-cert and -tls-key are required")
207 UmaskCur = syscall.Umask(0)
208 syscall.Umask(UmaskCur)
211 PyPIURLParsed, err = url.Parse(*PyPIURL)
215 tlsConfig := tls.Config{
216 ClientSessionCache: tls.NewLRUClientSessionCache(16),
217 NextProtos: []string{"h2", "http/1.1"},
219 PyPIHTTPTransport = http.Transport{
220 ForceAttemptHTTP2: true,
221 TLSClientConfig: &tlsConfig,
223 if *PyPICertHash != "" {
224 ourDgst, err := hex.DecodeString(*PyPICertHash)
228 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
229 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
230 theirDgst := sha256.Sum256(spki)
231 if !bytes.Equal(ourDgst, theirDgst[:]) {
232 return errors.New("certificate's SPKI digest mismatch")
238 server := &http.Server{
239 ReadTimeout: time.Minute,
240 WriteTimeout: time.Minute,
242 http.HandleFunc("/", serveHRRoot)
243 http.HandleFunc("/hr/", serveHRPkg)
244 http.HandleFunc(*JSONURLPath, serveJSON)
245 http.HandleFunc(*NoRefreshURLPath, handler)
246 http.HandleFunc(*RefreshURLPath, handler)
249 server.SetKeepAlivesEnabled(false)
251 server.ConnState = connStater
252 err := server.Serve(ln)
253 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
260 ln, err := net.Listen("tcp", *Bind)
264 ln = netutil.LimitListener(ln, *MaxClients)
266 needsShutdown := make(chan os.Signal, 1)
267 exitErr := make(chan error)
268 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
269 go func(s *http.Server) {
272 log.Println("shutting down")
273 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
274 exitErr <- s.Shutdown(ctx)
286 err = server.Serve(ln)
288 err = server.ServeTLS(ln, *TLSCert, *TLSKey)
290 if err != http.ErrServerClosed {
293 if err := <-exitErr; err != nil {