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
64var bomFuck = []byte{0xef, 0xbb, 0xbf}
65
66func isSVG(data []byte) bool {
67 if bytes.HasPrefix(data, bomFuck) {
68 data = data[3:]
69 }
70 ct := http.DetectContentType(data)
71 if strings.HasPrefix(ct, "text/xml") || strings.HasPrefix(ct, "text/plain") {
72 // this seems suboptimal
73 prefixes := []string{
74 `<svg `,
75 `<!DOCTYPE svg PUBLIC`,
76 `<?xml version="1.0" encoding="UTF-8"?> <svg `,
77 }
78 for _, pre := range prefixes {
79 if bytes.HasPrefix(data, []byte(pre)) {
80 return true
81 }
82 }
83 }
84 return ct == "image/svg+xml"
85}
86
87func imageFromSVG(data []byte) (*image.Image, error) {
88 if bytes.HasPrefix(data, bomFuck) {
89 data = data[3:]
90 }
91 if len(data) > 100000 {
92 return nil, errors.New("my svg is too big")
93 }
94 svg := &image.Image{
95 Data: data,
96 Format: "svg+xml",
97 }
98 return svg, nil
99}
100
101func callshrink(data []byte, params image.Params) (*image.Image, error) {
102 if isSVG(data) {
103 return imageFromSVG(data)
104 }
105 cl, err := rpc.Dial("unix", backendSockname())
106 if err != nil {
107 return nil, err
108 }
109 defer cl.Close()
110 var res ShrinkerResult
111 err = cl.Call("Shrinker.Shrink", &ShrinkerArgs{
112 Buf: data,
113 Params: params,
114 }, &res)
115 if err != nil {
116 return nil, err
117 }
118 return res.Image, nil
119}
120
121func bigshrink(data []byte) (*image.Image, error) {
122 params := image.Params{
123 LimitSize: 14200 * 4200,
124 MaxWidth: 2600,
125 MaxHeight: 2048,
126 MaxSize: 768 * 1024,
127 }
128 return callshrink(data, params)
129}
130
131func shrinkit(data []byte) (*image.Image, error) {
132 params := image.Params{
133 LimitSize: 4200 * 4200,
134 MaxWidth: 2048,
135 MaxHeight: 2048,
136 }
137 return callshrink(data, params)
138}
139
140func orphancheck() {
141 var b [1]byte
142 os.Stdin.Read(b[:])
143 dlog.Printf("backend shutting down")
144 os.Exit(0)
145}
146
147func backendServer() {
148 dlog.Printf("backend server running")
149 closedatabases()
150 go orphancheck()
151 signal.Ignore(syscall.SIGINT)
152 shrinker := new(Shrinker)
153 srv := rpc.NewServer()
154 err := srv.Register(shrinker)
155 if err != nil {
156 elog.Panicf("unable to register shrinker: %s", err)
157 }
158
159 sockname := backendSockname()
160 err = os.Remove(sockname)
161 if err != nil && !os.IsNotExist(err) {
162 elog.Panicf("unable to unlink socket: %s", err)
163 }
164
165 lis, err := net.Listen("unix", sockname)
166 if err != nil {
167 elog.Panicf("unable to register shrinker: %s", err)
168 }
169 err = setLimits()
170 if err != nil {
171 elog.Printf("error setting backend limits: %s", err)
172 }
173 securitizebackend()
174 srv.Accept(lis)
175}
176
177func runBackendServer() {
178 r, w, err := os.Pipe()
179 if err != nil {
180 elog.Panicf("can't pipe: %s", err)
181 }
182 proc := exec.Command(os.Args[0], reexecArgs("backend")...)
183 proc.Stdout = os.Stdout
184 proc.Stderr = os.Stderr
185 proc.Stdin = r
186 err = proc.Start()
187 if err != nil {
188 elog.Panicf("can't exec backend: %s", err)
189 }
190 workinprogress++
191 var mtx sync.Mutex
192 go func() {
193 <-endoftheworld
194 mtx.Lock()
195 defer mtx.Unlock()
196 w.Close()
197 w = nil
198 readyalready <- true
199 }()
200 go func() {
201 err := proc.Wait()
202 mtx.Lock()
203 defer mtx.Unlock()
204 if w != nil {
205 elog.Printf("lost the backend: %s", err)
206 w.Close()
207 }
208 }()
209}