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