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