]> Cypherpunks.ru repositories - gocheese.git/blob - gocheese.go
Send whole buffered response, preventing chunked encoding
[gocheese.git] / gocheese.go
1 /*
2 GoCheese -- Python private package repository and caching proxy
3 Copyright (C) 2019 Sergey Matveev <stargrave@stargrave.org>
4               2019 Elena Balakhonova <balakhonova_e@riseup.net>
5
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.
9
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.
14
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/>.
17 */
18
19 // Python private package repository and caching proxy
20 package main
21
22 import (
23         "bytes"
24         "context"
25         "crypto/sha256"
26         "encoding/hex"
27         "flag"
28         "fmt"
29         "io"
30         "io/ioutil"
31         "log"
32         "net"
33         "net/http"
34         "net/url"
35         "os"
36         "os/signal"
37         "path/filepath"
38         "regexp"
39         "runtime"
40         "strings"
41         "syscall"
42         "time"
43
44         "golang.org/x/net/netutil"
45 )
46
47 const (
48         HTMLBegin    = "<!DOCTYPE html><html><head><title>Links for %s</title></head><body><h1>Links for %s</h1>\n"
49         HTMLEnd      = "</body></html>"
50         HTMLElement  = "<a href='%s'>%s</a><br/>\n"
51         SHA256Prefix = "sha256="
52         SHA256Ext    = ".sha256"
53         InternalFlag = ".internal"
54
55         Warranty = `This program is free software: you can redistribute it and/or modify
56 it under the terms of the GNU General Public License as published by
57 the Free Software Foundation, version 3 of the License.
58
59 This program is distributed in the hope that it will be useful,
60 but WITHOUT ANY WARRANTY; without even the implied warranty of
61 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
62 GNU General Public License for more details.
63
64 You should have received a copy of the GNU General Public License
65 along with this program.  If not, see <http://www.gnu.org/licenses/>.`
66 )
67
68 var (
69         pkgPyPI        = regexp.MustCompile(`^.*<a href="([^"]+)"[^>]*>(.+)</a><br/>.*$`)
70         Version string = "UNKNOWN"
71
72         root             = flag.String("root", "./packages", "Path to packages directory")
73         bind             = flag.String("bind", "[::]:8080", "Address to bind to")
74         tlsCert          = flag.String("tls-cert", "", "Path to TLS X.509 certificate")
75         tlsKey           = flag.String("tls-key", "", "Path to TLS X.509 private key")
76         norefreshURLPath = flag.String("norefresh", "/norefresh/", "Non-refreshing URL path")
77         refreshURLPath   = flag.String("refresh", "/simple/", "Auto-refreshing URL path")
78         pypiURL          = flag.String("pypi", "https://pypi.org/simple/", "Upstream PyPI URL")
79         passwdPath       = flag.String("passwd", "passwd", "Path to file with authenticators")
80         passwdCheck      = flag.Bool("passwd-check", false, "Test the -passwd file for syntax errors and exit")
81         fsck             = flag.Bool("fsck", false, "Check integrity of all packages")
82         maxClients       = flag.Int("maxclients", 128, "Maximal amount of simultaneous clients")
83         version          = flag.Bool("version", false, "Print version information")
84         warranty         = flag.Bool("warranty", false, "Print warranty information")
85 )
86
87 func mkdirForPkg(w http.ResponseWriter, r *http.Request, dir string) bool {
88         path := filepath.Join(*root, dir)
89         if _, err := os.Stat(path); os.IsNotExist(err) {
90                 if err = os.Mkdir(path, os.FileMode(0777)); err != nil {
91                         http.Error(w, err.Error(), http.StatusInternalServerError)
92                         return false
93                 }
94                 log.Println(r.RemoteAddr, "mkdir", dir)
95         }
96         return true
97 }
98
99 func refreshDir(w http.ResponseWriter, r *http.Request, dir, filenameGet string) bool {
100         if _, err := os.Stat(filepath.Join(*root, dir, InternalFlag)); err == nil {
101                 log.Println(r.RemoteAddr, "pypi refresh skip, internal package", dir)
102                 return true
103         }
104         log.Println(r.RemoteAddr, "pypi refresh", dir)
105         resp, err := http.Get(*pypiURL + dir + "/")
106         if err != nil {
107                 http.Error(w, err.Error(), http.StatusBadGateway)
108                 return false
109         }
110         body, err := ioutil.ReadAll(resp.Body)
111         resp.Body.Close()
112         if err != nil {
113                 http.Error(w, err.Error(), http.StatusBadGateway)
114                 return false
115         }
116         if !mkdirForPkg(w, r, dir) {
117                 return false
118         }
119         var submatches []string
120         var uri string
121         var filename string
122         var path string
123         var pkgURL *url.URL
124         var digest []byte
125         for _, lineRaw := range bytes.Split(body, []byte("\n")) {
126                 submatches = pkgPyPI.FindStringSubmatch(string(lineRaw))
127                 if len(submatches) == 0 {
128                         continue
129                 }
130                 uri = submatches[1]
131                 filename = submatches[2]
132                 if pkgURL, err = url.Parse(uri); err != nil {
133                         http.Error(w, err.Error(), http.StatusInternalServerError)
134                         return false
135                 }
136                 digest, err = hex.DecodeString(strings.TrimPrefix(pkgURL.Fragment, SHA256Prefix))
137                 if err != nil {
138                         http.Error(w, err.Error(), http.StatusBadGateway)
139                         return false
140                 }
141                 if filename == filenameGet {
142                         log.Println(r.RemoteAddr, "pypi download", filename)
143                         path = filepath.Join(*root, dir, filename)
144                         resp, err = http.Get(uri)
145                         if err != nil {
146                                 http.Error(w, err.Error(), http.StatusBadGateway)
147                                 return false
148                         }
149                         defer resp.Body.Close()
150                         hasher := sha256.New()
151                         dst, err := TempFile(filepath.Join(*root, dir))
152                         if err != nil {
153                                 http.Error(w, err.Error(), http.StatusInternalServerError)
154                                 return false
155                         }
156                         wr := io.MultiWriter(hasher, dst)
157                         if _, err = io.Copy(wr, resp.Body); err != nil {
158                                 os.Remove(dst.Name())
159                                 dst.Close()
160                                 http.Error(w, err.Error(), http.StatusInternalServerError)
161                                 return false
162                         }
163                         if bytes.Compare(hasher.Sum(nil), digest) != 0 {
164                                 log.Println(r.RemoteAddr, "pypi", filename, "digest mismatch")
165                                 os.Remove(dst.Name())
166                                 dst.Close()
167                                 http.Error(w, err.Error(), http.StatusBadGateway)
168                                 return false
169                         }
170                         if err = dst.Sync(); err != nil {
171                                 os.Remove(dst.Name())
172                                 dst.Close()
173                                 http.Error(w, err.Error(), http.StatusInternalServerError)
174                                 return false
175                         }
176                         dst.Close()
177                         if err = os.Rename(dst.Name(), path); err != nil {
178                                 http.Error(w, err.Error(), http.StatusInternalServerError)
179                                 return false
180                         }
181                 }
182                 path = filepath.Join(*root, dir, filename+SHA256Ext)
183                 _, err = os.Stat(path)
184                 if err == nil {
185                         continue
186                 }
187                 if !os.IsNotExist(err) {
188                         http.Error(w, err.Error(), http.StatusInternalServerError)
189                         return false
190                 }
191                 log.Println(r.RemoteAddr, "pypi touch", filename)
192                 if err = ioutil.WriteFile(path, digest, os.FileMode(0666)); err != nil {
193                         http.Error(w, err.Error(), http.StatusInternalServerError)
194                         return false
195                 }
196         }
197         return true
198 }
199
200 func listRoot(w http.ResponseWriter, r *http.Request) {
201         log.Println(r.RemoteAddr, "root")
202         files, err := ioutil.ReadDir(*root)
203         if err != nil {
204                 http.Error(w, err.Error(), http.StatusInternalServerError)
205                 return
206         }
207         var result bytes.Buffer
208         result.WriteString(fmt.Sprintf(HTMLBegin, "root", "root"))
209         for _, file := range files {
210                 if file.Mode().IsDir() {
211                         result.WriteString(fmt.Sprintf(
212                                 HTMLElement,
213                                 *refreshURLPath+file.Name()+"/",
214                                 file.Name(),
215                         ))
216                 }
217         }
218         result.WriteString(HTMLEnd)
219         w.Write(result.Bytes())
220 }
221
222 func listDir(w http.ResponseWriter, r *http.Request, dir string, autorefresh bool) {
223         log.Println(r.RemoteAddr, "dir", dir)
224         dirPath := filepath.Join(*root, dir)
225         if autorefresh {
226                 if !refreshDir(w, r, dir, "") {
227                         return
228                 }
229         } else if _, err := os.Stat(dirPath); os.IsNotExist(err) && !refreshDir(w, r, dir, "") {
230                 return
231         }
232         files, err := ioutil.ReadDir(dirPath)
233         if err != nil {
234                 http.Error(w, err.Error(), http.StatusInternalServerError)
235                 return
236         }
237         var result bytes.Buffer
238         result.WriteString(fmt.Sprintf(HTMLBegin, dir, dir))
239         var data []byte
240         var filenameClean string
241         for _, file := range files {
242                 if !strings.HasSuffix(file.Name(), SHA256Ext) {
243                         continue
244                 }
245                 data, err = ioutil.ReadFile(filepath.Join(dirPath, file.Name()))
246                 if err != nil {
247                         http.Error(w, err.Error(), http.StatusInternalServerError)
248                         return
249                 }
250                 filenameClean = strings.TrimSuffix(file.Name(), SHA256Ext)
251                 result.WriteString(fmt.Sprintf(
252                         HTMLElement,
253                         strings.Join([]string{
254                                 *refreshURLPath, dir, "/",
255                                 filenameClean, "#", SHA256Prefix, hex.EncodeToString(data),
256                         }, ""),
257                         filenameClean,
258                 ))
259         }
260         result.WriteString(HTMLEnd)
261         w.Write(result.Bytes())
262 }
263
264 func servePkg(w http.ResponseWriter, r *http.Request, dir, filename string) {
265         log.Println(r.RemoteAddr, "pkg", filename)
266         path := filepath.Join(*root, dir, filename)
267         if _, err := os.Stat(path); os.IsNotExist(err) {
268                 if !refreshDir(w, r, dir, filename) {
269                         return
270                 }
271         }
272         http.ServeFile(w, r, path)
273 }
274
275 func serveUpload(w http.ResponseWriter, r *http.Request) {
276         username, password, ok := r.BasicAuth()
277         if !ok {
278                 log.Println(r.RemoteAddr, "unauthenticated", username)
279                 http.Error(w, "unauthenticated", http.StatusUnauthorized)
280                 return
281         }
282         auther, ok := passwords[username]
283         if !ok || !auther.Auth(password) {
284                 log.Println(r.RemoteAddr, "unauthenticated", username)
285                 http.Error(w, "unauthenticated", http.StatusUnauthorized)
286                 return
287         }
288         var err error
289         if err = r.ParseMultipartForm(1 << 20); err != nil {
290                 http.Error(w, err.Error(), http.StatusBadRequest)
291                 return
292         }
293         for _, file := range r.MultipartForm.File["content"] {
294                 filename := file.Filename
295                 log.Println(r.RemoteAddr, "upload", filename, "by", username)
296                 dir := filename[:strings.LastIndex(filename, "-")]
297                 dirPath := filepath.Join(*root, dir)
298                 path := filepath.Join(dirPath, filename)
299                 if _, err = os.Stat(path); err == nil {
300                         log.Println(r.RemoteAddr, "already exists", filename)
301                         http.Error(w, "Already exists", http.StatusBadRequest)
302                         return
303                 }
304                 if !mkdirForPkg(w, r, dir) {
305                         return
306                 }
307                 internalPath := filepath.Join(dirPath, InternalFlag)
308                 var dst *os.File
309                 if _, err = os.Stat(internalPath); os.IsNotExist(err) {
310                         if dst, err = os.Create(internalPath); err != nil {
311                                 http.Error(w, err.Error(), http.StatusInternalServerError)
312                                 return
313                         }
314                         dst.Close()
315                 }
316                 src, err := file.Open()
317                 defer src.Close()
318                 if err != nil {
319                         http.Error(w, err.Error(), http.StatusInternalServerError)
320                         return
321                 }
322                 dst, err = TempFile(dirPath)
323                 if err != nil {
324                         http.Error(w, err.Error(), http.StatusInternalServerError)
325                         return
326                 }
327                 hasher := sha256.New()
328                 wr := io.MultiWriter(hasher, dst)
329                 if _, err = io.Copy(wr, src); err != nil {
330                         os.Remove(dst.Name())
331                         dst.Close()
332                         http.Error(w, err.Error(), http.StatusInternalServerError)
333                         return
334                 }
335                 if err = dst.Sync(); err != nil {
336                         os.Remove(dst.Name())
337                         dst.Close()
338                         http.Error(w, err.Error(), http.StatusInternalServerError)
339                         return
340                 }
341                 dst.Close()
342                 if err = os.Rename(dst.Name(), path); err != nil {
343                         http.Error(w, err.Error(), http.StatusInternalServerError)
344                         return
345                 }
346                 if err = ioutil.WriteFile(path+SHA256Ext, hasher.Sum(nil), os.FileMode(0666)); err != nil {
347                         http.Error(w, err.Error(), http.StatusInternalServerError)
348                         return
349                 }
350         }
351 }
352
353 func handler(w http.ResponseWriter, r *http.Request) {
354         if r.Method == "GET" {
355                 var path string
356                 var autorefresh bool
357                 if strings.HasPrefix(r.URL.Path, *norefreshURLPath) {
358                         path = strings.TrimPrefix(r.URL.Path, *norefreshURLPath)
359                         autorefresh = false
360                 } else {
361                         path = strings.TrimPrefix(r.URL.Path, *refreshURLPath)
362                         autorefresh = true
363                 }
364                 parts := strings.Split(strings.TrimSuffix(path, "/"), "/")
365                 if len(parts) > 2 {
366                         http.Error(w, "invalid path", http.StatusBadRequest)
367                         return
368                 }
369                 if len(parts) == 1 {
370                         if parts[0] == "" {
371                                 listRoot(w, r)
372                         } else {
373                                 listDir(w, r, parts[0], autorefresh)
374                         }
375                 } else {
376                         servePkg(w, r, parts[0], parts[1])
377                 }
378         } else if r.Method == "POST" {
379                 serveUpload(w, r)
380         }
381 }
382
383 func goodIntegrity() bool {
384         dirs, err := ioutil.ReadDir(*root)
385         if err != nil {
386                 log.Fatal(err)
387         }
388         hasher := sha256.New()
389         digest := make([]byte, sha256.Size)
390         isGood := true
391         var data []byte
392         var pkgName string
393         for _, dir := range dirs {
394                 files, err := ioutil.ReadDir(filepath.Join(*root, dir.Name()))
395                 if err != nil {
396                         log.Fatal(err)
397                 }
398                 for _, file := range files {
399                         if !strings.HasSuffix(file.Name(), SHA256Ext) {
400                                 continue
401                         }
402                         pkgName = strings.TrimSuffix(file.Name(), SHA256Ext)
403                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), pkgName))
404                         if err != nil {
405                                 if os.IsNotExist(err) {
406                                         continue
407                                 }
408                                 log.Fatal(err)
409                         }
410                         hasher.Write(data)
411                         data, err = ioutil.ReadFile(filepath.Join(*root, dir.Name(), file.Name()))
412                         if err != nil {
413                                 log.Fatal(err)
414                         }
415                         if bytes.Compare(hasher.Sum(digest[:0]), data) == 0 {
416                                 log.Println(pkgName, "GOOD")
417                         } else {
418                                 isGood = false
419                                 log.Println(pkgName, "BAD")
420                         }
421                         hasher.Reset()
422                 }
423         }
424         return isGood
425 }
426
427 func main() {
428         flag.Parse()
429         if *warranty {
430                 fmt.Println(Warranty)
431                 return
432         }
433         if *version {
434                 fmt.Println("GoCheese version " + Version + " built with " + runtime.Version())
435                 return
436         }
437         if *fsck {
438                 if !goodIntegrity() {
439                         os.Exit(1)
440                 }
441                 return
442         }
443         if *passwdCheck {
444                 refreshPasswd()
445                 return
446         }
447         if (*tlsCert != "" && *tlsKey == "") || (*tlsCert == "" && *tlsKey != "") {
448                 log.Fatalln("Both -tls-cert and -tls-key are required")
449         }
450         refreshPasswd()
451         log.Println("root:", *root, "bind:", *bind)
452
453         ln, err := net.Listen("tcp", *bind)
454         if err != nil {
455                 log.Fatal(err)
456         }
457         ln = netutil.LimitListener(ln, *maxClients)
458         server := &http.Server{
459                 ReadTimeout:  time.Minute,
460                 WriteTimeout: time.Minute,
461         }
462         http.HandleFunc(*norefreshURLPath, handler)
463         http.HandleFunc(*refreshURLPath, handler)
464
465         needsRefreshPasswd := make(chan os.Signal, 0)
466         needsShutdown := make(chan os.Signal, 0)
467         killed := make(chan error, 0)
468         signal.Notify(needsRefreshPasswd, syscall.SIGHUP)
469         signal.Notify(needsShutdown, syscall.SIGTERM, syscall.SIGINT)
470         go func() {
471                 for range needsRefreshPasswd {
472                         log.Println("Refreshing passwords")
473                         refreshPasswd()
474                 }
475         }()
476         go func(s *http.Server) {
477                 <-needsShutdown
478                 log.Println("Shutting down")
479                 ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
480                 killed <- s.Shutdown(ctx)
481                 cancel()
482         }(server)
483
484         if *tlsCert == "" {
485                 err = server.Serve(ln)
486         } else {
487                 err = server.ServeTLS(ln, *tlsCert, *tlsKey)
488         }
489         if err != http.ErrServerClosed {
490                 log.Fatal(err)
491         }
492         if err := <-killed; err != nil {
493                 log.Fatal(err)
494         }
495 }