all repos — honk @ a67ca621a77629311266e129be088d5eaec5b7b1

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	"os"
 27	"regexp"
 28	"strings"
 29	"sync"
 30
 31	"humungus.tedunangst.com/r/webs/htfilter"
 32	"humungus.tedunangst.com/r/webs/httpsig"
 33)
 34
 35func reverbolate(userid int64, honks []*Honk) {
 36	filt := htfilter.New()
 37	zilences := getzilences(userid)
 38	for _, h := range honks {
 39		h.What += "ed"
 40		if h.What == "tonked" {
 41			h.What = "honked back"
 42			h.Style = "subtle"
 43		}
 44		if !h.Public {
 45			h.Style += " limited"
 46		}
 47		if h.Whofore == 2 || h.Whofore == 3 {
 48			h.URL = h.XID
 49			if h.What != "bonked" {
 50				h.Noise = mentionize(h.Noise)
 51			}
 52			h.Username, h.Handle = handles(h.Honker)
 53		} else {
 54			_, h.Handle = handles(h.Honker)
 55			h.Username = h.Handle
 56			if len(h.Username) > 20 {
 57				h.Username = h.Username[:20] + ".."
 58			}
 59			if h.URL == "" {
 60				h.URL = h.XID
 61			}
 62		}
 63		if h.Oonker != "" {
 64			_, h.Oondle = handles(h.Oonker)
 65		}
 66		zap := make(map[*Donk]bool)
 67		h.Noise = unpucker(h.Noise)
 68		h.Open = "open"
 69		if badword := unsee(zilences, h.Precis, h.Noise); badword != "" {
 70			if h.Precis == "" {
 71				h.Precis = badword
 72			}
 73			h.Open = ""
 74		} else if h.Precis == "unspecified horror" {
 75			h.Precis = ""
 76		}
 77		h.Precis = unpucker(h.Precis)
 78		h.HTML, _ = filt.String(h.Noise)
 79		emuxifier := func(e string) string {
 80			for _, d := range h.Donks {
 81				if d.Name == e {
 82					zap[d] = true
 83					if d.Local {
 84						return fmt.Sprintf(`<img class="emu" title="%s" src="/d/%s">`, d.Name, d.XID)
 85					}
 86				}
 87			}
 88			return e
 89		}
 90		h.HTML = template.HTML(re_emus.ReplaceAllStringFunc(string(h.HTML), emuxifier))
 91		j := 0
 92		for i := 0; i < len(h.Donks); i++ {
 93			if !zap[h.Donks[i]] {
 94				h.Donks[j] = h.Donks[i]
 95				j++
 96			}
 97		}
 98		h.Donks = h.Donks[:j]
 99	}
100}
101
102func unsee(zilences []*regexp.Regexp, precis string, noise string) string {
103	for _, z := range zilences {
104		if z.MatchString(precis) || z.MatchString(noise) {
105			if precis == "" {
106				w := z.String()
107				return w[6 : len(w)-3]
108			}
109			return precis
110		}
111	}
112	return ""
113}
114
115func osmosis(honks []*Honk, userid int64) []*Honk {
116	zords := getzords(userid)
117	j := 0
118outer:
119	for _, h := range honks {
120		for _, z := range zords {
121			if z.MatchString(h.Precis) || z.MatchString(h.Noise) {
122				continue outer
123			}
124		}
125		honks[j] = h
126		j++
127	}
128	honks = honks[0:j]
129	return honks
130}
131
132func shortxid(xid string) string {
133	idx := strings.LastIndexByte(xid, '/')
134	if idx == -1 {
135		return xid
136	}
137	return xid[idx+1:]
138}
139
140func xfiltrate() string {
141	letters := "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz1234567891234567891234"
142	var b [18]byte
143	rand.Read(b[:])
144	for i, c := range b {
145		b[i] = letters[c&63]
146	}
147	s := string(b[:])
148	return s
149}
150
151var re_hashes = regexp.MustCompile(`(?:^|\W)#[[:alnum:]]+`)
152
153func ontologies(s string) []string {
154	m := re_hashes.FindAllString(s, -1)
155	j := 0
156	for _, h := range m {
157		if h[0] == '&' {
158			continue
159		}
160		if h[0] != '#' {
161			h = h[1:]
162		}
163		m[j] = h
164		j++
165	}
166	return m[:j]
167}
168
169type Mention struct {
170	who   string
171	where string
172}
173
174var re_mentions = regexp.MustCompile(`@[[:alnum:]._-]+@[[:alnum:].-]*[[:alnum:]]`)
175var re_urltions = regexp.MustCompile(`@https://\S+`)
176
177func grapevine(s string) []string {
178	var mentions []string
179	m := re_mentions.FindAllString(s, -1)
180	for i := range m {
181		where := gofish(m[i])
182		if where != "" {
183			mentions = append(mentions, where)
184		}
185	}
186	m = re_urltions.FindAllString(s, -1)
187	for i := range m {
188		mentions = append(mentions, m[i][1:])
189	}
190	return mentions
191}
192
193func bunchofgrapes(s string) []Mention {
194	m := re_mentions.FindAllString(s, -1)
195	var mentions []Mention
196	for i := range m {
197		where := gofish(m[i])
198		if where != "" {
199			mentions = append(mentions, Mention{who: m[i], where: where})
200		}
201	}
202	m = re_urltions.FindAllString(s, -1)
203	for i := range m {
204		mentions = append(mentions, Mention{who: m[i][1:], where: m[i][1:]})
205	}
206	return mentions
207}
208
209type Emu struct {
210	ID   string
211	Name string
212}
213
214var re_link = regexp.MustCompile(`@?https?://[^\s"]+[\w/)]`)
215var re_emus = regexp.MustCompile(`:[[:alnum:]_-]+:`)
216
217func herdofemus(noise string) []Emu {
218	m := re_emus.FindAllString(noise, -1)
219	m = oneofakind(m)
220	var emus []Emu
221	for _, e := range m {
222		fname := e[1 : len(e)-1]
223		_, err := os.Stat("emus/" + fname + ".png")
224		if err != nil {
225			continue
226		}
227		url := fmt.Sprintf("https://%s/emu/%s.png", serverName, fname)
228		emus = append(emus, Emu{ID: url, Name: e})
229	}
230	return emus
231}
232
233var re_memes = regexp.MustCompile("meme: ?([[:alnum:]_.-]+)")
234
235func memetize(honk *Honk) {
236	repl := func(x string) string {
237		name := x[5:]
238		if name[0] == ' ' {
239			name = name[1:]
240		}
241		fd, err := os.Open("memes/" + name)
242		if err != nil {
243			log.Printf("no meme for %s", name)
244			return x
245		}
246		var peek [512]byte
247		n, _ := fd.Read(peek[:])
248		ct := http.DetectContentType(peek[:n])
249		fd.Close()
250
251		url := fmt.Sprintf("https://%s/meme/%s", serverName, name)
252		res, err := stmtSaveFile.Exec("", name, url, ct, 0, "")
253		if err != nil {
254			log.Printf("error saving meme: %s", err)
255			return x
256		}
257		var d Donk
258		d.FileID, _ = res.LastInsertId()
259		d.XID = ""
260		d.Name = name
261		d.Media = ct
262		d.URL = url
263		d.Local = false
264		honk.Donks = append(honk.Donks, &d)
265		return ""
266	}
267	honk.Noise = re_memes.ReplaceAllStringFunc(honk.Noise, repl)
268}
269
270var re_bolder = regexp.MustCompile(`(^|\W)\*\*([\w\s,.!?'-]+)\*\*($|\W)`)
271var re_italicer = regexp.MustCompile(`(^|\W)\*([\w\s,.!?'-]+)\*($|\W)`)
272var re_bigcoder = regexp.MustCompile("```\n?((?s:.*?))\n?```\n?")
273var re_coder = regexp.MustCompile("`([^`]*)`")
274var re_quoter = regexp.MustCompile(`(?m:^&gt; (.*)\n?)`)
275
276func markitzero(s string) string {
277	var bigcodes []string
278	bigsaver := func(code string) string {
279		bigcodes = append(bigcodes, code)
280		return "``````"
281	}
282	s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
283	var lilcodes []string
284	lilsaver := func(code string) string {
285		lilcodes = append(lilcodes, code)
286		return "`x`"
287	}
288	s = re_coder.ReplaceAllStringFunc(s, lilsaver)
289	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
290	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
291	s = re_quoter.ReplaceAllString(s, "<blockquote>$1</blockquote><p>")
292	lilun := func(s string) string {
293		code := lilcodes[0]
294		lilcodes = lilcodes[1:]
295		return code
296	}
297	s = re_coder.ReplaceAllStringFunc(s, lilun)
298	bigun := func(s string) string {
299		code := bigcodes[0]
300		bigcodes = bigcodes[1:]
301		return code
302	}
303	s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
304	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre><p>")
305	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
306	return s
307}
308
309func obfusbreak(s string) string {
310	s = strings.TrimSpace(s)
311	s = strings.Replace(s, "\r", "", -1)
312	s = html.EscapeString(s)
313	// dammit go
314	s = strings.Replace(s, "&#39;", "'", -1)
315	linkfn := func(url string) string {
316		if url[0] == '@' {
317			return url
318		}
319		addparen := false
320		adddot := false
321		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
322			url = url[:len(url)-1]
323			addparen = true
324		}
325		if strings.HasSuffix(url, ".") {
326			url = url[:len(url)-1]
327			adddot = true
328		}
329		url = fmt.Sprintf(`<a class="mention u-url" href="%s">%s</a>`, url, url)
330		if adddot {
331			url += "."
332		}
333		if addparen {
334			url += ")"
335		}
336		return url
337	}
338	s = re_link.ReplaceAllStringFunc(s, linkfn)
339
340	s = markitzero(s)
341
342	s = strings.Replace(s, "\n", "<br>", -1)
343	return s
344}
345
346func mentionize(s string) string {
347	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
348		where := gofish(m)
349		if where == "" {
350			return m
351		}
352		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
353		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
354			html.EscapeString(where), html.EscapeString(who))
355	})
356	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
357		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
358			html.EscapeString(m[1:]), html.EscapeString(m))
359	})
360	return s
361}
362
363var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
364var re_urlhost = regexp.MustCompile("https://([^/]+)")
365
366func originate(u string) string {
367	m := re_urlhost.FindStringSubmatch(u)
368	if len(m) > 1 {
369		return m[1]
370	}
371	return ""
372}
373
374var allhandles = make(map[string]string)
375var handlelock sync.Mutex
376
377// handle, handle@host
378func handles(xid string) (string, string) {
379	handlelock.Lock()
380	handle := allhandles[xid]
381	handlelock.Unlock()
382	if handle == "" {
383		handle = findhandle(xid)
384		handlelock.Lock()
385		allhandles[xid] = handle
386		handlelock.Unlock()
387	}
388	if handle == xid {
389		return xid, xid
390	}
391	return handle, handle + "@" + originate(xid)
392}
393
394func findhandle(xid string) string {
395	row := stmtGetXonker.QueryRow(xid, "handle")
396	var handle string
397	err := row.Scan(&handle)
398	if err != nil {
399		p := investigate(xid)
400		if p == nil {
401			m := re_unurl.FindStringSubmatch(xid)
402			if len(m) > 2 {
403				handle = m[2]
404			} else {
405				handle = xid
406			}
407		} else {
408			handle = p.Handle
409		}
410		_, err = stmtSaveXonker.Exec(xid, handle, "handle")
411		if err != nil {
412			log.Printf("error saving handle: %s", err)
413		}
414	}
415	return handle
416}
417
418func prepend(s string, x []string) []string {
419	return append([]string{s}, x...)
420}
421
422// pleroma leaks followers addressed posts to followers
423func butnottooloud(aud []string) {
424	for i, a := range aud {
425		if strings.HasSuffix(a, "/followers") {
426			aud[i] = ""
427		}
428	}
429}
430
431func keepitquiet(aud []string) bool {
432	for _, a := range aud {
433		if a == thewholeworld {
434			return false
435		}
436	}
437	return true
438}
439
440func oneofakind(a []string) []string {
441	var x []string
442	for n, s := range a {
443		if s != "" {
444			x = append(x, s)
445			for i := n + 1; i < len(a); i++ {
446				if a[i] == s {
447					a[i] = ""
448				}
449			}
450		}
451	}
452	return x
453}
454
455var ziggies = make(map[string]*rsa.PrivateKey)
456var zaggies = make(map[string]*rsa.PublicKey)
457var ziggylock sync.Mutex
458
459func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
460	ziggylock.Lock()
461	key = ziggies[username]
462	ziggylock.Unlock()
463	if key == nil {
464		db := opendatabase()
465		row := db.QueryRow("select seckey from users where username = ?", username)
466		var data string
467		row.Scan(&data)
468		var err error
469		key, _, err = httpsig.DecodeKey(data)
470		if err != nil {
471			log.Printf("error decoding %s seckey: %s", username, err)
472			return
473		}
474		ziggylock.Lock()
475		ziggies[username] = key
476		ziggylock.Unlock()
477	}
478	keyname = fmt.Sprintf("https://%s/%s/%s#key", serverName, userSep, username)
479	return
480}
481
482func zaggy(keyname string) (key *rsa.PublicKey) {
483	ziggylock.Lock()
484	key = zaggies[keyname]
485	ziggylock.Unlock()
486	if key != nil {
487		return
488	}
489	row := stmtGetXonker.QueryRow(keyname, "pubkey")
490	var data string
491	err := row.Scan(&data)
492	if err != nil {
493		log.Printf("hitting the webs for missing pubkey: %s", keyname)
494		j, err := GetJunk(keyname)
495		if err != nil {
496			log.Printf("error getting %s pubkey: %s", keyname, err)
497			return
498		}
499		keyobj, ok := j.GetMap("publicKey")
500		if ok {
501			j = keyobj
502		}
503		data, ok = j.GetString("publicKeyPem")
504		if !ok {
505			log.Printf("error finding %s pubkey", keyname)
506			return
507		}
508		_, ok = j.GetString("owner")
509		if !ok {
510			log.Printf("error finding %s pubkey owner", keyname)
511			return
512		}
513		_, key, err = httpsig.DecodeKey(data)
514		if err != nil {
515			log.Printf("error decoding %s pubkey: %s", keyname, err)
516			return
517		}
518		_, err = stmtSaveXonker.Exec(keyname, data, "pubkey")
519		if err != nil {
520			log.Printf("error saving key: %s", err)
521		}
522	} else {
523		_, key, err = httpsig.DecodeKey(data)
524		if err != nil {
525			log.Printf("error decoding %s pubkey: %s", keyname, err)
526			return
527		}
528	}
529	ziggylock.Lock()
530	zaggies[keyname] = key
531	ziggylock.Unlock()
532	return
533}
534
535func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
536	_, err := stmtDeleteXonker.Exec(keyname, "pubkey")
537	if err != nil {
538		log.Printf("error deleting key: %s", err)
539	}
540	ziggylock.Lock()
541	delete(zaggies, keyname)
542	ziggylock.Unlock()
543	return httpsig.VerifyRequest(r, payload, zaggy)
544}
545
546var thumbbiters map[int64]map[string]bool
547var zordses map[int64][]*regexp.Regexp
548var zilences map[int64][]*regexp.Regexp
549var thumblock sync.Mutex
550
551func bitethethumbs() {
552	rows, err := stmtThumbBiters.Query()
553	if err != nil {
554		log.Printf("error getting thumbbiters: %s", err)
555		return
556	}
557	defer rows.Close()
558
559	thumblock.Lock()
560	defer thumblock.Unlock()
561	thumbbiters = make(map[int64]map[string]bool)
562	zordses = make(map[int64][]*regexp.Regexp)
563	zilences = make(map[int64][]*regexp.Regexp)
564	for rows.Next() {
565		var userid int64
566		var name, wherefore string
567		err = rows.Scan(&userid, &name, &wherefore)
568		if err != nil {
569			log.Printf("error scanning zonker: %s", err)
570			continue
571		}
572		if wherefore == "zord" || wherefore == "zilence" {
573			zord := "\\b(?i:" + name + ")\\b"
574			re, err := regexp.Compile(zord)
575			if err != nil {
576				log.Printf("error compiling zord: %s", err)
577			} else {
578				if wherefore == "zord" {
579					zordses[userid] = append(zordses[userid], re)
580				} else {
581					zilences[userid] = append(zilences[userid], re)
582				}
583			}
584			continue
585		}
586		m := thumbbiters[userid]
587		if m == nil {
588			m = make(map[string]bool)
589			thumbbiters[userid] = m
590		}
591		m[name] = true
592	}
593}
594
595func getzords(userid int64) []*regexp.Regexp {
596	thumblock.Lock()
597	defer thumblock.Unlock()
598	return zordses[userid]
599}
600
601func getzilences(userid int64) []*regexp.Regexp {
602	thumblock.Lock()
603	defer thumblock.Unlock()
604	return zilences[userid]
605}
606
607func thoudostbitethythumb(userid int64, who []string, objid string) bool {
608	thumblock.Lock()
609	biters := thumbbiters[userid]
610	thumblock.Unlock()
611	objwhere := originate(objid)
612	if objwhere != "" && biters[objwhere] {
613		return true
614	}
615	for _, w := range who {
616		if biters[w] {
617			return true
618		}
619		where := originate(w)
620		if where != "" {
621			if biters[where] {
622				return true
623			}
624		}
625	}
626	return false
627}
628
629func keymatch(keyname string, actor string) string {
630	hash := strings.IndexByte(keyname, '#')
631	if hash == -1 {
632		hash = len(keyname)
633	}
634	owner := keyname[0:hash]
635	if owner == actor {
636		return originate(actor)
637	}
638	return ""
639}