web.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 "bytes"
20 "context"
21 "crypto/sha512"
22 "database/sql"
23 "errors"
24 "fmt"
25 "html/template"
26 "io"
27 notrand "math/rand"
28 "mime/multipart"
29 "net"
30 "net/http"
31 "net/http/fcgi"
32 "net/url"
33 "os"
34 "os/signal"
35 "path"
36 "path/filepath"
37 "regexp"
38 "runtime/pprof"
39 "sort"
40 "strconv"
41 "strings"
42 "sync"
43 "syscall"
44 "time"
45 "unicode/utf8"
46
47 "github.com/gorilla/handlers"
48 "github.com/gorilla/mux"
49 "humungus.tedunangst.com/r/gonix"
50 "humungus.tedunangst.com/r/webs/gencache"
51 "humungus.tedunangst.com/r/webs/httpsig"
52 "humungus.tedunangst.com/r/webs/junk"
53 "humungus.tedunangst.com/r/webs/login"
54 "humungus.tedunangst.com/r/webs/rss"
55 "humungus.tedunangst.com/r/webs/templates"
56)
57
58var readviews *templates.Template
59
60var userSep = "u"
61var honkSep = "h"
62
63var develMode = false
64
65var allemus []Emu
66
67func getuserstyle(u *login.UserInfo) template.HTMLAttr {
68 if u == nil {
69 return ""
70 }
71 user, _ := butwhatabout(u.Username)
72 class := template.HTMLAttr("")
73 if user.Options.SkinnyCSS {
74 class += `class="skinny"`
75 }
76 return class
77}
78
79func getmaplink(u *login.UserInfo) string {
80 if u == nil {
81 return "osm"
82 }
83 user, _ := butwhatabout(u.Username)
84 ml := user.Options.MapLink
85 if ml == "" {
86 ml = "osm"
87 }
88 return ml
89}
90
91func getInfo(r *http.Request) map[string]interface{} {
92 templinfo := make(map[string]interface{})
93 templinfo["StyleParam"] = getassetparam(viewDir + "/views/style.css")
94 templinfo["LocalStyleParam"] = getassetparam(dataDir + "/views/local.css")
95 templinfo["JSParam"] = getassetparam(viewDir + "/views/honkpage.js")
96 templinfo["MiscJSParam"] = getassetparam(viewDir + "/views/misc.js")
97 templinfo["LocalJSParam"] = getassetparam(dataDir + "/views/local.js")
98 templinfo["ServerName"] = serverName
99 templinfo["IconName"] = iconName
100 templinfo["UserSep"] = userSep
101 if r == nil {
102 return templinfo
103 }
104 if u := login.GetUserInfo(r); u != nil {
105 templinfo["UserInfo"], _ = butwhatabout(u.Username)
106 templinfo["UserStyle"] = getuserstyle(u)
107 combos, _ := combocache.Get(UserID(u.UserID))
108 templinfo["Combos"] = combos
109 }
110 return templinfo
111}
112
113var oldnews = gencache.New(gencache.Options[string, []byte]{
114 Fill: func(url string) ([]byte, bool) {
115 templinfo := getInfo(nil)
116 var honks []*Honk
117 var userid UserID = -1
118
119 templinfo["ServerMessage"] = serverMsg
120 switch url {
121 case "/events":
122 honks = geteventhonks(userid)
123 templinfo["ServerMessage"] = "some recent and upcoming events"
124 default:
125 templinfo["ShowRSS"] = true
126 honks = getpublichonks()
127 }
128 reverbolate(userid, honks)
129 templinfo["Honks"] = honks
130 templinfo["MapLink"] = getmaplink(nil)
131 var buf bytes.Buffer
132 err := readviews.Execute(&buf, "honkpage.html", templinfo)
133 if err != nil {
134 elog.Print(err)
135 }
136 return buf.Bytes(), true
137
138 },
139 Duration: 1 * time.Minute,
140})
141
142func lonelypage(w http.ResponseWriter, r *http.Request) {
143 page, _ := oldnews.Get(r.URL.Path)
144 if !develMode {
145 w.Header().Set("Cache-Control", "max-age=60")
146 }
147 w.Write(page)
148}
149
150func homepage(w http.ResponseWriter, r *http.Request) {
151 u := login.GetUserInfo(r)
152 if u == nil {
153 lonelypage(w, r)
154 return
155 }
156 templinfo := getInfo(r)
157 var honks []*Honk
158 var userid UserID = -1
159
160 templinfo["ServerMessage"] = serverMsg
161 if u == nil || r.URL.Path == "/front" {
162 switch r.URL.Path {
163 case "/events":
164 honks = geteventhonks(userid)
165 templinfo["ServerMessage"] = "some recent and upcoming events"
166 default:
167 templinfo["ShowRSS"] = true
168 honks = getpublichonks()
169 }
170 } else {
171 userid = UserID(u.UserID)
172 switch r.URL.Path {
173 case "/atme":
174 templinfo["ServerMessage"] = "at me!"
175 templinfo["PageName"] = "atme"
176 honks = gethonksforme(userid, 0)
177 honks = osmosis(honks, userid, false)
178 menewnone(userid)
179 templinfo["UserInfo"], _ = butwhatabout(u.Username)
180 case "/longago":
181 templinfo["ServerMessage"] = "long ago and far away!"
182 templinfo["PageName"] = "longago"
183 honks = gethonksfromlongago(userid, 0)
184 honks = osmosis(honks, userid, false)
185 case "/events":
186 templinfo["ServerMessage"] = "some recent and upcoming events"
187 templinfo["PageName"] = "events"
188 honks = geteventhonks(userid)
189 honks = osmosis(honks, userid, true)
190 case "/first":
191 templinfo["PageName"] = "first"
192 honks = gethonksforuserfirstclass(userid, 0)
193 honks = osmosis(honks, userid, true)
194 case "/saved":
195 templinfo["ServerMessage"] = "saved honks"
196 templinfo["PageName"] = "saved"
197 honks = getsavedhonks(userid, 0)
198 default:
199 templinfo["PageName"] = "home"
200 honks = gethonksforuser(userid, 0)
201 honks = osmosis(honks, userid, true)
202 }
203 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
204 }
205
206 honkpage(w, u, honks, templinfo)
207}
208
209func showemus(w http.ResponseWriter, r *http.Request) {
210 templinfo := getInfo(r)
211 templinfo["Emus"] = allemus
212 err := readviews.Execute(w, "emus.html", templinfo)
213 if err != nil {
214 elog.Print(err)
215 }
216}
217
218func showfunzone(w http.ResponseWriter, r *http.Request) {
219 var emunames, memenames []string
220 emuext := make(map[string]string)
221 dir, err := os.Open(dataDir + "/emus")
222 if err == nil {
223 emunames, _ = dir.Readdirnames(0)
224 dir.Close()
225 }
226 for i, e := range emunames {
227 if len(e) > 4 {
228 emunames[i] = e[:len(e)-4]
229 emuext[emunames[i]] = e[len(e)-4:]
230 }
231 }
232 dir, err = os.Open(dataDir + "/memes")
233 if err == nil {
234 memenames, _ = dir.Readdirnames(0)
235 dir.Close()
236 }
237 sort.Strings(emunames)
238 sort.Strings(memenames)
239 templinfo := getInfo(r)
240 templinfo["Emus"] = emunames
241 templinfo["Emuext"] = emuext
242 templinfo["Memes"] = memenames
243 err = readviews.Execute(w, "funzone.html", templinfo)
244 if err != nil {
245 elog.Print(err)
246 }
247}
248
249func showrss(w http.ResponseWriter, r *http.Request) {
250 name := mux.Vars(r)["name"]
251
252 var honks []*Honk
253 if name != "" {
254 honks = gethonksbyuser(name, false, 0)
255 } else {
256 honks = getpublichonks()
257 }
258 reverbolate(-1, honks)
259
260 home := serverURL("/")
261 base := home
262 if name != "" {
263 home += "u/" + name
264 name += " "
265 }
266 feed := rss.Feed{
267 Title: name + "honk",
268 Link: home,
269 Description: name + "honk rss",
270 Image: &rss.Image{
271 URL: base + "icon.png",
272 Title: name + "honk rss",
273 Link: home,
274 },
275 }
276 var modtime time.Time
277 for _, honk := range honks {
278 if !firstclass(honk) {
279 continue
280 }
281 desc := string(honk.HTML)
282 if t := honk.Time; t != nil {
283 desc += fmt.Sprintf(`<p>Time: %s`, t.StartTime.Local().Format("03:04PM MST Mon Jan 02"))
284 if t.Duration != 0 {
285 desc += fmt.Sprintf(`<br>Duration: %s`, t.Duration)
286 }
287 }
288 if p := honk.Place; p != nil {
289 desc += string(templates.Sprintf(`<p>Location: <a href="%s">%s</a> %f %f`,
290 p.Url, p.Name, p.Latitude, p.Longitude))
291 }
292 for _, d := range honk.Donks {
293 desc += string(templates.Sprintf(`<p><a href="%s">Attachment: %s</a>`,
294 d.URL, d.Desc))
295 if strings.HasPrefix(d.Media, "image") {
296 desc += string(templates.Sprintf(`<img src="%s">`, d.URL))
297 }
298 }
299
300 feed.Items = append(feed.Items, &rss.Item{
301 Title: fmt.Sprintf("%s %s %s", honk.Username, honk.What, honk.XID),
302 Description: rss.CData{Data: desc},
303 Link: honk.URL,
304 PubDate: honk.Date.Format(time.RFC1123),
305 Guid: &rss.Guid{IsPermaLink: true, Value: honk.URL},
306 })
307 if honk.Date.After(modtime) {
308 modtime = honk.Date
309 }
310 }
311 if !develMode {
312 w.Header().Set("Cache-Control", "max-age=300")
313 w.Header().Set("Last-Modified", modtime.Format(http.TimeFormat))
314 }
315
316 err := feed.Write(w)
317 if err != nil {
318 elog.Printf("error writing rss: %s", err)
319 }
320}
321
322func crappola(j junk.Junk) bool {
323 t, _ := j.GetString("type")
324 a, _ := j.GetString("actor")
325 o, _ := j.GetString("object")
326 if t == "Delete" && a == o {
327 dlog.Printf("crappola from %s", a)
328 return true
329 }
330 return false
331}
332
333func ping(user *WhatAbout, who string) {
334 if targ := fullname(who, user.ID); targ != "" {
335 who = targ
336 }
337 if !strings.HasPrefix(who, "https://") {
338 who = gofish(who)
339 }
340 if who == "" {
341 ilog.Printf("nobody to ping!")
342 return
343 }
344 box, ok := boxofboxes.Get(who)
345 if !ok {
346 ilog.Printf("no inbox to ping %s", who)
347 return
348 }
349 ilog.Printf("sending ping to %s", box.In)
350 j := junk.New()
351 j["@context"] = itiswhatitis
352 j["type"] = "Ping"
353 j["id"] = user.URL + "/ping/" + xfiltrate()
354 j["actor"] = user.URL
355 j["to"] = who
356 ki := ziggy(user.ID)
357 if ki == nil {
358 return
359 }
360 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
361 if err != nil {
362 elog.Printf("can't send ping: %s", err)
363 return
364 }
365 ilog.Printf("sent ping to %s: %s", who, j["id"])
366}
367
368func pong(user *WhatAbout, who string, obj string) {
369 box, ok := boxofboxes.Get(who)
370 if !ok {
371 ilog.Printf("no inbox to pong %s", who)
372 return
373 }
374 j := junk.New()
375 j["@context"] = itiswhatitis
376 j["type"] = "Pong"
377 j["id"] = user.URL + "/pong/" + xfiltrate()
378 j["actor"] = user.URL
379 j["to"] = who
380 j["object"] = obj
381 ki := ziggy(user.ID)
382 if ki == nil {
383 return
384 }
385 err := PostJunk(ki.keyname, ki.seckey, box.In, j)
386 if err != nil {
387 elog.Printf("can't send pong: %s", err)
388 return
389 }
390}
391
392func inbox(w http.ResponseWriter, r *http.Request) {
393 name := mux.Vars(r)["name"]
394 user, err := butwhatabout(name)
395 if err != nil {
396 http.NotFound(w, r)
397 return
398 }
399 if stealthmode(user.ID, r) {
400 http.NotFound(w, r)
401 return
402 }
403 var buf bytes.Buffer
404 limiter := io.LimitReader(r.Body, 1*1024*1024)
405 io.Copy(&buf, limiter)
406 payload := buf.Bytes()
407 j, err := junk.FromBytes(payload)
408 if err != nil {
409 ilog.Printf("bad payload: %s", err)
410 ilog.Writer().Write(payload)
411 ilog.Writer().Write([]byte{'\n'})
412 return
413 }
414
415 if crappola(j) {
416 return
417 }
418 what := firstofmany(j, "type")
419 obj, _ := j.GetString("object")
420 switch what {
421 case "Like":
422 return
423 case "Dislike":
424 return
425 case "Listen":
426 return
427 case "EmojiReact":
428 if originate(obj) != serverName {
429 return
430 }
431 }
432 who, _ := j.GetString("actor")
433 if rejectactor(user.ID, who) {
434 return
435 }
436
437 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
438 if err != nil && keyname != "" {
439 savingthrow(keyname)
440 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
441 }
442 if err != nil {
443 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
444 if keyname != "" {
445 ilog.Printf("bad signature from %s", keyname)
446 }
447 http.Error(w, "what did you call me?", http.StatusUnauthorized)
448 return
449 }
450 origin := keymatch(keyname, who)
451 if origin == "" {
452 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
453 if what == "Create" {
454 var xid string
455 obj, ok := j.GetMap("object")
456 if ok {
457 xid, _ = obj.GetString("id")
458 } else {
459 xid, _ = j.GetString("object")
460 }
461 if xid != "" {
462 dlog.Printf("getting forwarded create from %s: %s", keyname, xid)
463 go grabhonk(user, xid)
464 }
465 }
466 return
467 }
468
469 switch what {
470 case "Ping":
471 id, _ := j.GetString("id")
472 ilog.Printf("ping from %s: %s", who, id)
473 pong(user, who, id)
474 case "Pong":
475 ilog.Printf("pong from %s: %s", who, obj)
476 case "Follow":
477 if obj != user.URL {
478 ilog.Printf("can't follow %s", obj)
479 return
480 }
481 followme(user, who, who, j)
482 case "Accept":
483 followyou2(user, j)
484 case "Reject":
485 nofollowyou2(user, j)
486 case "Update":
487 obj, ok := j.GetMap("object")
488 if ok {
489 what := firstofmany(obj, "type")
490 switch what {
491 case "Service":
492 fallthrough
493 case "Person":
494 return
495 case "Question":
496 return
497 }
498 }
499 go xonksaver(user, j, origin)
500 case "Undo":
501 obj, ok := j.GetMap("object")
502 if !ok {
503 folxid, ok := j.GetString("object")
504 if ok && originate(folxid) == origin {
505 unfollowme(user, "", "", j)
506 }
507 return
508 }
509 what := firstofmany(obj, "type")
510 switch what {
511 case "Follow":
512 unfollowme(user, who, who, j)
513 case "Announce":
514 xid, _ := obj.GetString("object")
515 dlog.Printf("undo announce: %s", xid)
516 case "Like":
517 default:
518 ilog.Printf("unknown undo: %s", what)
519 }
520 case "EmojiReact":
521 obj, ok := j.GetString("object")
522 if ok {
523 content, _ := j.GetString("content")
524 addreaction(user, obj, who, content)
525 }
526 default:
527 go saveandcheck(user, j, origin)
528 }
529}
530
531func saveandcheck(user *WhatAbout, j junk.Junk, origin string) {
532 xonk := xonksaver(user, j, origin)
533 if xonk == nil {
534 return
535 }
536 if sname := shortname(user.ID, xonk.Honker); sname == "" {
537 dlog.Printf("received unexpected activity from %s", xonk.Honker)
538 if xonk.Whofore == 0 {
539 dlog.Printf("it's not even for me!")
540 }
541 }
542}
543
544func serverinbox(w http.ResponseWriter, r *http.Request) {
545 user := getserveruser()
546 if stealthmode(user.ID, r) {
547 http.NotFound(w, r)
548 return
549 }
550 var buf bytes.Buffer
551 io.Copy(&buf, r.Body)
552 payload := buf.Bytes()
553 j, err := junk.FromBytes(payload)
554 if err != nil {
555 ilog.Printf("bad payload: %s", err)
556 ilog.Writer().Write(payload)
557 ilog.Writer().Write([]byte{'\n'})
558 return
559 }
560 if crappola(j) {
561 return
562 }
563 keyname, err := httpsig.VerifyRequest(r, payload, zaggy)
564 if err != nil && keyname != "" {
565 savingthrow(keyname)
566 keyname, err = httpsig.VerifyRequest(r, payload, zaggy)
567 }
568 if err != nil {
569 ilog.Printf("inbox message failed signature for %s from %s: %s", keyname, r.Header.Get("X-Forwarded-For"), err)
570 if keyname != "" {
571 ilog.Printf("bad signature from %s", keyname)
572 }
573 http.Error(w, "what did you call me?", http.StatusUnauthorized)
574 return
575 }
576 who, _ := j.GetString("actor")
577 origin := keymatch(keyname, who)
578 if origin == "" {
579 ilog.Printf("keyname actor mismatch: %s <> %s", keyname, who)
580 return
581 }
582 if rejectactor(user.ID, who) {
583 return
584 }
585 re_ont := regexp.MustCompile(serverURL("/o") + "/([\\pL[:digit:]]+)")
586 what := firstofmany(j, "type")
587 dlog.Printf("server got a %s", what)
588 switch what {
589 case "Follow":
590 obj, _ := j.GetString("object")
591 if obj == user.URL {
592 ilog.Printf("can't follow the server!")
593 return
594 }
595 m := re_ont.FindStringSubmatch(obj)
596 if len(m) != 2 {
597 ilog.Printf("not sure how to handle this")
598 return
599 }
600 ont := "#" + m[1]
601
602 followme(user, who, ont, j)
603 case "Undo":
604 obj, ok := j.GetMap("object")
605 if !ok {
606 ilog.Printf("unknown undo no object")
607 return
608 }
609 what := firstofmany(obj, "type")
610 if what != "Follow" {
611 ilog.Printf("unknown undo: %s", what)
612 return
613 }
614 targ, _ := obj.GetString("object")
615 m := re_ont.FindStringSubmatch(targ)
616 if len(m) != 2 {
617 ilog.Printf("not sure how to handle this")
618 return
619 }
620 ont := "#" + m[1]
621 unfollowme(user, who, ont, j)
622 default:
623 ilog.Printf("unhandled server activity: %s", what)
624 dumpactivity(j)
625 }
626}
627
628func serveractor(w http.ResponseWriter, r *http.Request) {
629 user := getserveruser()
630 if stealthmode(user.ID, r) {
631 http.NotFound(w, r)
632 return
633 }
634 j := junkuser(user)
635 j.Write(w)
636}
637
638func ximport(w http.ResponseWriter, r *http.Request) {
639 u := login.GetUserInfo(r)
640 xid := strings.TrimSpace(r.FormValue("q"))
641 xonk := getxonk(UserID(u.UserID), xid)
642 if xonk == nil {
643 p, _ := investigate(xid)
644 if p != nil {
645 xid = p.XID
646 }
647 j, err := GetJunk(UserID(u.UserID), xid)
648 if err != nil {
649 http.Error(w, "error getting external object", http.StatusInternalServerError)
650 ilog.Printf("error getting external object: %s", err)
651 return
652 }
653 allinjest(originate(xid), j)
654 dlog.Printf("importing %s", xid)
655 user, _ := butwhatabout(u.Username)
656
657 info, _ := somethingabout(j)
658 if info == nil {
659 xonk = xonksaver(user, j, originate(xid))
660 } else if info.What == SomeActor {
661 outbox, _ := j.GetString("outbox")
662 gimmexonks(user, outbox)
663 http.Redirect(w, r, "/h?xid="+url.QueryEscape(xid), http.StatusSeeOther)
664 return
665 } else if info.What == SomeCollection {
666 gimmexonks(user, xid)
667 http.Redirect(w, r, "/xzone", http.StatusSeeOther)
668 return
669 }
670 }
671 convoy := ""
672 if xonk != nil {
673 convoy = xonk.Convoy
674 }
675 http.Redirect(w, r, "/t?c="+url.QueryEscape(convoy), http.StatusSeeOther)
676}
677
678func xzone(w http.ResponseWriter, r *http.Request) {
679 u := login.GetUserInfo(r)
680 rows, err := stmtRecentHonkers.Query(u.UserID, u.UserID)
681 if err != nil {
682 elog.Printf("query err: %s", err)
683 return
684 }
685 defer rows.Close()
686 var honkers []Honker
687 for rows.Next() {
688 var xid string
689 rows.Scan(&xid)
690 honkers = append(honkers, Honker{XID: xid})
691 }
692 rows.Close()
693 for i := range honkers {
694 _, honkers[i].Handle = handles(honkers[i].XID)
695 }
696 templinfo := getInfo(r)
697 templinfo["XCSRF"] = login.GetCSRF("ximport", r)
698 templinfo["Honkers"] = honkers
699 err = readviews.Execute(w, "xzone.html", templinfo)
700 if err != nil {
701 elog.Print(err)
702 }
703}
704
705var oldoutbox = gencache.New(gencache.Options[string, []byte]{Fill: func(name string) ([]byte, bool) {
706 user, err := butwhatabout(name)
707 if err != nil {
708 return nil, false
709 }
710 honks := gethonksbyuser(name, false, 0)
711 if len(honks) > 20 {
712 honks = honks[0:20]
713 }
714
715 var jonks []junk.Junk
716 for _, h := range honks {
717 j, _ := jonkjonk(user, h)
718 jonks = append(jonks, j)
719 }
720
721 j := junk.New()
722 j["@context"] = itiswhatitis
723 j["id"] = user.URL + "/outbox"
724 j["attributedTo"] = user.URL
725 j["type"] = "OrderedCollection"
726 j["totalItems"] = len(jonks)
727 j["orderedItems"] = jonks
728
729 return j.ToBytes(), true
730}, Duration: 1 * time.Minute})
731
732func outbox(w http.ResponseWriter, r *http.Request) {
733 name := mux.Vars(r)["name"]
734 user, err := butwhatabout(name)
735 if err != nil {
736 http.NotFound(w, r)
737 return
738 }
739 if stealthmode(user.ID, r) {
740 http.NotFound(w, r)
741 return
742 }
743 j, ok := oldoutbox.Get(name)
744 if ok {
745 w.Header().Set("Content-Type", theonetruename)
746 w.Write(j)
747 } else {
748 http.NotFound(w, r)
749 }
750}
751
752var oldempties = gencache.New(gencache.Options[string, []byte]{Fill: func(url string) ([]byte, bool) {
753 colname := "/followers"
754 if strings.HasSuffix(url, "/following") {
755 colname = "/following"
756 }
757 user := serverURL("%s", url[:len(url)-10])
758 j := junk.New()
759 j["@context"] = itiswhatitis
760 j["id"] = user + colname
761 j["attributedTo"] = user
762 j["type"] = "OrderedCollection"
763 j["totalItems"] = 0
764 j["orderedItems"] = []junk.Junk{}
765
766 return j.ToBytes(), true
767}})
768
769func emptiness(w http.ResponseWriter, r *http.Request) {
770 name := mux.Vars(r)["name"]
771 user, err := butwhatabout(name)
772 if err != nil {
773 http.NotFound(w, r)
774 return
775 }
776 if stealthmode(user.ID, r) {
777 http.NotFound(w, r)
778 return
779 }
780 j, ok := oldempties.Get(r.URL.Path)
781 if ok {
782 w.Header().Set("Content-Type", theonetruename)
783 w.Write(j)
784 } else {
785 http.NotFound(w, r)
786 }
787}
788
789func showuser(w http.ResponseWriter, r *http.Request) {
790 name := mux.Vars(r)["name"]
791 user, err := butwhatabout(name)
792 if err != nil {
793 ilog.Printf("user not found %s: %s", name, err)
794 http.NotFound(w, r)
795 return
796 }
797 if stealthmode(user.ID, r) {
798 http.NotFound(w, r)
799 return
800 }
801 wantjson := false
802 if strings.HasSuffix(r.URL.Path, ".json") {
803 wantjson = true
804 }
805 if friendorfoe(r.Header.Get("Accept")) || wantjson {
806 j, ok := asjonker(name)
807 if ok {
808 w.Header().Set("Content-Type", theonetruename)
809 w.Write(j)
810 } else {
811 http.NotFound(w, r)
812 }
813 return
814 }
815 u := login.GetUserInfo(r)
816 if u != nil && u.Username != name {
817 u = nil
818 }
819 honks := gethonksbyuser(name, u != nil, 0)
820 templinfo := getInfo(r)
821 templinfo["PageName"] = "user"
822 templinfo["PageArg"] = name
823 templinfo["Name"] = user.Name
824 templinfo["Honkology"] = oguser(user)
825 templinfo["WhatAbout"] = user.HTAbout
826 templinfo["ServerMessage"] = ""
827 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", user.URL)
828 if u != nil {
829 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
830 }
831 honkpage(w, u, honks, templinfo)
832}
833
834func showhonker(w http.ResponseWriter, r *http.Request) {
835 u := login.GetUserInfo(r)
836 name := mux.Vars(r)["name"]
837 var honks []*Honk
838 if name == "" {
839 name = r.FormValue("xid")
840 honks = gethonksbyxonker(UserID(u.UserID), name, 0)
841 } else {
842 honks = gethonksbyhonker(UserID(u.UserID), name, 0)
843 }
844 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
845<input type="hidden" name="CSRF" value="%s">
846<input type="hidden" name="url" value="%s">
847<button tabindex=1 name="add honker" value="add honker">add honker</button>
848</form>`, login.GetCSRF("submithonker", r), name)
849 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, name, name, miniform)
850 templinfo := getInfo(r)
851 templinfo["PageName"] = "honker"
852 templinfo["PageArg"] = name
853 templinfo["ServerMessage"] = msg
854 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
855 honkpage(w, u, honks, templinfo)
856}
857
858func showcombo(w http.ResponseWriter, r *http.Request) {
859 name := mux.Vars(r)["name"]
860 u := login.GetUserInfo(r)
861 honks := gethonksbycombo(UserID(u.UserID), name, 0)
862 honks = osmosis(honks, UserID(u.UserID), true)
863 templinfo := getInfo(r)
864 templinfo["PageName"] = "combo"
865 templinfo["PageArg"] = name
866 templinfo["ServerMessage"] = "honks by combo: " + name
867 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
868 honkpage(w, u, honks, templinfo)
869}
870func showconvoy(w http.ResponseWriter, r *http.Request) {
871 c := r.FormValue("c")
872 u := login.GetUserInfo(r)
873 honks := gethonksbyconvoy(UserID(u.UserID), c, 0)
874 templinfo := getInfo(r)
875 if len(honks) > 0 {
876 templinfo["TopHID"] = honks[0].ID
877 }
878 honks = osmosis(honks, UserID(u.UserID), false)
879 //reversehonks(honks)
880 honks = threadsort(honks)
881 templinfo["PageName"] = "convoy"
882 templinfo["PageArg"] = c
883 templinfo["ServerMessage"] = "honks in convoy: " + c
884 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
885 honkpage(w, u, honks, templinfo)
886}
887func showsearch(w http.ResponseWriter, r *http.Request) {
888 q := r.FormValue("q")
889 if strings.HasPrefix(q, "https://") {
890 ximport(w, r)
891 return
892 }
893 u := login.GetUserInfo(r)
894 honks := gethonksbysearch(UserID(u.UserID), q, 0)
895 templinfo := getInfo(r)
896 templinfo["PageName"] = "search"
897 templinfo["PageArg"] = q
898 templinfo["ServerMessage"] = "honks for search: " + q
899 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
900 honkpage(w, u, honks, templinfo)
901}
902func showontology(w http.ResponseWriter, r *http.Request) {
903 name := mux.Vars(r)["name"]
904 u := login.GetUserInfo(r)
905 var userid UserID = -1
906 if u != nil {
907 userid = UserID(u.UserID)
908 }
909 honks := gethonksbyontology(userid, "#"+name, 0)
910 if friendorfoe(r.Header.Get("Accept")) {
911 if len(honks) > 40 {
912 honks = honks[0:40]
913 }
914
915 var xids []string
916 for _, h := range honks {
917 xids = append(xids, h.XID)
918 }
919
920 user := getserveruser()
921
922 j := junk.New()
923 j["@context"] = itiswhatitis
924 j["id"] = serverURL("/o/%s", name)
925 j["name"] = "#" + name
926 j["attributedTo"] = user.URL
927 j["type"] = "OrderedCollection"
928 j["totalItems"] = len(xids)
929 j["orderedItems"] = xids
930
931 j.Write(w)
932 return
933 }
934
935 templinfo := getInfo(r)
936 templinfo["ServerMessage"] = "honks by ontology: " + name
937 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
938 honkpage(w, u, honks, templinfo)
939}
940
941type Ont struct {
942 Name string
943 Count int64
944}
945
946func thelistingoftheontologies(w http.ResponseWriter, r *http.Request) {
947 u := login.GetUserInfo(r)
948 var userid UserID = -1
949 if u != nil {
950 userid = UserID(u.UserID)
951 }
952 rows, err := stmtAllOnts.Query(userid)
953 if err != nil {
954 elog.Printf("selection error: %s", err)
955 return
956 }
957 defer rows.Close()
958 var onts, pops []Ont
959 for rows.Next() {
960 var o Ont
961 err := rows.Scan(&o.Name, &o.Count)
962 if err != nil {
963 elog.Printf("error scanning ont: %s", err)
964 continue
965 }
966 if utf8.RuneCountInString(o.Name) > 24 {
967 continue
968 }
969 o.Name = o.Name[1:]
970 onts = append(onts, o)
971 if o.Count > 1 {
972 pops = append(pops, o)
973 }
974 }
975 sort.Slice(onts, func(i, j int) bool {
976 return onts[i].Name < onts[j].Name
977 })
978 sort.Slice(pops, func(i, j int) bool {
979 return pops[i].Count > pops[j].Count
980 })
981 if len(pops) > 40 {
982 pops = pops[:40]
983 }
984 if u == nil && !develMode {
985 w.Header().Set("Cache-Control", "max-age=300")
986 }
987 templinfo := getInfo(r)
988 templinfo["Pops"] = pops
989 templinfo["Onts"] = onts
990 templinfo["FirstRune"] = func(s string) rune { r, _ := utf8.DecodeRuneInString(s); return r }
991 err = readviews.Execute(w, "onts.html", templinfo)
992 if err != nil {
993 elog.Print(err)
994 }
995}
996
997type Track struct {
998 xid string
999 who string
1000}
1001
1002func getbacktracks(xid string) []string {
1003 c := make(chan bool)
1004 dumptracks <- c
1005 <-c
1006 row := stmtGetTracks.QueryRow(xid)
1007 var rawtracks string
1008 err := row.Scan(&rawtracks)
1009 if err != nil {
1010 if err != sql.ErrNoRows {
1011 elog.Printf("error scanning tracks: %s", err)
1012 }
1013 return nil
1014 }
1015 var rcpts []string
1016 for _, f := range strings.Split(rawtracks, " ") {
1017 idx := strings.LastIndexByte(f, '#')
1018 if idx != -1 {
1019 f = f[:idx]
1020 }
1021 if !strings.HasPrefix(f, "https://") {
1022 f = fmt.Sprintf("%%https://%s/inbox", f)
1023 }
1024 rcpts = append(rcpts, f)
1025 }
1026 return rcpts
1027}
1028
1029func savetracks(tracks map[string][]string) {
1030 db := opendatabase()
1031 tx, err := db.Begin()
1032 if err != nil {
1033 elog.Printf("savetracks begin error: %s", err)
1034 return
1035 }
1036 defer func() {
1037 err := tx.Commit()
1038 if err != nil {
1039 elog.Printf("savetracks commit error: %s", err)
1040 }
1041
1042 }()
1043 stmtGetTracks, err := tx.Prepare("select fetches from tracks where xid = ?")
1044 if err != nil {
1045 elog.Printf("savetracks error: %s", err)
1046 return
1047 }
1048 stmtNewTracks, err := tx.Prepare("insert into tracks (xid, fetches) values (?, ?)")
1049 if err != nil {
1050 elog.Printf("savetracks error: %s", err)
1051 return
1052 }
1053 stmtUpdateTracks, err := tx.Prepare("update tracks set fetches = ? where xid = ?")
1054 if err != nil {
1055 elog.Printf("savetracks error: %s", err)
1056 return
1057 }
1058 count := 0
1059 for xid, f := range tracks {
1060 count += len(f)
1061 var prev string
1062 row := stmtGetTracks.QueryRow(xid)
1063 err := row.Scan(&prev)
1064 if err == sql.ErrNoRows {
1065 f = oneofakind(f)
1066 stmtNewTracks.Exec(xid, strings.Join(f, " "))
1067 } else if err == nil {
1068 all := append(strings.Split(prev, " "), f...)
1069 all = oneofakind(all)
1070 stmtUpdateTracks.Exec(strings.Join(all, " "))
1071 } else {
1072 elog.Printf("savetracks error: %s", err)
1073 }
1074 }
1075 dlog.Printf("saved %d new fetches", count)
1076}
1077
1078var trackchan = make(chan Track)
1079var dumptracks = make(chan chan bool)
1080
1081func tracker() {
1082 timeout := 4 * time.Minute
1083 sleeper := time.NewTimer(timeout)
1084 tracks := make(map[string][]string)
1085 workinprogress++
1086 for {
1087 select {
1088 case track := <-trackchan:
1089 tracks[track.xid] = append(tracks[track.xid], track.who)
1090 case <-sleeper.C:
1091 if len(tracks) > 0 {
1092 go savetracks(tracks)
1093 tracks = make(map[string][]string)
1094 }
1095 sleeper.Reset(timeout)
1096 case c := <-dumptracks:
1097 if len(tracks) > 0 {
1098 savetracks(tracks)
1099 }
1100 c <- true
1101 case <-endoftheworld:
1102 if len(tracks) > 0 {
1103 savetracks(tracks)
1104 }
1105 readyalready <- true
1106 return
1107 }
1108 }
1109}
1110
1111var re_keyholder = regexp.MustCompile(`keyId="([^"]+)"`)
1112
1113func requestActor(r *http.Request) string {
1114 if sig := r.Header.Get("Signature"); sig != "" {
1115 if m := re_keyholder.FindStringSubmatch(sig); len(m) == 2 {
1116 return m[1]
1117 }
1118 }
1119 return ""
1120}
1121
1122func trackback(xid string, r *http.Request) {
1123 who := requestActor(r)
1124 if who != "" {
1125 trackchan <- Track{xid: xid, who: who}
1126 }
1127}
1128
1129func sameperson(h1, h2 *Honk) bool {
1130 n1, n2 := h1.Honker, h2.Honker
1131 if h1.Oonker != "" {
1132 n1 = h1.Oonker
1133 }
1134 if h2.Oonker != "" {
1135 n2 = h2.Oonker
1136 }
1137 return n1 == n2
1138}
1139
1140func threadposes(honks []*Honk, wanted int64) ([]*Honk, []int) {
1141 var poses []int
1142 var newhonks []*Honk
1143 for i, honk := range honks {
1144 if honk.ID > wanted {
1145 newhonks = append(newhonks, honk)
1146 poses = append(poses, i)
1147 }
1148 }
1149 return newhonks, poses
1150}
1151
1152func threadsort(honks []*Honk) []*Honk {
1153 sort.Slice(honks, func(i, j int) bool {
1154 return honks[i].Date.Before(honks[j].Date)
1155 })
1156 honkx := make(map[string]*Honk)
1157 kids := make(map[string][]*Honk)
1158 for _, h := range honks {
1159 honkx[h.XID] = h
1160 rid := h.RID
1161 kids[rid] = append(kids[rid], h)
1162 }
1163 done := make(map[*Honk]bool)
1164 var thread []*Honk
1165 var nextlevel func(p *Honk)
1166 level := 0
1167 nextlevel = func(p *Honk) {
1168 levelup := level < 4
1169 if pp := honkx[p.RID]; p.RID == "" || (pp != nil && sameperson(p, pp)) {
1170 levelup = false
1171 }
1172 if level > 0 && len(kids[p.RID]) == 1 {
1173 if pp := honkx[p.RID]; pp != nil && len(kids[pp.RID]) == 1 {
1174 levelup = false
1175 }
1176 }
1177 if levelup {
1178 level++
1179 }
1180 p.Style += fmt.Sprintf(" level%d", level)
1181 childs := kids[p.XID]
1182 if false {
1183 sort.SliceStable(childs, func(i, j int) bool {
1184 return sameperson(childs[i], p) && !sameperson(childs[j], p)
1185 })
1186 }
1187 if true {
1188 sort.SliceStable(childs, func(i, j int) bool {
1189 return !sameperson(childs[i], p) && sameperson(childs[j], p)
1190 })
1191 }
1192 for _, h := range childs {
1193 if !done[h] {
1194 done[h] = true
1195 thread = append(thread, h)
1196 nextlevel(h)
1197 }
1198 }
1199 if levelup {
1200 level--
1201 }
1202 }
1203 for _, h := range honks {
1204 if !done[h] && h.RID == "" {
1205 done[h] = true
1206 thread = append(thread, h)
1207 nextlevel(h)
1208 }
1209 }
1210 for _, h := range honks {
1211 if !done[h] {
1212 done[h] = true
1213 thread = append(thread, h)
1214 nextlevel(h)
1215 }
1216 }
1217 return thread
1218}
1219
1220func oguser(user *WhatAbout) template.HTML {
1221 short := user.About
1222 if len(short) > 160 {
1223 short = short[0:160] + "..."
1224 }
1225 title := user.Display
1226 imgurl := avatarURL(user)
1227 return templates.Sprintf(
1228 `<meta property="og:title" content="%s" />
1229<meta property="og:type" content="website" />
1230<meta property="og:url" content="%s" />
1231<meta property="og:image" content="%s" />
1232<meta property="og:description" content="%s" />`,
1233 title, user.URL, imgurl, short)
1234}
1235
1236func honkology(honk *Honk) template.HTML {
1237 user, ok := somenumberedusers.Get(honk.UserID)
1238 if !ok {
1239 return ""
1240 }
1241 title := fmt.Sprintf("%s: %s", user.Display, honk.Precis)
1242 imgurl := avatarURL(user)
1243 for _, d := range honk.Donks {
1244 if d.Local && strings.HasPrefix(d.Media, "image") {
1245 imgurl = d.URL
1246 break
1247 }
1248 }
1249 short := honk.Noise
1250 if len(short) > 160 {
1251 short = short[0:160] + "..."
1252 }
1253 return templates.Sprintf(
1254 `<meta property="og:title" content="%s" />
1255<meta property="og:type" content="article" />
1256<meta property="article:author" content="%s" />
1257<meta property="og:url" content="%s" />
1258<meta property="og:image" content="%s" />
1259<meta property="og:description" content="%s" />`,
1260 title, user.URL, honk.XID, imgurl, short)
1261}
1262
1263func showonehonk(w http.ResponseWriter, r *http.Request) {
1264 name := mux.Vars(r)["name"]
1265 user, err := butwhatabout(name)
1266 if err != nil {
1267 http.NotFound(w, r)
1268 return
1269 }
1270 if stealthmode(user.ID, r) {
1271 http.NotFound(w, r)
1272 return
1273 }
1274 wantjson := false
1275 path := r.URL.Path
1276 if strings.HasSuffix(path, ".json") {
1277 path = path[:len(path)-5]
1278 wantjson = true
1279 }
1280 xid := serverURL("%s", path)
1281
1282 if friendorfoe(r.Header.Get("Accept")) || wantjson {
1283 j, ok := gimmejonk(xid)
1284 if ok {
1285 trackback(xid, r)
1286 w.Header().Set("Content-Type", theonetruename)
1287 w.Write(j)
1288 } else {
1289 http.NotFound(w, r)
1290 }
1291 return
1292 }
1293 honk := getxonk(user.ID, xid)
1294 if honk == nil {
1295 http.NotFound(w, r)
1296 return
1297 }
1298 u := login.GetUserInfo(r)
1299 if u != nil && UserID(u.UserID) != user.ID {
1300 u = nil
1301 }
1302 if !honk.Public {
1303 if u == nil {
1304 http.NotFound(w, r)
1305 return
1306
1307 }
1308 honks := []*Honk{honk}
1309 donksforhonks(honks)
1310 templinfo := getInfo(r)
1311 templinfo["ServerMessage"] = "one honk maybe more"
1312 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1313 honkpage(w, u, honks, templinfo)
1314 return
1315 }
1316
1317 templinfo := getInfo(r)
1318 rawhonks := gethonksbyconvoy(honk.UserID, honk.Convoy, 0)
1319 //reversehonks(rawhonks)
1320 rawhonks = threadsort(rawhonks)
1321 var honks []*Honk
1322 for i, h := range rawhonks {
1323 if h.XID == xid {
1324 templinfo["Honkology"] = honkology(h)
1325 if i > 0 {
1326 h.Style += " glow"
1327 }
1328 }
1329 if h.Public && (h.Whofore == 2 || h.IsAcked()) {
1330 honks = append(honks, h)
1331 }
1332 }
1333
1334 templinfo["ServerMessage"] = "one honk maybe more"
1335 if u != nil {
1336 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1337 }
1338 templinfo["APAltLink"] = templates.Sprintf("<link href='%s' rel='alternate' type='application/activity+json'>", xid)
1339 honkpage(w, u, honks, templinfo)
1340}
1341
1342func honkpage(w http.ResponseWriter, u *login.UserInfo, honks []*Honk, templinfo map[string]interface{}) {
1343 var userid UserID = -1
1344 if u != nil {
1345 userid = UserID(u.UserID)
1346 templinfo["User"], _ = butwhatabout(u.Username)
1347 }
1348 reverbolate(userid, honks)
1349 templinfo["Honks"] = honks
1350 templinfo["MapLink"] = getmaplink(u)
1351 if templinfo["TopHID"] == nil {
1352 if len(honks) > 0 {
1353 templinfo["TopHID"] = honks[0].ID
1354 } else {
1355 templinfo["TopHID"] = 0
1356 }
1357 }
1358 if u == nil && !develMode {
1359 w.Header().Set("Cache-Control", "max-age=60")
1360 }
1361 err := readviews.Execute(w, "honkpage.html", templinfo)
1362 if err != nil {
1363 elog.Print(err)
1364 }
1365}
1366
1367func saveuser(w http.ResponseWriter, r *http.Request) {
1368 whatabout := r.FormValue("whatabout")
1369 whatabout = strings.Replace(whatabout, "\r", "", -1)
1370 u := login.GetUserInfo(r)
1371 user, _ := butwhatabout(u.Username)
1372 db := opendatabase()
1373
1374 options := user.Options
1375 options.SkinnyCSS = r.FormValue("skinny") == "skinny"
1376 options.OmitImages = r.FormValue("omitimages") == "omitimages"
1377 options.MentionAll = r.FormValue("mentionall") == "mentionall"
1378 options.InlineQuotes = r.FormValue("inlineqts") == "inlineqts"
1379 options.MapLink = r.FormValue("maps")
1380 options.Reaction = r.FormValue("reaction")
1381
1382 sendupdate := false
1383 if r.FormValue("displayname") != "" {
1384 options.CustomDisplay = r.FormValue("displayname")
1385 _, err := db.Exec("update users set displayname = ? where username = ?", options.CustomDisplay, u.Username)
1386 if err != nil {
1387 elog.Printf("error setting displayname: %s", err)
1388 }
1389 sendupdate = true
1390 } else {
1391 options.CustomDisplay = ""
1392 }
1393
1394 options.Reaction = r.FormValue("reaction")
1395
1396 ava := re_avatar.FindString(whatabout)
1397 if ava != "" {
1398 whatabout = re_avatar.ReplaceAllString(whatabout, "")
1399 ava = ava[7:]
1400 if ava[0] == ' ' {
1401 ava = ava[1:]
1402 }
1403 ava = serverURL("/meme/%s", ava)
1404 }
1405 if ava != options.Avatar {
1406 options.Avatar = ava
1407 sendupdate = true
1408 }
1409 ban := re_banner.FindString(whatabout)
1410 if ban != "" {
1411 whatabout = re_banner.ReplaceAllString(whatabout, "")
1412 ban = ban[7:]
1413 if ban[0] == ' ' {
1414 ban = ban[1:]
1415 }
1416 ban = serverURL("/meme/%s", ban)
1417 }
1418 if ban != options.Banner {
1419 options.Banner = ban
1420 sendupdate = true
1421 }
1422 whatabout = strings.TrimSpace(whatabout)
1423 if whatabout != user.About {
1424 sendupdate = true
1425 }
1426 j, err := jsonify(options)
1427 if err == nil {
1428 _, err = db.Exec("update users set about = ?, options = ? where username = ?", whatabout, j, u.Username)
1429 }
1430 if err != nil {
1431 elog.Printf("error bouting what: %s", err)
1432 }
1433 somenamedusers.Clear(u.Username)
1434 somenumberedusers.Clear(user.ID)
1435 oldjonkers.Clear(u.Username)
1436
1437 if sendupdate {
1438 updateMe(u.Username)
1439 }
1440
1441 http.Redirect(w, r, "/account", http.StatusSeeOther)
1442}
1443
1444func bonkit(xid string, user *WhatAbout) {
1445 dlog.Printf("bonking %s", xid)
1446
1447 xonk := getxonk(user.ID, xid)
1448 if xonk == nil {
1449 return
1450 }
1451 if !xonk.Public {
1452 return
1453 }
1454 if xonk.IsBonked() {
1455 return
1456 }
1457 donksforhonks([]*Honk{xonk})
1458
1459 _, err := stmtUpdateFlags.Exec(flagIsBonked, xonk.ID)
1460 if err != nil {
1461 elog.Printf("error acking bonk: %s", err)
1462 }
1463
1464 oonker := xonk.Oonker
1465 if oonker == "" {
1466 oonker = xonk.Honker
1467 }
1468 dt := time.Now().UTC()
1469 bonk := &Honk{
1470 UserID: user.ID,
1471 Username: user.Name,
1472 What: "bonk",
1473 Honker: user.URL,
1474 Oonker: oonker,
1475 XID: xonk.XID,
1476 RID: xonk.RID,
1477 Noise: xonk.Noise,
1478 Precis: xonk.Precis,
1479 URL: xonk.URL,
1480 Date: dt,
1481 Donks: xonk.Donks,
1482 Whofore: 2,
1483 Convoy: xonk.Convoy,
1484 Audience: []string{thewholeworld, oonker},
1485 Public: true,
1486 Format: xonk.Format,
1487 Place: xonk.Place,
1488 Onts: xonk.Onts,
1489 Time: xonk.Time,
1490 }
1491
1492 err = savehonk(bonk)
1493 if err != nil {
1494 elog.Printf("uh oh")
1495 return
1496 }
1497
1498 go honkworldwide(user, bonk)
1499}
1500
1501func submitbonk(w http.ResponseWriter, r *http.Request) {
1502 xid := r.FormValue("xid")
1503 userinfo := login.GetUserInfo(r)
1504 user, _ := butwhatabout(userinfo.Username)
1505
1506 bonkit(xid, user)
1507
1508 if r.FormValue("js") != "1" {
1509 templinfo := getInfo(r)
1510 templinfo["ServerMessage"] = "Bonked!"
1511 err := readviews.Execute(w, "msg.html", templinfo)
1512 if err != nil {
1513 elog.Print(err)
1514 }
1515 }
1516}
1517
1518func sendzonkofsorts(xonk *Honk, user *WhatAbout, what string, aux string) {
1519 zonk := &Honk{
1520 What: what,
1521 XID: xonk.XID,
1522 Date: time.Now().UTC(),
1523 Audience: oneofakind(xonk.Audience),
1524 Noise: aux,
1525 }
1526 zonk.Public = loudandproud(zonk.Audience)
1527
1528 dlog.Printf("announcing %sed honk: %s", what, xonk.XID)
1529 go honkworldwide(user, zonk)
1530}
1531
1532func zonkit(w http.ResponseWriter, r *http.Request) {
1533 wherefore := r.FormValue("wherefore")
1534 what := r.FormValue("what")
1535 u := login.GetUserInfo(r)
1536 user, _ := butwhatabout(u.Username)
1537
1538 if wherefore == "save" {
1539 xonk := getxonk(user.ID, what)
1540 if xonk != nil {
1541 _, err := stmtUpdateFlags.Exec(flagIsSaved, xonk.ID)
1542 if err != nil {
1543 elog.Printf("error saving: %s", err)
1544 }
1545 }
1546 return
1547 }
1548
1549 if wherefore == "unsave" {
1550 xonk := getxonk(user.ID, what)
1551 if xonk != nil {
1552 _, err := stmtClearFlags.Exec(flagIsSaved, xonk.ID)
1553 if err != nil {
1554 elog.Printf("error unsaving: %s", err)
1555 }
1556 }
1557 return
1558 }
1559
1560 if wherefore == "react" {
1561 reaction := user.Options.Reaction
1562 if r2 := r.FormValue("reaction"); r2 != "" {
1563 reaction = r2
1564 }
1565 if reaction == "none" {
1566 return
1567 }
1568 xonk := getxonk(user.ID, what)
1569 if xonk != nil {
1570 _, err := stmtUpdateFlags.Exec(flagIsReacted, xonk.ID)
1571 if err != nil {
1572 elog.Printf("error saving: %s", err)
1573 }
1574 sendzonkofsorts(xonk, user, "react", reaction)
1575 }
1576 return
1577 }
1578
1579 // my hammer is too big, oh well
1580 defer oldjonks.Flush()
1581
1582 if wherefore == "ack" {
1583 xonk := getxonk(user.ID, what)
1584 if xonk != nil && !xonk.IsAcked() {
1585 _, err := stmtUpdateFlags.Exec(flagIsAcked, xonk.ID)
1586 if err != nil {
1587 elog.Printf("error acking: %s", err)
1588 }
1589 sendzonkofsorts(xonk, user, "ack", "")
1590 }
1591 return
1592 }
1593
1594 if wherefore == "deack" {
1595 xonk := getxonk(user.ID, what)
1596 if xonk != nil && xonk.IsAcked() {
1597 _, err := stmtClearFlags.Exec(flagIsAcked, xonk.ID)
1598 if err != nil {
1599 elog.Printf("error deacking: %s", err)
1600 }
1601 sendzonkofsorts(xonk, user, "deack", "")
1602 }
1603 return
1604 }
1605
1606 if wherefore == "bonk" {
1607 bonkit(what, user)
1608 return
1609 }
1610
1611 if wherefore == "unbonk" {
1612 xonk := getbonk(user.ID, what)
1613 if xonk != nil {
1614 deletehonk(xonk.ID)
1615 xonk = getxonk(user.ID, what)
1616 _, err := stmtClearFlags.Exec(flagIsBonked, xonk.ID)
1617 if err != nil {
1618 elog.Printf("error unbonking: %s", err)
1619 }
1620 sendzonkofsorts(xonk, user, "unbonk", "")
1621 }
1622 return
1623 }
1624
1625 if wherefore == "untag" {
1626 xonk := getxonk(user.ID, what)
1627 if xonk != nil {
1628 _, err := stmtUpdateFlags.Exec(flagIsUntagged, xonk.ID)
1629 if err != nil {
1630 elog.Printf("error untagging: %s", err)
1631 }
1632 }
1633 var badparents map[string]bool
1634 untagged.GetAndLock(user.ID, &badparents)
1635 badparents[what] = true
1636 untagged.Unlock()
1637 return
1638 }
1639
1640 ilog.Printf("zonking %s %s", wherefore, what)
1641 if wherefore == "zonk" {
1642 xonk := getxonk(user.ID, what)
1643 if xonk != nil {
1644 deletehonk(xonk.ID)
1645 if xonk.Whofore == 2 || xonk.Whofore == 3 {
1646 sendzonkofsorts(xonk, user, "zonk", "")
1647 }
1648 }
1649 }
1650 _, err := stmtSaveZonker.Exec(user.ID, what, wherefore)
1651 if err != nil {
1652 elog.Printf("error saving zonker: %s", err)
1653 return
1654 }
1655}
1656
1657func edithonkpage(w http.ResponseWriter, r *http.Request) {
1658 u := login.GetUserInfo(r)
1659 user, _ := butwhatabout(u.Username)
1660 xid := r.FormValue("xid")
1661 honk := getxonk(user.ID, xid)
1662 if !canedithonk(user, honk) {
1663 http.Error(w, "no editing that please", http.StatusInternalServerError)
1664 return
1665 }
1666 noise := honk.Noise
1667 var savedfiles []string
1668
1669 honks := []*Honk{honk}
1670 donksforhonks(honks)
1671 for _, d := range honk.Donks {
1672 savedfiles = append(savedfiles, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1673 }
1674 reverbolate(user.ID, honks)
1675
1676 templinfo := getInfo(r)
1677 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1678 templinfo["Honks"] = honks
1679 templinfo["MapLink"] = getmaplink(u)
1680 templinfo["Noise"] = noise
1681 templinfo["SavedPlace"] = honk.Place
1682 if tm := honk.Time; tm != nil {
1683 templinfo["ShowTime"] = " "
1684 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
1685 if tm.Duration != 0 {
1686 templinfo["Duration"] = tm.Duration
1687 }
1688 }
1689 templinfo["Onties"] = honk.Onties
1690 templinfo["SeeAlso"] = honk.SeeAlso
1691 templinfo["Link"] = honk.Link
1692 templinfo["LegalName"] = honk.LegalName
1693 templinfo["ServerMessage"] = "honk edit"
1694 templinfo["IsPreview"] = true
1695 templinfo["UpdateXID"] = honk.XID
1696 if len(savedfiles) > 0 {
1697 templinfo["SavedFile"] = strings.Join(savedfiles, ",")
1698 }
1699 err := readviews.Execute(w, "honkpage.html", templinfo)
1700 if err != nil {
1701 elog.Print(err)
1702 }
1703}
1704
1705func newhonkpage(w http.ResponseWriter, r *http.Request) {
1706 u := login.GetUserInfo(r)
1707 rid := r.FormValue("rid")
1708 noise := ""
1709
1710 xonk := getxonk(UserID(u.UserID), rid)
1711 if xonk != nil {
1712 _, replto := handles(xonk.Honker)
1713 if replto != "" {
1714 noise = "@" + replto + " "
1715 }
1716 }
1717
1718 templinfo := getInfo(r)
1719 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
1720 templinfo["InReplyTo"] = rid
1721 templinfo["Noise"] = noise
1722 templinfo["ServerMessage"] = "compose honk"
1723 templinfo["IsPreview"] = true
1724 err := readviews.Execute(w, "honkpage.html", templinfo)
1725 if err != nil {
1726 elog.Print(err)
1727 }
1728}
1729
1730func canedithonk(user *WhatAbout, honk *Honk) bool {
1731 if honk == nil || honk.Honker != user.URL || honk.What == "bonk" {
1732 return false
1733 }
1734 return true
1735}
1736
1737func submitdonk(w http.ResponseWriter, r *http.Request) ([]*Donk, error) {
1738 if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/form-data") {
1739 return nil, nil
1740 }
1741 var donks []*Donk
1742 for i, hdr := range r.MultipartForm.File["donk"] {
1743 if i > 16 {
1744 break
1745 }
1746 donk, err := formtodonk(w, r, hdr)
1747 if err != nil {
1748 return nil, err
1749 }
1750 donks = append(donks, donk)
1751 }
1752 return donks, nil
1753}
1754
1755func formtodonk(w http.ResponseWriter, r *http.Request, filehdr *multipart.FileHeader) (*Donk, error) {
1756 file, err := filehdr.Open()
1757 if err != nil {
1758 if err == http.ErrMissingFile {
1759 return nil, nil
1760 }
1761 elog.Printf("error reading donk: %s", err)
1762 http.Error(w, "error reading donk", http.StatusUnsupportedMediaType)
1763 return nil, err
1764 }
1765 var buf bytes.Buffer
1766 io.Copy(&buf, file)
1767 file.Close()
1768 data := buf.Bytes()
1769 var media, name string
1770 img, err := bigshrink(data)
1771 if err == nil {
1772 data = img.Data
1773 format := img.Format
1774 media = "image/" + format
1775 if format == "jpeg" {
1776 format = "jpg"
1777 }
1778 if format == "svg+xml" {
1779 format = "svg"
1780 }
1781 name = xfiltrate() + "." + format
1782 } else {
1783 ct := http.DetectContentType(data)
1784 switch ct {
1785 case "application/pdf":
1786 maxsize := 10000000
1787 if len(data) > maxsize {
1788 ilog.Printf("bad image: %s too much pdf: %d", err, len(data))
1789 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1790 return nil, err
1791 }
1792 media = ct
1793 name = filehdr.Filename
1794 if name == "" {
1795 name = xfiltrate() + ".pdf"
1796 }
1797 default:
1798 maxsize := 100000
1799 if len(data) > maxsize {
1800 ilog.Printf("bad image: %s too much text: %d", err, len(data))
1801 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1802 return nil, err
1803 }
1804 for i := 0; i < len(data); i++ {
1805 if data[i] < 32 && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' {
1806 ilog.Printf("bad image: %s not text: %d", err, data[i])
1807 http.Error(w, "didn't like your attachment", http.StatusUnsupportedMediaType)
1808 return nil, err
1809 }
1810 }
1811 media = "text/plain"
1812 name = filehdr.Filename
1813 if name == "" {
1814 name = xfiltrate() + ".txt"
1815 }
1816 }
1817 }
1818 desc := strings.TrimSpace(r.FormValue("donkdesc"))
1819 if desc == "" {
1820 desc = name
1821 }
1822 fileid, xid, err := savefileandxid(name, desc, "", media, true, data)
1823 if err != nil {
1824 elog.Printf("unable to save image: %s", err)
1825 http.Error(w, "failed to save attachment", http.StatusUnsupportedMediaType)
1826 return nil, err
1827 }
1828 d := &Donk{
1829 FileID: fileid,
1830 XID: xid,
1831 Desc: desc,
1832 Local: true,
1833 }
1834 return d, nil
1835}
1836
1837func websubmithonk(w http.ResponseWriter, r *http.Request) {
1838 h := submithonk(w, r)
1839 if h == nil {
1840 return
1841 }
1842 redir := h.XID[len(serverURL("")):]
1843 http.Redirect(w, r, redir, http.StatusSeeOther)
1844}
1845
1846// what a hot mess this function is
1847func submithonk(w http.ResponseWriter, r *http.Request) *Honk {
1848 rid := r.FormValue("rid")
1849 noise := r.FormValue("noise")
1850 format := r.FormValue("format")
1851 if format == "" {
1852 format = "markdown"
1853 }
1854 if !(format == "markdown" || format == "html") {
1855 http.Error(w, "unknown format", 500)
1856 return nil
1857 }
1858
1859 u := login.GetUserInfo(r)
1860 user, _ := butwhatabout(u.Username)
1861
1862 dt := time.Now().UTC()
1863 updatexid := r.FormValue("updatexid")
1864 var honk *Honk
1865 if updatexid != "" {
1866 honk = getxonk(user.ID, updatexid)
1867 if !canedithonk(user, honk) {
1868 http.Error(w, "no editing that please", http.StatusInternalServerError)
1869 return nil
1870 }
1871 honk.Date = dt
1872 honk.What = "update"
1873 honk.Format = format
1874 } else {
1875 xid := fmt.Sprintf("%s/%s/%s", user.URL, honkSep, xfiltrate())
1876 what := "honk"
1877 honk = &Honk{
1878 UserID: user.ID,
1879 Username: user.Name,
1880 What: what,
1881 Honker: user.URL,
1882 XID: xid,
1883 Date: dt,
1884 Format: format,
1885 }
1886 }
1887 honk.SeeAlso = strings.TrimSpace(r.FormValue("seealso"))
1888 honk.Onties = strings.TrimSpace(r.FormValue("onties"))
1889 honk.Link = strings.TrimSpace(r.FormValue("link"))
1890 honk.LegalName = strings.TrimSpace(r.FormValue("legalname"))
1891
1892 var convoy string
1893 noise = strings.Replace(noise, "\r", "", -1)
1894 if updatexid == "" && rid == "" {
1895 noise = re_convoy.ReplaceAllStringFunc(noise, func(m string) string {
1896 convoy = m[7:]
1897 convoy = strings.TrimSpace(convoy)
1898 if !re_convalidate.MatchString(convoy) {
1899 convoy = ""
1900 }
1901 return ""
1902 })
1903 }
1904 noise = quickrename(noise, user.ID)
1905 honk.Noise = noise
1906 precipitate(honk)
1907 noise = honk.Noise
1908 recategorize(honk)
1909 translate(honk)
1910
1911 if rid != "" {
1912 xonk := getxonk(user.ID, rid)
1913 if xonk == nil {
1914 http.Error(w, "replyto disappeared", http.StatusNotFound)
1915 return nil
1916 }
1917 if xonk.Public {
1918 honk.Audience = append(honk.Audience, xonk.Audience...)
1919 }
1920 convoy = xonk.Convoy
1921 for i, a := range honk.Audience {
1922 if a == thewholeworld {
1923 honk.Audience[0], honk.Audience[i] = honk.Audience[i], honk.Audience[0]
1924 break
1925 }
1926 }
1927 honk.RID = rid
1928 if xonk.Precis != "" && honk.Precis == "" {
1929 honk.Precis = xonk.Precis
1930 if !re_dangerous.MatchString(honk.Precis) {
1931 honk.Precis = "re: " + honk.Precis
1932 }
1933 }
1934 } else if updatexid == "" {
1935 honk.Audience = []string{thewholeworld}
1936 }
1937 if noise != "" && noise[0] == '@' {
1938 honk.Audience = append(grapevine(honk.Mentions), honk.Audience...)
1939 } else {
1940 honk.Audience = append(honk.Audience, grapevine(honk.Mentions)...)
1941 }
1942 honk.Convoy = convoy
1943
1944 if convoy == "" {
1945 convoy = fmt.Sprintf("data:,%s-", masqName) + xfiltrate()
1946 }
1947 butnottooloud(honk.Audience)
1948 honk.Audience = oneofakind(honk.Audience)
1949 if len(honk.Audience) == 0 {
1950 ilog.Printf("honk to nowhere")
1951 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1952 return nil
1953 }
1954 honk.Public = loudandproud(honk.Audience)
1955
1956 donkxid := strings.Join(r.Form["donkxid"], ",")
1957 if donkxid == "" {
1958 donks, err := submitdonk(w, r)
1959 if err != nil && err != http.ErrMissingFile {
1960 return nil
1961 }
1962 if len(donks) > 0 {
1963 honk.Donks = append(honk.Donks, donks...)
1964 var xids []string
1965 for _, d := range honk.Donks {
1966 xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1967 }
1968 donkxid = strings.Join(xids, ",")
1969 }
1970 } else {
1971 xids := strings.Split(donkxid, ",")
1972 for i, xid := range xids {
1973 if i > 16 {
1974 break
1975 }
1976 p := strings.Split(xid, ":")
1977 xid = p[0]
1978 url := serverURL("/d/%s", xid)
1979 var donk *Donk
1980 if len(p) > 1 {
1981 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1982 donk = finddonkid(fileid, url)
1983 } else {
1984 donk = finddonk(url)
1985 }
1986 if donk != nil {
1987 honk.Donks = append(honk.Donks, donk)
1988 } else {
1989 ilog.Printf("can't find file: %s", xid)
1990 }
1991 }
1992 }
1993 memetize(honk)
1994 imaginate(honk)
1995
1996 placename := strings.TrimSpace(r.FormValue("placename"))
1997 placelat := strings.TrimSpace(r.FormValue("placelat"))
1998 placelong := strings.TrimSpace(r.FormValue("placelong"))
1999 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
2000 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
2001 p := new(Place)
2002 p.Name = placename
2003 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
2004 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
2005 p.Url = placeurl
2006 honk.Place = p
2007 }
2008 timestart := strings.TrimSpace(r.FormValue("timestart"))
2009 if timestart != "" {
2010 t := new(Time)
2011 now := time.Now().Local()
2012 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
2013 start, err := time.ParseInLocation(layout, timestart, now.Location())
2014 if err == nil {
2015 if start.Year() == 0 {
2016 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
2017 }
2018 t.StartTime = start
2019 break
2020 }
2021 }
2022 timeend := r.FormValue("timeend")
2023 dur := parseDuration(timeend)
2024 if dur != 0 {
2025 t.Duration = Duration(dur)
2026 }
2027 if !t.StartTime.IsZero() {
2028 honk.What = "event"
2029 honk.Time = t
2030 }
2031 }
2032
2033 if honk.Public {
2034 honk.Whofore = 2
2035 } else {
2036 honk.Whofore = 3
2037 }
2038
2039 // back to markdown
2040 honk.Noise = noise
2041
2042 if r.FormValue("preview") == "preview" {
2043 honks := []*Honk{honk}
2044 reverbolate(user.ID, honks)
2045 templinfo := getInfo(r)
2046 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2047 templinfo["Honks"] = honks
2048 templinfo["MapLink"] = getmaplink(u)
2049 templinfo["InReplyTo"] = r.FormValue("rid")
2050 templinfo["Noise"] = r.FormValue("noise")
2051 templinfo["SavedFile"] = donkxid
2052 if tm := honk.Time; tm != nil {
2053 templinfo["ShowTime"] = " "
2054 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
2055 if tm.Duration != 0 {
2056 templinfo["Duration"] = tm.Duration
2057 }
2058 }
2059 templinfo["IsPreview"] = true
2060 templinfo["UpdateXID"] = updatexid
2061 templinfo["ServerMessage"] = "honk preview"
2062 err := readviews.Execute(w, "honkpage.html", templinfo)
2063 if err != nil {
2064 elog.Print(err)
2065 }
2066 return nil
2067 }
2068
2069 if updatexid != "" {
2070 updatehonk(honk)
2071 oldjonks.Clear(honk.XID)
2072 } else {
2073 err := savehonk(honk)
2074 if err != nil {
2075 elog.Printf("uh oh")
2076 return nil
2077 }
2078 }
2079
2080 // reload for consistency
2081 honk.Donks = nil
2082 donksforhonks([]*Honk{honk})
2083
2084 go honkworldwide(user, honk)
2085
2086 return honk
2087}
2088
2089func showhonkers(w http.ResponseWriter, r *http.Request) {
2090 userid := UserID(login.GetUserInfo(r).UserID)
2091 templinfo := getInfo(r)
2092 templinfo["Honkers"] = gethonkers(userid)
2093 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2094 err := readviews.Execute(w, "honkers.html", templinfo)
2095 if err != nil {
2096 elog.Print(err)
2097 }
2098}
2099
2100func showchatter(w http.ResponseWriter, r *http.Request) {
2101 u := login.GetUserInfo(r)
2102 chatnewnone(UserID(u.UserID))
2103 chatter := loadchatter(UserID(u.UserID))
2104 for _, chat := range chatter {
2105 for _, ch := range chat.Chonks {
2106 filterchonk(ch)
2107 }
2108 }
2109
2110 templinfo := getInfo(r)
2111 templinfo["Chatter"] = chatter
2112 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2113 err := readviews.Execute(w, "chatter.html", templinfo)
2114 if err != nil {
2115 elog.Print(err)
2116 }
2117}
2118
2119func submitchonk(w http.ResponseWriter, r *http.Request) {
2120 u := login.GetUserInfo(r)
2121 user, _ := butwhatabout(u.Username)
2122 noise := r.FormValue("noise")
2123 target := r.FormValue("target")
2124 format := "markdown"
2125 dt := time.Now().UTC()
2126 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2127
2128 if !strings.HasPrefix(target, "https://") {
2129 target = fullname(target, user.ID)
2130 }
2131 if target == "" {
2132 http.Error(w, "who is that?", http.StatusInternalServerError)
2133 return
2134 }
2135 ch := Chonk{
2136 UserID: user.ID,
2137 XID: xid,
2138 Who: user.URL,
2139 Target: target,
2140 Date: dt,
2141 Noise: noise,
2142 Format: format,
2143 }
2144 donks, err := submitdonk(w, r)
2145 if err != nil && err != http.ErrMissingFile {
2146 return
2147 }
2148 if len(donks) > 0 {
2149 ch.Donks = append(ch.Donks, donks...)
2150 }
2151
2152 translatechonk(&ch)
2153 savechonk(&ch)
2154 // reload for consistency
2155 ch.Donks = nil
2156 donksforchonks([]*Chonk{&ch})
2157 go sendchonk(user, &ch)
2158
2159 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2160}
2161
2162var combocache = gencache.New(gencache.Options[UserID, []string]{Fill: func(userid UserID) ([]string, bool) {
2163 honkers := gethonkers(userid)
2164 var combos []string
2165 for _, h := range honkers {
2166 combos = append(combos, h.Combos...)
2167 }
2168 for i, c := range combos {
2169 if c == "-" {
2170 combos[i] = ""
2171 }
2172 }
2173 combos = oneofakind(combos)
2174 sort.Strings(combos)
2175 return combos, true
2176}, Invalidator: &honkerinvalidator})
2177
2178func showcombos(w http.ResponseWriter, r *http.Request) {
2179 templinfo := getInfo(r)
2180 err := readviews.Execute(w, "combos.html", templinfo)
2181 if err != nil {
2182 elog.Print(err)
2183 }
2184}
2185
2186func websubmithonker(w http.ResponseWriter, r *http.Request) {
2187 h := submithonker(w, r)
2188 if h == nil {
2189 return
2190 }
2191 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2192}
2193
2194func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2195 u := login.GetUserInfo(r)
2196 user, _ := butwhatabout(u.Username)
2197 name := strings.TrimSpace(r.FormValue("name"))
2198 url := strings.TrimSpace(r.FormValue("url"))
2199 peep := r.FormValue("peep")
2200 combos := strings.TrimSpace(r.FormValue("combos"))
2201 combos = " " + combos + " "
2202 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2203
2204 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2205 if name != "" && !re_namecheck.MatchString(name) {
2206 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2207 return nil
2208 }
2209
2210 var meta HonkerMeta
2211 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2212 mj, _ := jsonify(&meta)
2213
2214 defer honkerinvalidator.Clear(user.ID)
2215
2216 // mostly dummy, fill in later...
2217 h := &Honker{
2218 ID: honkerid,
2219 }
2220
2221 if honkerid > 0 {
2222 if r.FormValue("delete") == "delete" {
2223 unfollowyou(user, honkerid, false)
2224 stmtDeleteHonker.Exec(honkerid)
2225 return h
2226 }
2227 if r.FormValue("unsub") == "unsub" {
2228 unfollowyou(user, honkerid, false)
2229 }
2230 if r.FormValue("sub") == "sub" {
2231 followyou(user, honkerid, false)
2232 }
2233 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, user.ID)
2234 if err != nil {
2235 elog.Printf("update honker err: %s", err)
2236 return nil
2237 }
2238 return h
2239 }
2240
2241 if url == "" {
2242 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2243 return nil
2244 }
2245
2246 flavor := "presub"
2247 if peep == "peep" {
2248 flavor = "peep"
2249 }
2250
2251 var err error
2252 honkerid, flavor, err = savehonker(user, url, name, flavor, combos, mj)
2253 if err != nil {
2254 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2255 return nil
2256 }
2257 if flavor == "presub" {
2258 followyou(user, honkerid, false)
2259 }
2260 h.ID = honkerid
2261 return h
2262}
2263
2264func hfcspage(w http.ResponseWriter, r *http.Request) {
2265 u := login.GetUserInfo(r)
2266
2267 filters := getfilters(UserID(u.UserID), filtAny)
2268
2269 templinfo := getInfo(r)
2270 templinfo["Filters"] = filters
2271 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2272 err := readviews.Execute(w, "hfcs.html", templinfo)
2273 if err != nil {
2274 elog.Print(err)
2275 }
2276}
2277
2278func accountpage(w http.ResponseWriter, r *http.Request) {
2279 u := login.GetUserInfo(r)
2280 user, _ := butwhatabout(u.Username)
2281 templinfo := getInfo(r)
2282 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2283 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2284 templinfo["User"] = user
2285 about := user.About
2286 if ava := user.Options.Avatar; ava != "" {
2287 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2288 }
2289 if ban := user.Options.Banner; ban != "" {
2290 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2291 }
2292 templinfo["WhatAbout"] = about
2293 err := readviews.Execute(w, "account.html", templinfo)
2294 if err != nil {
2295 elog.Print(err)
2296 }
2297}
2298
2299func dochpass(w http.ResponseWriter, r *http.Request) {
2300 err := login.ChangePassword(w, r)
2301 if err != nil {
2302 elog.Printf("error changing password: %s", err)
2303 }
2304 http.Redirect(w, r, "/account", http.StatusSeeOther)
2305}
2306
2307var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2308 if strings.HasPrefix(orig, "acct:") {
2309 orig = orig[5:]
2310 } else {
2311 orig, _ = url.QueryUnescape(orig)
2312 }
2313
2314 name := orig
2315 idx := strings.LastIndexByte(name, '/')
2316 if idx != -1 {
2317 url := fmt.Sprintf("https://%s/%s/%s", serverName, "u", name)
2318 name = name[idx+1:]
2319 if strings.HasPrefix(name, "@") {
2320 url = fmt.Sprintf("https://%s/%s", serverName, name)
2321 name = name[1:]
2322 }
2323 if url != orig {
2324 ilog.Printf("foreign request rejected")
2325 name = ""
2326 }
2327 } else {
2328 idx = strings.IndexByte(name, '@')
2329 if idx != -1 {
2330 name = name[:idx]
2331 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2332 ilog.Printf("foreign request rejected")
2333 name = ""
2334 }
2335 }
2336 }
2337 user, err := butwhatabout(name)
2338 if err != nil {
2339 return nil, false
2340 }
2341
2342 j := junk.New()
2343 pretty := fmt.Sprintf("https://%s/@%s", serverName, name)
2344 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2345 j["aliases"] = []string{pretty, user.URL}
2346 l := junk.New()
2347 l["rel"] = "self"
2348 l["type"] = `application/activity+json`
2349 l["href"] = user.URL
2350 j["links"] = []junk.Junk{l}
2351 l2 := junk.New()
2352 l2["rel"] = "http://webfinger.net/rel/profile-page"
2353 l2["type"] = "text/html"
2354 l2["href"] = pretty
2355 l3 := junk.New()
2356 l3["rel"] = "http://webfinger.net/rel/avatar"
2357
2358 ext := filepath.Ext(user.Options.Avatar)
2359 if ext[1:] == "jpg" {
2360 l3["type"] = "image/jpeg"
2361 } else if ext[1:] == "png" {
2362 l3["type"] = "image/png"
2363 }
2364 l3["href"] = user.Options.Avatar
2365 j["links"] = []junk.Junk{l, l2, l3}
2366
2367 return j.ToBytes(), true
2368}})
2369
2370func fingerlicker(w http.ResponseWriter, r *http.Request) {
2371 orig := r.FormValue("resource")
2372
2373 dlog.Printf("finger lick: %s", orig)
2374
2375 j, ok := oldfingers.Get(orig)
2376 if ok {
2377 w.Header().Set("Content-Type", "application/jrd+json")
2378 w.Write(j)
2379 } else {
2380 http.NotFound(w, r)
2381 }
2382}
2383
2384func knowninformation(w http.ResponseWriter, r *http.Request) {
2385 j := junk.New()
2386 l := junk.New()
2387
2388 l["rel"] = `http://nodeinfo.diaspora.software/ns/schema/2.0`
2389 l["href"] = fmt.Sprintf("https://%s/nodeinfo/2.0", serverName)
2390 j["links"] = []junk.Junk{l}
2391
2392 w.Header().Set("Content-Type", "application/json")
2393 j.Write(w)
2394}
2395
2396func actualinformation(w http.ResponseWriter, r *http.Request) {
2397 j := junk.New()
2398
2399 soft := junk.New()
2400 soft["name"] = "honk"
2401 soft["version"] = softwareVersion
2402
2403 services := junk.New()
2404 services["inbound"] = []string{}
2405 services["outbound"] = []string{"rss2.0"}
2406
2407 users := junk.New()
2408 users["total"] = getusercount()
2409 users["activeHalfyear"] = getactiveusercount(6)
2410 users["activeMonth"] = getactiveusercount(1)
2411
2412 usage := junk.New()
2413 usage["users"] = users
2414 usage["localPosts"] = getlocalhonkcount()
2415
2416 j["version"] = "2.0"
2417 j["protocols"] = []string{"activitypub"}
2418 j["software"] = soft
2419 j["services"] = services
2420 j["openRegistrations"] = false
2421 j["usage"] = usage
2422
2423 w.Header().Set("Content-Type", "application/json")
2424 j.Write(w)
2425}
2426
2427func somedays() string {
2428 secs := 432000 + notrand.Int63n(432000)
2429 return fmt.Sprintf("%d", secs)
2430}
2431
2432func isurl(s string) bool {
2433 u, err := url.Parse(s)
2434 return err == nil && u.Scheme != "" && u.Host != ""
2435}
2436
2437func avatateautogen(r *http.Request) []byte {
2438 n := r.FormValue("a")
2439 return genAvatar(n)
2440}
2441
2442func avatate(w http.ResponseWriter, r *http.Request) {
2443 if develMode {
2444 loadAvatarColors()
2445 }
2446 var a []byte
2447 n := r.FormValue("a")
2448
2449 if isurl(n) {
2450 uinfo := login.GetUserInfo(r)
2451 if uinfo != nil {
2452 j, err := GetJunkFast(UserID(uinfo.UserID), n)
2453 if err != nil {
2454 dlog.Println("avatating: getting junk:", err)
2455 a = avatateautogen(r)
2456 }
2457 pfpurl, _ := j.GetString("icon", "url")
2458 res, err := http.Get(pfpurl)
2459 if err != nil {
2460 dlog.Println("avatating: getting pfp url:", err)
2461 a = avatateautogen(r)
2462 } else {
2463 defer res.Body.Close()
2464
2465 pfpbytes, err := io.ReadAll(res.Body)
2466 if err != nil {
2467 dlog.Println("avatating: bruh shits clapped:", err)
2468 a = avatateautogen(r)
2469 }
2470 a = pfpbytes
2471 }
2472 } else {
2473 a = avatateautogen(r)
2474 }
2475 } else {
2476 a = avatateautogen(r)
2477 }
2478
2479 if !develMode {
2480 w.Header().Set("Cache-Control", "max-age="+somedays())
2481 }
2482
2483 w.Write(a)
2484}
2485
2486func serveviewasset(w http.ResponseWriter, r *http.Request) {
2487 serveasset(w, r, viewDir)
2488}
2489func servedataasset(w http.ResponseWriter, r *http.Request) {
2490 if r.URL.Path == "/favicon.ico" {
2491 r.URL.Path = "/icon.png"
2492 }
2493 serveasset(w, r, dataDir)
2494}
2495
2496func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2497 if !develMode {
2498 w.Header().Set("Cache-Control", "max-age=7776000")
2499 }
2500 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2501}
2502func servehelp(w http.ResponseWriter, r *http.Request) {
2503 name := mux.Vars(r)["name"]
2504 if !develMode {
2505 w.Header().Set("Cache-Control", "max-age=3600")
2506 }
2507 http.ServeFile(w, r, viewDir+"/docs/"+name)
2508}
2509func servehtml(w http.ResponseWriter, r *http.Request) {
2510 u := login.GetUserInfo(r)
2511 templinfo := getInfo(r)
2512 templinfo["AboutMsg"] = aboutMsg
2513 templinfo["LoginMsg"] = loginMsg
2514 templinfo["HonkVersion"] = softwareVersion
2515 if r.URL.Path == "/about" {
2516 templinfo["Sensors"] = getSensors()
2517 }
2518 if u == nil && !develMode {
2519 w.Header().Set("Cache-Control", "max-age=60")
2520 }
2521 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2522 if err != nil {
2523 elog.Print(err)
2524 }
2525}
2526func serveemu(w http.ResponseWriter, r *http.Request) {
2527 emu := mux.Vars(r)["emu"]
2528
2529 w.Header().Set("Cache-Control", "max-age="+somedays())
2530 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2531}
2532func servememe(w http.ResponseWriter, r *http.Request) {
2533 meme := mux.Vars(r)["meme"]
2534
2535 w.Header().Set("Cache-Control", "max-age="+somedays())
2536 _, err := os.Stat(dataDir + "/memes/" + meme)
2537 if err == nil {
2538 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2539 } else {
2540 mux.Vars(r)["xid"] = meme
2541 servefile(w, r)
2542 }
2543}
2544
2545func servefile(w http.ResponseWriter, r *http.Request) {
2546 if friendorfoe(r.Header.Get("Accept")) {
2547 dlog.Printf("incompatible accept for donk")
2548 http.Error(w, "there are no activities here", http.StatusNotAcceptable)
2549 return
2550 }
2551 xid := mux.Vars(r)["xid"]
2552 preview := r.FormValue("preview") == "1"
2553 var media string
2554 var data []byte
2555 row := stmtGetFileData.QueryRow(xid)
2556 err := row.Scan(&media, &data)
2557 if err != nil {
2558 elog.Printf("error loading file: %s", err)
2559 http.NotFound(w, r)
2560 return
2561 }
2562 if preview && strings.HasPrefix(media, "image") {
2563 img, err := lilshrink(data)
2564 if err == nil {
2565 data = img.Data
2566 }
2567 }
2568 w.Header().Set("Content-Type", media)
2569 w.Header().Set("X-Content-Type-Options", "nosniff")
2570 w.Header().Set("Cache-Control", "max-age="+somedays())
2571 w.Write(data)
2572}
2573
2574func nomoroboto(w http.ResponseWriter, r *http.Request) {
2575 io.WriteString(w, "User-agent: *\n")
2576 io.WriteString(w, "Disallow: /a\n")
2577 io.WriteString(w, "Disallow: /d/\n")
2578 io.WriteString(w, "Disallow: /meme/\n")
2579 io.WriteString(w, "Disallow: /o\n")
2580 io.WriteString(w, "Disallow: /o/\n")
2581 io.WriteString(w, "Disallow: /help/\n")
2582 for _, u := range allusers() {
2583 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2584 }
2585}
2586
2587type Hydration struct {
2588 Tophid int64
2589 Srvmsg template.HTML
2590 Honks string
2591 MeCount int64
2592 ChatCount int64
2593 Poses []int
2594}
2595
2596func webhydra(w http.ResponseWriter, r *http.Request) {
2597 u := login.GetUserInfo(r)
2598 userid := UserID(u.UserID)
2599 templinfo := getInfo(r)
2600 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2601 page := r.FormValue("page")
2602
2603 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2604
2605 var hydra Hydration
2606
2607 var honks []*Honk
2608 switch page {
2609 case "atme":
2610 honks = gethonksforme(userid, wanted)
2611 honks = osmosis(honks, userid, false)
2612 menewnone(userid)
2613 hydra.Srvmsg = "at me!"
2614 case "longago":
2615 honks = gethonksfromlongago(userid, wanted)
2616 honks = osmosis(honks, userid, false)
2617 hydra.Srvmsg = "from long ago"
2618 case "home":
2619 honks = gethonksforuser(userid, wanted)
2620 honks = osmosis(honks, userid, true)
2621 hydra.Srvmsg = serverMsg
2622 case "first":
2623 honks = gethonksforuserfirstclass(userid, wanted)
2624 honks = osmosis(honks, userid, true)
2625 hydra.Srvmsg = "first class only"
2626 case "saved":
2627 honks = getsavedhonks(userid, wanted)
2628 templinfo["PageName"] = "saved"
2629 hydra.Srvmsg = "saved honks"
2630 case "combo":
2631 c := r.FormValue("c")
2632 honks = gethonksbycombo(userid, c, wanted)
2633 honks = osmosis(honks, userid, false)
2634 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2635 case "convoy":
2636 c := r.FormValue("c")
2637 honks = gethonksbyconvoy(userid, c, 0)
2638 honks = osmosis(honks, userid, false)
2639 honks = threadsort(honks)
2640 honks, hydra.Poses = threadposes(honks, wanted)
2641 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2642 case "honker":
2643 xid := r.FormValue("xid")
2644 honks = gethonksbyxonker(userid, xid, wanted)
2645 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2646 <input type="hidden" name="CSRF" value="%s">
2647 <input type="hidden" name="url" value="%s">
2648 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2649 </form>`, login.GetCSRF("submithonker", r), xid)
2650 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2651 hydra.Srvmsg = msg
2652 case "user":
2653 uname := r.FormValue("uname")
2654 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2655 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2656 default:
2657 http.NotFound(w, r)
2658 }
2659
2660 if len(honks) > 0 {
2661 if page == "convoy" {
2662 hydra.Tophid = honks[len(honks)-1].ID
2663 } else {
2664 hydra.Tophid = honks[0].ID
2665 }
2666 } else {
2667 hydra.Tophid = wanted
2668 }
2669 reverbolate(userid, honks)
2670
2671 user, _ := butwhatabout(u.Username)
2672
2673 var buf strings.Builder
2674 templinfo["Honks"] = honks
2675 templinfo["MapLink"] = getmaplink(u)
2676 templinfo["User"], _ = butwhatabout(u.Username)
2677 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2678 if err != nil {
2679 elog.Printf("frag error: %s", err)
2680 return
2681 }
2682 hydra.Honks = buf.String()
2683 hydra.MeCount = user.Options.MeCount
2684 hydra.ChatCount = user.Options.ChatCount
2685 w.Header().Set("Content-Type", "application/json")
2686 j, _ := jsonify(&hydra)
2687 io.WriteString(w, j)
2688}
2689
2690var honkline = make(chan bool)
2691
2692func honkhonkline() {
2693 for {
2694 select {
2695 case honkline <- true:
2696 default:
2697 return
2698 }
2699 }
2700}
2701
2702func apihandler(w http.ResponseWriter, r *http.Request) {
2703 u := login.GetUserInfo(r)
2704 userid := UserID(u.UserID)
2705 action := r.FormValue("action")
2706 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2707 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2708 switch action {
2709 case "honk":
2710 h := submithonk(w, r)
2711 if h == nil {
2712 return
2713 }
2714
2715 fmt.Fprintf(w, "%s", h.XID)
2716 case "donk":
2717 donks, err := submitdonk(w, r)
2718 if err != nil {
2719 http.Error(w, err.Error(), http.StatusBadRequest)
2720 return
2721 }
2722 if len(donks) == 0 {
2723 http.Error(w, "missing donk", http.StatusBadRequest)
2724 return
2725 }
2726 d := donks[0]
2727 donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2728 w.Write([]byte(donkxid))
2729 case "zonkit":
2730 zonkit(w, r)
2731 case "gethonks":
2732 var honks []*Honk
2733 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2734 page := r.FormValue("page")
2735 var waitchan <-chan time.Time
2736 requery:
2737 switch page {
2738 case "atme":
2739 honks = gethonksforme(userid, wanted)
2740 honks = osmosis(honks, userid, false)
2741 menewnone(userid)
2742 case "longago":
2743 honks = gethonksfromlongago(userid, wanted)
2744 honks = osmosis(honks, userid, false)
2745 case "home":
2746 honks = gethonksforuser(userid, wanted)
2747 honks = osmosis(honks, userid, true)
2748 case "myhonks":
2749 honks = gethonksbyuser(u.Username, true, wanted)
2750 honks = osmosis(honks, userid, true)
2751 case "saved":
2752 honks = getsavedhonks(userid, wanted)
2753 case "combo":
2754 c := r.FormValue("c")
2755 honks = gethonksbycombo(userid, c, wanted)
2756 honks = osmosis(honks, userid, false)
2757 case "convoy":
2758 c := r.FormValue("c")
2759 honks = gethonksbyconvoy(userid, c, 0)
2760 honks = osmosis(honks, userid, false)
2761 honks = threadsort(honks)
2762 honks, _ = threadposes(honks, wanted)
2763 case "honker":
2764 xid := r.FormValue("xid")
2765 honks = gethonksbyxonker(userid, xid, wanted)
2766 case "search":
2767 q := r.FormValue("q")
2768 honks = gethonksbysearch(userid, q, wanted)
2769 default:
2770 http.Error(w, "unknown page", http.StatusNotFound)
2771 return
2772 }
2773 if len(honks) == 0 && wait > 0 {
2774 if waitchan == nil {
2775 waitchan = time.After(time.Duration(wait) * time.Second)
2776 }
2777 select {
2778 case <-honkline:
2779 goto requery
2780 case <-waitchan:
2781 }
2782 }
2783 reverbolate(userid, honks)
2784 user, _ := butwhatabout(u.Username)
2785 j := junk.New()
2786 j["honks"] = honks
2787 j["mecount"] = user.Options.MeCount
2788 j["chatcount"] = user.Options.ChatCount
2789 j.Write(w)
2790 case "sendactivity":
2791 public := r.FormValue("public") == "1"
2792 user, _ := butwhatabout(u.Username)
2793 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2794 msg := []byte(r.FormValue("msg"))
2795 for rcpt := range rcpts {
2796 go deliverate(userid, rcpt, msg)
2797 }
2798 case "gethonkers":
2799 j := junk.New()
2800 j["honkers"] = gethonkers(userid)
2801 j.Write(w)
2802 case "savehonker":
2803 h := submithonker(w, r)
2804 if h == nil {
2805 return
2806 }
2807 fmt.Fprintf(w, "%d", h.ID)
2808 default:
2809 http.Error(w, "unknown action", http.StatusNotFound)
2810 return
2811 }
2812}
2813
2814func fiveoh(w http.ResponseWriter, r *http.Request) {
2815 if !develMode {
2816 return
2817 }
2818 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2819 if err != nil {
2820 elog.Printf("error opening violations! %s", err)
2821 return
2822 }
2823 defer fd.Close()
2824 io.Copy(fd, r.Body)
2825 fd.WriteString("\n")
2826}
2827
2828var endoftheworld = make(chan bool)
2829var readyalready = make(chan bool)
2830var workinprogress = 0
2831var requestWG sync.WaitGroup
2832var listenSocket net.Listener
2833
2834func enditall() {
2835 sig := make(chan os.Signal, 1)
2836 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2837 <-sig
2838 ilog.Printf("stopping...")
2839 listenSocket.Close()
2840 for i := 0; i < workinprogress; i++ {
2841 endoftheworld <- true
2842 }
2843 if *cpuprofile != "" {
2844 pprof.StopCPUProfile()
2845 }
2846 if *memprofile != "" {
2847 pprof.WriteHeapProfile(memprofilefd)
2848 memprofilefd.Close()
2849 }
2850 ilog.Printf("waiting...")
2851 go func() {
2852 time.Sleep(10 * time.Second)
2853 elog.Printf("timed out waiting for requests to finish")
2854 os.Exit(0)
2855 }()
2856 for i := 0; i < workinprogress; i++ {
2857 <-readyalready
2858 }
2859 requestWG.Wait()
2860 ilog.Printf("apocalypse")
2861 closedatabases()
2862 os.Exit(0)
2863}
2864
2865func bgmonitor() {
2866 for {
2867 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2868 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2869 if err != nil {
2870 elog.Printf("error deleting old xonkers: %s", err)
2871 }
2872 zaggies.Flush()
2873 time.Sleep(50 * time.Minute)
2874 }
2875}
2876
2877func addcspheaders(next http.Handler) http.Handler {
2878 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2879 requestWG.Add(1)
2880 defer requestWG.Done()
2881 policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2882 if develMode {
2883 policy += "; report-uri /csp-violation"
2884 }
2885 w.Header().Set("Content-Security-Policy", policy)
2886 next.ServeHTTP(w, r)
2887 })
2888}
2889
2890func emuinit() {
2891 var emunames []string
2892 dir, err := os.Open(dataDir + "/emus")
2893 if err == nil {
2894 emunames, _ = dir.Readdirnames(0)
2895 dir.Close()
2896 }
2897 for _, e := range emunames {
2898 if len(e) <= 4 {
2899 continue
2900 }
2901 ext := e[len(e)-4:]
2902 emu := Emu{
2903 ID: fmt.Sprintf("/emu/%s", e),
2904 Name: e[:len(e)-4],
2905 Type: "image/" + ext[1:],
2906 }
2907 allemus = append(allemus, emu)
2908 }
2909 sort.Slice(allemus, func(i, j int) bool {
2910 return allemus[i].Name < allemus[j].Name
2911 })
2912}
2913
2914func redirectPretty(w http.ResponseWriter, r *http.Request) {
2915 last := path.Base(r.URL.Path)
2916 name := mux.Vars(r)["name"]
2917 aturl := "/@" + name
2918
2919 if last == name {
2920 last = ""
2921 }
2922 http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2923}
2924
2925var savedassetparams = make(map[string]string)
2926
2927func getassetparam(file string) string {
2928 if p, ok := savedassetparams[file]; ok {
2929 return p
2930 }
2931 data, err := os.ReadFile(file)
2932 if err != nil {
2933 return ""
2934 }
2935 hasher := sha512.New()
2936 hasher.Write(data)
2937
2938 return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2939}
2940
2941func startWatcher() {
2942 watcher, err := gonix.NewWatcher()
2943 if err != nil {
2944 return
2945 }
2946 go func() {
2947 s := dataDir + "/views/local.css"
2948 for {
2949 err := watcher.WatchFile(s)
2950 if err != nil {
2951 break
2952 }
2953 err = watcher.WaitForChange()
2954 if err != nil {
2955 dlog.Printf("can't wait: %s", err)
2956 break
2957 }
2958 dlog.Printf("local.css changed")
2959 delete(savedassetparams, s)
2960 savedassetparams[s] = getassetparam(s)
2961 }
2962 }()
2963}
2964
2965var usefcgi bool
2966
2967func serve() {
2968 db := opendatabase()
2969 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2970
2971 listener, err := openListener()
2972 if err != nil {
2973 elog.Fatal(err)
2974 }
2975 runBackendServer()
2976 go enditall()
2977 go redeliverator()
2978 go tracker()
2979 go syndicator()
2980 go bgmonitor()
2981 go qotd()
2982 loadLingo()
2983 emuinit()
2984
2985 var toload []string
2986 dents, _ := os.ReadDir(viewDir + "/views")
2987 for _, dent := range dents {
2988 name := dent.Name()
2989 if strings.HasSuffix(name, ".html") {
2990 toload = append(toload, viewDir+"/views/"+name)
2991 }
2992 }
2993
2994 readviews = templates.Load(develMode, toload...)
2995 if !develMode {
2996 assets := []string{
2997 viewDir + "/views/style.css",
2998 dataDir + "/views/local.css",
2999 viewDir + "/views/honkpage.js",
3000 viewDir + "/views/misc.js",
3001 dataDir + "/views/local.js",
3002 viewDir + "/views/manifest.webmanifest",
3003 viewDir + "/views/sw.js",
3004 }
3005 for _, s := range assets {
3006 savedassetparams[s] = getassetparam(s)
3007 }
3008 loadAvatarColors()
3009 }
3010 startWatcher()
3011
3012 securitizeweb()
3013
3014 mux := mux.NewRouter()
3015 mux.Use(login.Checker)
3016
3017 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
3018
3019 posters := mux.Methods("POST").Subrouter()
3020 getters := mux.Methods("GET").Subrouter()
3021
3022 getters.HandleFunc("/", homepage)
3023 getters.HandleFunc("/home", homepage)
3024 getters.HandleFunc("/front", homepage)
3025 getters.HandleFunc("/events", homepage)
3026 getters.HandleFunc("/robots.txt", nomoroboto)
3027 getters.HandleFunc("/rss", showrss)
3028 getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
3029 getters.HandleFunc("/@{name:[\\pL[:digit:]]+}.json", showuser)
3030 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}.json", showuser)
3031 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
3032 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
3033 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}.json", showonehonk)
3034 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
3035 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
3036 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
3037 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
3038 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
3039 getters.HandleFunc("/a", avatate)
3040 getters.HandleFunc("/o", thelistingoftheontologies)
3041 getters.HandleFunc("/o/{name:.+}", showontology)
3042 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
3043 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
3044 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
3045 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
3046 getters.HandleFunc("/.well-known/nodeinfo", knowninformation)
3047 getters.HandleFunc("/nodeinfo/2.0", actualinformation)
3048
3049 getters.HandleFunc("/flag/{code:.+}", showflag)
3050
3051 getters.HandleFunc("/server", serveractor)
3052 posters.HandleFunc("/server/inbox", serverinbox)
3053 posters.HandleFunc("/inbox", serverinbox)
3054
3055 posters.HandleFunc("/csp-violation", fiveoh)
3056
3057 getters.HandleFunc("/style.css", serveviewasset)
3058 getters.HandleFunc("/sw.js", serveviewasset)
3059 getters.HandleFunc("/honkpage.js", serveviewasset)
3060 getters.HandleFunc("/misc.js", serveviewasset)
3061 getters.HandleFunc("/local.css", servedataasset)
3062 getters.HandleFunc("/local.js", servedataasset)
3063 getters.HandleFunc("/icon.png", servedataasset)
3064 getters.HandleFunc("/favicon.ico", servedataasset)
3065 getters.HandleFunc("/manifest.webmanifest", serveviewasset)
3066
3067 getters.HandleFunc("/about", servehtml)
3068 getters.HandleFunc("/login", servehtml)
3069 posters.HandleFunc("/dologin", login.LoginFunc)
3070 getters.HandleFunc("/logout", login.LogoutFunc)
3071 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
3072
3073 loggedin := mux.NewRoute().Subrouter()
3074 loggedin.Use(login.Required)
3075 loggedin.HandleFunc("/first", homepage)
3076 loggedin.HandleFunc("/chatter", showchatter)
3077 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
3078 loggedin.HandleFunc("/saved", homepage)
3079 loggedin.HandleFunc("/account", accountpage)
3080 loggedin.HandleFunc("/funzone", showfunzone)
3081 loggedin.HandleFunc("/chpass", dochpass)
3082 loggedin.HandleFunc("/atme", homepage)
3083 loggedin.HandleFunc("/longago", homepage)
3084 loggedin.HandleFunc("/hfcs", hfcspage)
3085 loggedin.HandleFunc("/xzone", xzone)
3086 loggedin.HandleFunc("/newhonk", newhonkpage)
3087 loggedin.HandleFunc("/edit", edithonkpage)
3088 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
3089 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
3090 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
3091 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
3092 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
3093 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
3094 loggedin.HandleFunc("/honkers", showhonkers)
3095 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
3096 loggedin.HandleFunc("/h", showhonker)
3097 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
3098 loggedin.HandleFunc("/c", showcombos)
3099 loggedin.HandleFunc("/t", showconvoy)
3100 loggedin.HandleFunc("/q", showsearch)
3101 loggedin.HandleFunc("/hydra", webhydra)
3102 loggedin.HandleFunc("/emus", showemus)
3103 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
3104
3105 // mastoshit
3106 mastopost := mux.Methods("POST").Subrouter()
3107 mastoget := mux.Methods("GET").Subrouter()
3108
3109 mastoget.HandleFunc("/oauth/authorize", showoauthlogin)
3110 mastopost.HandleFunc("/oauth/authorize", oauthorize)
3111 mastopost.HandleFunc("/oauth/token", oauthtoken)
3112 mastoget.HandleFunc("/api/v1/instance", instance)
3113 mastopost.HandleFunc("/api/v1/apps", apiapps)
3114 mastoget.HandleFunc("/api/v1/accounts/verify_credentials", checktoken(verifycreds))
3115
3116 loggedmux := handlers.LoggingHandler(os.Stdout, mux)
3117 err = http.Serve(listener, loggedmux)
3118 if err != nil {
3119 elog.Fatal(err)
3120 }
3121 if usefcgi {
3122 err = fcgi.Serve(listener, mux)
3123 } else {
3124 err = http.Serve(listener, mux)
3125 }
3126 if err != nil && !errors.Is(err, net.ErrClosed) {
3127 elog.Printf("serve error: %s", err)
3128 }
3129 time.Sleep(15 * time.Second)
3130 elog.Printf("fell off the bottom")
3131}
3132
3133// Verifies that accesstoken is valid and injects the associated
3134// MastoApp in the request context
3135func checktoken(h http.HandlerFunc) http.HandlerFunc {
3136 return func(w http.ResponseWriter, r *http.Request) {
3137 authHeader := r.Header.Get("Authorization")
3138 split := strings.Split(authHeader, "Bearer")
3139 if len(split) != 2 {
3140 elog.Println("masto: bad access token format or lack thereof")
3141 w.WriteHeader(http.StatusBadRequest)
3142 return
3143 }
3144
3145 token := strings.ReplaceAll(split[1], " ", "")
3146 app := getMastoAppFromAccessToken(token)
3147 if app == nil {
3148 elog.Println("masto: invalid access token")
3149 w.WriteHeader(http.StatusUnauthorized)
3150 return
3151 }
3152
3153 fmt.Printf("logged in! app: %s\n", app.Name)
3154
3155 ctx := context.WithValue(r.Context(), "app", app)
3156 r = r.WithContext(ctx)
3157 h(w, r)
3158 }
3159}