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