all repos — honk @ 4176f74dbeac47c69224d380629d574f132f777b

my fork of honk

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
138var backendhooks []func()
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	go orphancheck()
150	signal.Ignore(syscall.SIGINT)
151	shrinker := new(Shrinker)
152	srv := rpc.NewServer()
153	err := srv.Register(shrinker)
154	if err != nil {
155		elog.Panicf("unable to register shrinker: %s", err)
156	}
157
158	sockname := backendSockname()
159	err = os.Remove(sockname)
160	if err != nil && !os.IsNotExist(err) {
161		elog.Panicf("unable to unlink socket: %s", err)
162	}
163
164	lis, err := net.Listen("unix", sockname)
165	if err != nil {
166		elog.Panicf("unable to register shrinker: %s", err)
167	}
168	err = setLimits()
169	if err != nil {
170		elog.Printf("error setting backend limits: %s", err)
171	}
172	for _, h := range backendhooks {
173		h()
174	}
175	srv.Accept(lis)
176}
177
178func runBackendServer() {
179	r, w, err := os.Pipe()
180	if err != nil {
181		elog.Panicf("can't pipe: %s", err)
182	}
183	proc := exec.Command(os.Args[0], reexecArgs("backend")...)
184	proc.Stdout = os.Stdout
185	proc.Stderr = os.Stderr
186	proc.Stdin = r
187	err = proc.Start()
188	if err != nil {
189		elog.Panicf("can't exec backend: %s", err)
190	}
191	workinprogress++
192	var mtx sync.Mutex
193	go func() {
194		<-endoftheworld
195		mtx.Lock()
196		defer mtx.Unlock()
197		w.Close()
198		w = nil
199		readyalready <- true
200	}()
201	go func() {
202		proc.Wait()
203		mtx.Lock()
204		defer mtx.Unlock()
205		if w != nil {
206			elog.Printf("lost the backend: %s", err)
207			w.Close()
208		}
209	}()
210}