all repos — honk @ b9c7fb253fe7d89846ba287ec0cafff32139b92a

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		// 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	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	securitizebackend()
173	srv.Accept(lis)
174}
175
176func runBackendServer() {
177	r, w, err := os.Pipe()
178	if err != nil {
179		elog.Panicf("can't pipe: %s", err)
180	}
181	proc := exec.Command(os.Args[0], reexecArgs("backend")...)
182	proc.Stdout = os.Stdout
183	proc.Stderr = os.Stderr
184	proc.Stdin = r
185	err = proc.Start()
186	if err != nil {
187		elog.Panicf("can't exec backend: %s", err)
188	}
189	workinprogress++
190	var mtx sync.Mutex
191	go func() {
192		<-endoftheworld
193		mtx.Lock()
194		defer mtx.Unlock()
195		w.Close()
196		w = nil
197		readyalready <- true
198	}()
199	go func() {
200		err := proc.Wait()
201		mtx.Lock()
202		defer mtx.Unlock()
203		if w != nil {
204			elog.Printf("lost the backend: %s", err)
205			w.Close()
206		}
207	}()
208}