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
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 GPGUpdateURLPath = flag.String("gpgupdate", DefaultGPGUpdateURLPath, "")
63 JSONURLPath = flag.String("json", DefaultJSONURLPath, "")
65 PyPIURL = flag.String("pypi", DefaultPyPIURL, "")
66 JSONURL = flag.String("pypi-json", DefaultJSONURL, "")
67 PyPICertHash = flag.String("pypi-cert-hash", "", "")
69 PasswdPath = flag.String("passwd", "", "")
70 PasswdListPath = flag.String("passwd-list", "", "")
71 PasswdCheck = flag.Bool("passwd-check", false, "")
73 LogTimestamped = flag.Bool("log-timestamped", false, "")
74 FSCK = flag.Bool("fsck", false, "")
75 DoVersion = flag.Bool("version", false, "")
76 DoWarranty = flag.Bool("warranty", false, "")
81 func servePkg(w http.ResponseWriter, r *http.Request, pkgName, filename string) {
82 log.Println(r.RemoteAddr, "get", filename)
83 path := filepath.Join(Root, pkgName, filename)
84 if _, err := os.Stat(path); os.IsNotExist(err) {
85 if !refreshDir(w, r, pkgName, filename, false) {
89 http.ServeFile(w, r, path)
92 func handler(w http.ResponseWriter, r *http.Request) {
93 w.Header().Set("Server", UserAgent)
99 if strings.HasPrefix(r.URL.Path, *NoRefreshURLPath) {
100 path = strings.TrimPrefix(r.URL.Path, *NoRefreshURLPath)
101 } else if strings.HasPrefix(r.URL.Path, *RefreshURLPath) {
102 path = strings.TrimPrefix(r.URL.Path, *RefreshURLPath)
104 } else if strings.HasPrefix(r.URL.Path, *GPGUpdateURLPath) {
105 path = strings.TrimPrefix(r.URL.Path, *GPGUpdateURLPath)
109 http.Error(w, "unknown action", http.StatusBadRequest)
112 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
114 http.Error(w, "invalid path", http.StatusBadRequest)
121 serveListDir(w, r, parts[0], autorefresh, gpgUpdate)
124 servePkg(w, r, parts[0], parts[1])
129 http.Error(w, "unknown action", http.StatusBadRequest)
137 fmt.Println(Warranty)
141 fmt.Println("GoCheese", Version, "built with", runtime.Version())
146 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
148 log.SetFlags(log.Lshortfile)
151 log.SetOutput(os.Stdout)
154 if len(flag.Args()) != 1 {
158 Root = flag.Args()[0]
159 if _, err := os.Stat(Root); err != nil {
164 if !goodIntegrity() {
171 if passwdReader(os.Stdin) {
178 if *PasswdPath != "" {
181 fd, err := os.OpenFile(
194 if *PasswdListPath != "" {
197 fd, err := os.OpenFile(
199 os.O_WRONLY|os.O_APPEND,
211 if (*TLSCert != "" && *TLSKey == "") || (*TLSCert == "" && *TLSKey != "") {
212 log.Fatalln("Both -tls-cert and -tls-key are required")
216 PyPIURLParsed, err = url.Parse(*PyPIURL)
220 tlsConfig := tls.Config{
221 ClientSessionCache: tls.NewLRUClientSessionCache(16),
222 NextProtos: []string{"h2", "http/1.1"},
224 PyPIHTTPTransport = http.Transport{
225 ForceAttemptHTTP2: true,
226 TLSClientConfig: &tlsConfig,
228 if *PyPICertHash != "" {
229 ourDgst, err := hex.DecodeString(*PyPICertHash)
233 tlsConfig.VerifyConnection = func(s tls.ConnectionState) error {
234 spki := s.VerifiedChains[0][0].RawSubjectPublicKeyInfo
235 theirDgst := sha256.Sum256(spki)
236 if bytes.Compare(ourDgst, theirDgst[:]) != 0 {
237 return errors.New("certificate's SPKI digest mismatch")
243 server := &http.Server{
244 ReadTimeout: time.Minute,
245 WriteTimeout: time.Minute,
247 http.HandleFunc("/", serveHRRoot)
248 http.HandleFunc("/hr/", serveHRPkg)
249 http.HandleFunc(*JSONURLPath, serveJSON)
250 http.HandleFunc(*NoRefreshURLPath, handler)
251 http.HandleFunc(*RefreshURLPath, handler)
252 if *GPGUpdateURLPath != "" {
253 http.HandleFunc(*GPGUpdateURLPath, handler)
257 server.SetKeepAlivesEnabled(false)
259 server.ConnState = connStater
260 err := server.Serve(ln)
261 if _, ok := err.(UCSPIAlreadyAccepted); !ok {
268 ln, err := net.Listen("tcp", *Bind)
272 ln = netutil.LimitListener(ln, *MaxClients)
274 needsShutdown := make(chan os.Signal, 0)
275 exitErr := make(chan error, 0)
276 signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
277 go func(s *http.Server) {
280 log.Println("shutting down")
281 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
282 exitErr <- s.Shutdown(ctx)
294 err = server.Serve(ln)
296 err = server.ServeTLS(ln, *TLSCert, *TLSKey)
298 if err != http.ErrServerClosed {
301 if err := <-exitErr; err != nil {