backend.go (view raw)
1//
2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
3//
4// Permission to use, copy, modify, and distribute this software for any
5// purpose with or without fee is hereby granted, provided that the above
6// copyright notice and this permission notice appear in all copies.
7//
8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
16package main
17
18import (
19 "bytes"
20 "errors"
21 "net"
22 "net/http"
23 "net/rpc"
24 "os"
25 "os/exec"
26 "os/signal"
27 "strings"
28 "sync"
29 "syscall"
30
31 "humungus.tedunangst.com/r/webs/gate"
32 "humungus.tedunangst.com/r/webs/image"
33)
34
35type Shrinker struct {
36}
37
38type ShrinkerArgs struct {
39 Buf []byte
40 Params image.Params
41}
42
43type ShrinkerResult struct {
44 Image *image.Image
45}
46
47var shrinkgate = gate.NewLimiter(4)
48
49func (s *Shrinker) Shrink(args *ShrinkerArgs, res *ShrinkerResult) error {
50 shrinkgate.Start()
51 defer shrinkgate.Finish()
52 img, err := image.Vacuum(bytes.NewReader(args.Buf), args.Params)
53 if err != nil {
54 return err
55 }
56 res.Image = img
57 return nil
58}
59
60func backendSockname() string {
61 return dataDir + "/backend.sock"
62}
63
64func isSVG(data []byte) bool {
65 ct := http.DetectContentType(data)
66 if strings.HasPrefix(ct, "text/xml") {
67 return strings.Index(string(data), "<!DOCTYPE svg PUBLIC") != -1
68 }
69 if strings.HasPrefix(ct, "text/plain") {
70 return bytes.HasPrefix(data, []byte("<svg "))
71 }
72 return ct == "image/svg+xml"
73}
74
75func imageFromSVG(data []byte) (*image.Image, error) {
76 if len(data) > 100000 {
77 return nil, errors.New("my svg is too big")
78 }
79 svg := &image.Image{
80 Data: data,
81 Format: "svg+xml",
82 }
83 return svg, nil
84}
85
86func shrinkit(data []byte) (*image.Image, error) {
87 if isSVG(data) {
88 return imageFromSVG(data)
89 }
90 cl, err := rpc.Dial("unix", backendSockname())
91 if err != nil {
92 return nil, err
93 }
94 defer cl.Close()
95 var res ShrinkerResult
96 err = cl.Call("Shrinker.Shrink", &ShrinkerArgs{
97 Buf: data,
98 Params: image.Params{LimitSize: 4200 * 4200, MaxWidth: 2048, MaxHeight: 2048},
99 }, &res)
100 if err != nil {
101 return nil, err
102 }
103 return res.Image, nil
104}
105
106var backendhooks []func()
107
108func orphancheck() {
109 var b [1]byte
110 os.Stdin.Read(b[:])
111 dlog.Printf("backend shutting down")
112 os.Exit(0)
113}
114
115func backendServer() {
116 dlog.Printf("backend server running")
117 go orphancheck()
118 signal.Ignore(syscall.SIGINT)
119 shrinker := new(Shrinker)
120 srv := rpc.NewServer()
121 err := srv.Register(shrinker)
122 if err != nil {
123 elog.Panicf("unable to register shrinker: %s", err)
124 }
125
126 sockname := backendSockname()
127 err = os.Remove(sockname)
128 if err != nil && !os.IsNotExist(err) {
129 elog.Panicf("unable to unlink socket: %s", err)
130 }
131
132 lis, err := net.Listen("unix", sockname)
133 if err != nil {
134 elog.Panicf("unable to register shrinker: %s", err)
135 }
136 err = setLimits()
137 if err != nil {
138 elog.Printf("error setting backend limits: %s", err)
139 }
140 for _, h := range backendhooks {
141 h()
142 }
143 srv.Accept(lis)
144}
145
146func runBackendServer() {
147 r, w, err := os.Pipe()
148 if err != nil {
149 elog.Panicf("can't pipe: %s", err)
150 }
151 proc := exec.Command(os.Args[0], reexecArgs("backend")...)
152 proc.Stdout = os.Stdout
153 proc.Stderr = os.Stderr
154 proc.Stdin = r
155 err = proc.Start()
156 if err != nil {
157 elog.Panicf("can't exec backend: %s", err)
158 }
159 workinprogress++
160 var mtx sync.Mutex
161 go func() {
162 <-endoftheworld
163 mtx.Lock()
164 defer mtx.Unlock()
165 w.Close()
166 w = nil
167 readyalready <- true
168 }()
169 go func() {
170 proc.Wait()
171 mtx.Lock()
172 defer mtx.Unlock()
173 if w != nil {
174 elog.Printf("lost the backend: %s", err)
175 w.Close()
176 }
177 }()
178}