all repos — honk @ cee91279ee6da9d61f066d2a6e35d32b5c282ec6

my fork of honk

fun.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	"crypto/rand"
 20	"crypto/rsa"
 21	"fmt"
 22	"html"
 23	"html/template"
 24	"log"
 25	"net/http"
 26	"regexp"
 27	"strings"
 28	"sync"
 29)
 30
 31func reverbolate(honks []*Honk) {
 32	for _, h := range honks {
 33		h.What += "ed"
 34		if h.Honker == "" {
 35			h.Honker = "https://" + serverName + "/u/" + h.Username
 36			if strings.IndexByte(h.XID, '/') == -1 {
 37				h.URL = h.Honker + "/h/" + h.XID
 38			} else {
 39				h.URL = h.XID
 40			}
 41			h.Noise = mentionize(h.Noise)
 42		} else {
 43			idx := strings.LastIndexByte(h.Honker, '/')
 44			if idx != -1 {
 45				h.Username = honkerhandle(h.Honker)
 46			} else {
 47				h.Username = h.Honker
 48			}
 49			if h.URL == "" {
 50				h.URL = h.XID
 51			}
 52		}
 53		h.Privacy = "limited"
 54		for _, a := range h.Audience {
 55			if a == thewholeworld {
 56				h.Privacy = ""
 57				break
 58			}
 59		}
 60		zap := make(map[*Donk]bool)
 61		h.Noise = unpucker(h.Noise)
 62		h.HTML = cleanstring(h.Noise)
 63		emuxifier := func(e string) string {
 64			for _, d := range h.Donks {
 65				if d.Name == e {
 66					zap[d] = true
 67					return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
 68				}
 69			}
 70			return e
 71		}
 72		h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
 73		j := 0
 74		for i := 0; i < len(h.Donks); i++ {
 75			if !zap[h.Donks[i]] {
 76				h.Donks[j] = h.Donks[i]
 77				j++
 78			}
 79		}
 80		h.Donks = h.Donks[:j]
 81	}
 82}
 83
 84func xfiltrate() string {
 85	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
 86	for {
 87		var b [18]byte
 88		rand.Read(b[:])
 89		for i, c := range b {
 90			b[i] = letters[c&63]
 91		}
 92		s := string(b[:])
 93		return s
 94	}
 95}
 96
 97type Mention struct {
 98	who   string
 99	where string
100}
101
102var re_mentions = regexp.MustCompile(`@[[:alnum:]]+@[[:alnum:].]+`)
103var re_urltions = regexp.MustCompile(`@https://\S+`)
104
105func grapevine(s string) []string {
106	var mentions []string
107	m := re_mentions.FindAllString(s, -1)
108	for i := range m {
109		where := gofish(m[i])
110		if where != "" {
111			mentions = append(mentions, where)
112		}
113	}
114	m = re_urltions.FindAllString(s, -1)
115	for i := range m {
116		mentions = append(mentions, m[i][1:])
117	}
118	return mentions
119}
120
121func bunchofgrapes(s string) []Mention {
122	m := re_mentions.FindAllString(s, -1)
123	var mentions []Mention
124	for i := range m {
125		where := gofish(m[i])
126		if where != "" {
127			mentions = append(mentions, Mention{who: m[i], where: where})
128		}
129	}
130	m = re_urltions.FindAllString(s, -1)
131	for i := range m {
132		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
133	}
134	return mentions
135}
136
137type Emu struct {
138	ID   string
139	Name string
140}
141
142var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
143var re_emus = regexp.MustCompile(`:[[:alnum:]_]+:`)
144
145func herdofemus(noise string) []Emu {
146	m := re_emus.FindAllString(noise, -1)
147	m = oneofakind(m)
148	var emus []Emu
149	for _, e := range m {
150		fname := e[1 : len(e)-1]
151		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
152		emus = append(emus, Emu{ID: url, Name: e})
153	}
154	return emus
155}
156
157var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?']+)\*\*($|\W)`)
158var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?']+)\*($|\W)`)
159var re_bigcoder = regexp.MustCompile("\n?```\n?((?s:.*?))\n?```\n?")
160var re_coder = regexp.MustCompile("`(.*?)`")
161
162func markitzero(s string) string {
163	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
164	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
165	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre>")
166	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
167	return s
168}
169
170func obfusbreak(s string) string {
171	s = strings.TrimSpace(s)
172	s = strings.Replace(s, "\r", "", -1)
173	s = html.EscapeString(s)
174	// dammit go
175	s = strings.Replace(s, "&#39;", "'", -1)
176	linkfn := func(url string) string {
177		if url[0] == '@' {
178			return url
179		}
180		addparen := false
181		adddot := false
182		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
183			url = url[:len(url)-1]
184			addparen = true
185		}
186		if strings.HasSuffix(url, ".") {
187			url = url[:len(url)-1]
188			adddot = true
189		}
190		url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
191		if adddot {
192			url += "."
193		}
194		if addparen {
195			url += ")"
196		}
197		return url
198	}
199	s = re_link.ReplaceAllStringFunc(s, linkfn)
200
201	s = markitzero(s)
202
203	s = strings.Replace(s, "\n", "<br>", -1)
204	return s
205}
206
207func mentionize(s string) string {
208	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
209		where := gofish(m)
210		if where == "" {
211			return m
212		}
213		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
214		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
215			html.EscapeString(where), html.EscapeString(who))
216	})
217	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
218		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
219			html.EscapeString(m[1:]), html.EscapeString(m))
220	})
221	return s
222}
223
224var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
225
226func honkerhandle(h string) string {
227	m := re_unurl.FindStringSubmatch(h)
228	if len(m) > 2 {
229		return fmt.Sprintf("%s@%s", m[2], m[1])
230	}
231	return h
232}
233
234func prepend(s string, x []string) []string {
235	return append([]string{s}, x...)
236}
237
238// pleroma leaks followers addressed posts to followers
239func butnottooloud(aud []string) {
240	for i, a := range aud {
241		if strings.HasSuffix(a, "/followers") {
242			aud[i] = ""
243		}
244	}
245}
246
247func oneofakind(a []string) []string {
248	var x []string
249	for n, s := range a {
250		if s != "" {
251			x = append(x, s)
252			for i := n + 1; i < len(a); i++ {
253				if a[i] == s {
254					a[i] = ""
255				}
256			}
257		}
258	}
259	return x
260}
261
262var ziggies = make(map[string]*rsa.PrivateKey)
263var zaggies = make(map[string]*rsa.PublicKey)
264var ziggylock sync.Mutex
265
266func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
267	ziggylock.Lock()
268	key = ziggies[username]
269	ziggylock.Unlock()
270	if key == nil {
271		db := opendatabase()
272		row := db.QueryRow("select seckey from users where username = ?", username)
273		var data string
274		row.Scan(&data)
275		var err error
276		key, _, err = pez(data)
277		if err != nil {
278			log.Printf("error decoding %s seckey: %s", username, err)
279			return
280		}
281		ziggylock.Lock()
282		ziggies[username] = key
283		ziggylock.Unlock()
284	}
285	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
286	return
287}
288
289func zaggy(keyname string) (key *rsa.PublicKey) {
290	ziggylock.Lock()
291	key = zaggies[keyname]
292	ziggylock.Unlock()
293	if key != nil {
294		return
295	}
296	db := opendatabase()
297	row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
298	var data string
299	err := row.Scan(&data)
300	if err != nil {
301		log.Printf("hitting the webs for missing pubkey: %s", keyname)
302		j, err := GetJunk(keyname)
303		if err != nil {
304			log.Printf("error getting %s pubkey: %s", keyname, err)
305			return
306		}
307		var ok bool
308		data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
309		if !ok {
310			log.Printf("error finding %s pubkey", keyname)
311			return
312		}
313		_, ok = jsonfindstring(j, []string{"publicKey", "owner"})
314		if !ok {
315			log.Printf("error finding %s pubkey owner", keyname)
316			return
317		}
318		_, key, err = pez(data)
319		if err != nil {
320			log.Printf("error decoding %s pubkey: %s", keyname, err)
321			return
322		}
323		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
324		if err != nil {
325			log.Printf("error saving key: %s", err)
326		}
327	} else {
328		_, key, err = pez(data)
329		if err != nil {
330			log.Printf("error decoding %s pubkey: %s", keyname, err)
331			return
332		}
333	}
334	ziggylock.Lock()
335	zaggies[keyname] = key
336	ziggylock.Unlock()
337	return
338}
339
340func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
341	db := opendatabase()
342	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
343	if err != nil {
344		log.Printf("error deleting key: %s", err)
345	}
346	ziggylock.Lock()
347	delete(zaggies, keyname)
348	ziggylock.Unlock()
349	return zag(r, payload)
350}
351
352var thumbbiters map[int64]map[string]bool
353var thumblock sync.Mutex
354
355func bitethethumbs() {
356	rows, err := stmtThumbBiters.Query()
357	if err != nil {
358		log.Printf("error getting thumbbiters: %s", err)
359		return
360	}
361	defer rows.Close()
362	thumblock.Lock()
363	defer thumblock.Unlock()
364	thumbbiters = make(map[int64]map[string]bool)
365	for rows.Next() {
366		var userid int64
367		var name, wherefore string
368		err = rows.Scan(&userid, &name, &wherefore)
369		if err != nil {
370			log.Printf("error scanning zonker: %s", err)
371			continue
372		}
373		m := thumbbiters[userid]
374		if m == nil {
375			m = make(map[string]bool)
376			thumbbiters[userid] = m
377		}
378		m[name] = true
379	}
380}
381
382func thoudostbitethythumb(userid int64, who []string, objid string) bool {
383	thumblock.Lock()
384	biters := thumbbiters[userid]
385	thumblock.Unlock()
386	for _, w := range who {
387		if biters[w] {
388			return true
389		}
390		m := re_unurl.FindStringSubmatch(w)
391		if len(m) > 2 {
392			where := m[1]
393			if biters[where] {
394				return true
395			}
396		}
397	}
398	return false
399}
400
401func keymatch(keyname string, actor string, what string, userid int64) bool {
402	hash := strings.IndexByte(keyname, '#')
403	if hash == -1 {
404		hash = len(keyname)
405	}
406	owner := keyname[0:hash]
407	if owner == actor {
408		return true
409	}
410	return false
411}