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 callshrink(data []byte, params image.Params) (*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: params,
106 }, &res)
107 if err != nil {
108 return nil, err
109 }
110 return res.Image, nil
111}
112
113func bigshrink(data []byte) (*image.Image, error) {
114 params := image.Params{
115 LimitSize: 14200 * 4200,
116 MaxWidth: 2600,
117 MaxHeight: 2048,
118 MaxSize: 768 * 1024,
119 }
120 return callshrink(data, params)
121}
122
123func shrinkit(data []byte) (*image.Image, error) {
124 params := image.Params{
125 LimitSize: 4200 * 4200,
126 MaxWidth: 2048,
127 MaxHeight: 2048,
128 }
129 return callshrink(data, params)
130}
131
132func orphancheck() {
133 var b [1]byte
134 os.Stdin.Read(b[:])
135 dlog.Printf("backend shutting down")
136 os.Exit(0)
137}
138
139func backendServer() {
140 dlog.Printf("backend server running")
141 go orphancheck()
142 signal.Ignore(syscall.SIGINT)
143 shrinker := new(Shrinker)
144 srv := rpc.NewServer()
145 err := srv.Register(shrinker)
146 if err != nil {
147 elog.Panicf("unable to register shrinker: %s", err)
148 }
149
150 sockname := backendSockname()
151 err = os.Remove(sockname)
152 if err != nil && !os.IsNotExist(err) {
153 elog.Panicf("unable to unlink socket: %s", err)
154 }
155
156 lis, err := net.Listen("unix", sockname)
157 if err != nil {
158 elog.Panicf("unable to register shrinker: %s", err)
159 }
160 err = setLimits()
161 if err != nil {
162 elog.Printf("error setting backend limits: %s", err)
163 }
164 securitizebackend()
165 srv.Accept(lis)
166}
167
168func runBackendServer() {
169 r, w, err := os.Pipe()
170 if err != nil {
171 elog.Panicf("can't pipe: %s", err)
172 }
173 proc := exec.Command(os.Args[0], reexecArgs("backend")...)
174 proc.Stdout = os.Stdout
175 proc.Stderr = os.Stderr
176 proc.Stdin = r
177 err = proc.Start()
178 if err != nil {
179 elog.Panicf("can't exec backend: %s", err)
180 }
181 workinprogress++
182 var mtx sync.Mutex
183 go func() {
184 <-endoftheworld
185 mtx.Lock()
186 defer mtx.Unlock()
187 w.Close()
188 w = nil
189 readyalready <- true
190 }()
191 go func() {
192 proc.Wait()
193 mtx.Lock()
194 defer mtx.Unlock()
195 if w != nil {
196 elog.Printf("lost the backend: %s", err)
197 w.Close()
198 }
199 }()
200}