all repos — honk @ 5422207280779349b192adf39879424c6a841940

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?((?s:.*?))\n?```")
160var re_coder = regexp.MustCompile("`([^`]*)`")
161
162func markitzero(s string) string {
163	var bigcodes []string
164	bigsaver := func(code string) string {
165		bigcodes = append(bigcodes, code)
166		return "``````"
167	}
168	s = re_bigcoder.ReplaceAllStringFunc(s, bigsaver)
169	var lilcodes []string
170	lilsaver := func(code string) string {
171		lilcodes = append(lilcodes, code)
172		return "`x`"
173	}
174	s = re_coder.ReplaceAllStringFunc(s, lilsaver)
175	s = re_bolder.ReplaceAllString(s, "$1<b>$2</b>$3")
176	s = re_italicer.ReplaceAllString(s, "$1<i>$2</i>$3")
177	lilun := func(s string) string {
178		code := lilcodes[0]
179		lilcodes = lilcodes[1:]
180		return code
181	}
182	s = re_coder.ReplaceAllStringFunc(s, lilun)
183	bigun := func(s string) string {
184		code := bigcodes[0]
185		bigcodes = bigcodes[1:]
186		return code
187	}
188	s = re_bigcoder.ReplaceAllStringFunc(s, bigun)
189	s = re_bigcoder.ReplaceAllString(s, "<pre><code>$1</code></pre>")
190	s = re_coder.ReplaceAllString(s, "<code>$1</code>")
191	return s
192}
193
194func obfusbreak(s string) string {
195	s = strings.TrimSpace(s)
196	s = strings.Replace(s, "\r", "", -1)
197	s = html.EscapeString(s)
198	// dammit go
199	s = strings.Replace(s, "&#39;", "'", -1)
200	linkfn := func(url string) string {
201		if url[0] == '@' {
202			return url
203		}
204		addparen := false
205		adddot := false
206		if strings.HasSuffix(url, ")") && strings.IndexByte(url, '(') == -1 {
207			url = url[:len(url)-1]
208			addparen = true
209		}
210		if strings.HasSuffix(url, ".") {
211			url = url[:len(url)-1]
212			adddot = true
213		}
214		url = fmt.Sprintf(`<a href="%s">%s</a>`, url, url)
215		if adddot {
216			url += "."
217		}
218		if addparen {
219			url += ")"
220		}
221		return url
222	}
223	s = re_link.ReplaceAllStringFunc(s, linkfn)
224
225	s = markitzero(s)
226
227	s = strings.Replace(s, "\n", "<br>", -1)
228	return s
229}
230
231func mentionize(s string) string {
232	s = re_mentions.ReplaceAllStringFunc(s, func(m string) string {
233		where := gofish(m)
234		if where == "" {
235			return m
236		}
237		who := m[0 : 1+strings.IndexByte(m[1:], '@')]
238		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
239			html.EscapeString(where), html.EscapeString(who))
240	})
241	s = re_urltions.ReplaceAllStringFunc(s, func(m string) string {
242		return fmt.Sprintf(`<span class="h-card"><a class="u-url mention" href="%s">%s</a></span>`,
243			html.EscapeString(m[1:]), html.EscapeString(m))
244	})
245	return s
246}
247
248var re_unurl = regexp.MustCompile("https://([^/]+).*/([^/]+)")
249
250func honkerhandle(h string) string {
251	m := re_unurl.FindStringSubmatch(h)
252	if len(m) > 2 {
253		return fmt.Sprintf("%s@%s", m[2], m[1])
254	}
255	return h
256}
257
258func prepend(s string, x []string) []string {
259	return append([]string{s}, x...)
260}
261
262// pleroma leaks followers addressed posts to followers
263func butnottooloud(aud []string) {
264	for i, a := range aud {
265		if strings.HasSuffix(a, "/followers") {
266			aud[i] = ""
267		}
268	}
269}
270
271func oneofakind(a []string) []string {
272	var x []string
273	for n, s := range a {
274		if s != "" {
275			x = append(x, s)
276			for i := n + 1; i < len(a); i++ {
277				if a[i] == s {
278					a[i] = ""
279				}
280			}
281		}
282	}
283	return x
284}
285
286var ziggies = make(map[string]*rsa.PrivateKey)
287var zaggies = make(map[string]*rsa.PublicKey)
288var ziggylock sync.Mutex
289
290func ziggy(username string) (keyname string, key *rsa.PrivateKey) {
291	ziggylock.Lock()
292	key = ziggies[username]
293	ziggylock.Unlock()
294	if key == nil {
295		db := opendatabase()
296		row := db.QueryRow("select seckey from users where username = ?", username)
297		var data string
298		row.Scan(&data)
299		var err error
300		key, _, err = pez(data)
301		if err != nil {
302			log.Printf("error decoding %s seckey: %s", username, err)
303			return
304		}
305		ziggylock.Lock()
306		ziggies[username] = key
307		ziggylock.Unlock()
308	}
309	keyname = fmt.Sprintf("https://%s/u/%s#key", serverName, username)
310	return
311}
312
313func zaggy(keyname string) (key *rsa.PublicKey) {
314	ziggylock.Lock()
315	key = zaggies[keyname]
316	ziggylock.Unlock()
317	if key != nil {
318		return
319	}
320	db := opendatabase()
321	row := db.QueryRow("select pubkey from xonkers where xid = ?", keyname)
322	var data string
323	err := row.Scan(&data)
324	if err != nil {
325		log.Printf("hitting the webs for missing pubkey: %s", keyname)
326		j, err := GetJunk(keyname)
327		if err != nil {
328			log.Printf("error getting %s pubkey: %s", keyname, err)
329			return
330		}
331		var ok bool
332		data, ok = jsonfindstring(j, []string{"publicKey", "publicKeyPem"})
333		if !ok {
334			log.Printf("error finding %s pubkey", keyname)
335			return
336		}
337		_, ok = jsonfindstring(j, []string{"publicKey", "owner"})
338		if !ok {
339			log.Printf("error finding %s pubkey owner", keyname)
340			return
341		}
342		_, key, err = pez(data)
343		if err != nil {
344			log.Printf("error decoding %s pubkey: %s", keyname, err)
345			return
346		}
347		_, err = stmtSaveBoxes.Exec(keyname, "", "", "", data)
348		if err != nil {
349			log.Printf("error saving key: %s", err)
350		}
351	} else {
352		_, key, err = pez(data)
353		if err != nil {
354			log.Printf("error decoding %s pubkey: %s", keyname, err)
355			return
356		}
357	}
358	ziggylock.Lock()
359	zaggies[keyname] = key
360	ziggylock.Unlock()
361	return
362}
363
364func makeitworksomehowwithoutregardforkeycontinuity(keyname string, r *http.Request, payload []byte) (string, error) {
365	db := opendatabase()
366	_, err := db.Exec("delete from xonkers where xid = ?", keyname)
367	if err != nil {
368		log.Printf("error deleting key: %s", err)
369	}
370	ziggylock.Lock()
371	delete(zaggies, keyname)
372	ziggylock.Unlock()
373	return zag(r, payload)
374}
375
376var thumbbiters map[int64]map[string]bool
377var thumblock sync.Mutex
378
379func bitethethumbs() {
380	rows, err := stmtThumbBiters.Query()
381	if err != nil {
382		log.Printf("error getting thumbbiters: %s", err)
383		return
384	}
385	defer rows.Close()
386	thumblock.Lock()
387	defer thumblock.Unlock()
388	thumbbiters = make(map[int64]map[string]bool)
389	for rows.Next() {
390		var userid int64
391		var name, wherefore string
392		err = rows.Scan(&userid, &name, &wherefore)
393		if err != nil {
394			log.Printf("error scanning zonker: %s", err)
395			continue
396		}
397		m := thumbbiters[userid]
398		if m == nil {
399			m = make(map[string]bool)
400			thumbbiters[userid] = m
401		}
402		m[name] = true
403	}
404}
405
406func thoudostbitethythumb(userid int64, who []string, objid string) bool {
407	thumblock.Lock()
408	biters := thumbbiters[userid]
409	thumblock.Unlock()
410	for _, w := range who {
411		if biters[w] {
412			return true
413		}
414		m := re_unurl.FindStringSubmatch(w)
415		if len(m) > 2 {
416			where := m[1]
417			if biters[where] {
418				return true
419			}
420		}
421	}
422	return false
423}
424
425func keymatch(keyname string, actor string, what string, userid int64) bool {
426	hash := strings.IndexByte(keyname, '#')
427	if hash == -1 {
428		hash = len(keyname)
429	}
430	owner := keyname[0:hash]
431	if owner == actor {
432		return true
433	}
434	return false
435}