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 fmt.Println("convoy:", convoy)
1947 }
1948 butnottooloud(honk.Audience)
1949 honk.Audience = oneofakind(honk.Audience)
1950 if len(honk.Audience) == 0 {
1951 ilog.Printf("honk to nowhere")
1952 http.Error(w, "honk to nowhere...", http.StatusNotFound)
1953 return nil
1954 }
1955 honk.Public = loudandproud(honk.Audience)
1956
1957 donkxid := strings.Join(r.Form["donkxid"], ",")
1958 if donkxid == "" {
1959 donks, err := submitdonk(w, r)
1960 if err != nil && err != http.ErrMissingFile {
1961 return nil
1962 }
1963 if len(donks) > 0 {
1964 honk.Donks = append(honk.Donks, donks...)
1965 var xids []string
1966 for _, d := range honk.Donks {
1967 xids = append(xids, fmt.Sprintf("%s:%d", d.XID, d.FileID))
1968 }
1969 donkxid = strings.Join(xids, ",")
1970 }
1971 } else {
1972 xids := strings.Split(donkxid, ",")
1973 for i, xid := range xids {
1974 if i > 16 {
1975 break
1976 }
1977 p := strings.Split(xid, ":")
1978 xid = p[0]
1979 url := serverURL("/d/%s", xid)
1980 var donk *Donk
1981 if len(p) > 1 {
1982 fileid, _ := strconv.ParseInt(p[1], 10, 0)
1983 donk = finddonkid(fileid, url)
1984 } else {
1985 donk = finddonk(url)
1986 }
1987 if donk != nil {
1988 honk.Donks = append(honk.Donks, donk)
1989 } else {
1990 ilog.Printf("can't find file: %s", xid)
1991 }
1992 }
1993 }
1994 memetize(honk)
1995 imaginate(honk)
1996
1997 placename := strings.TrimSpace(r.FormValue("placename"))
1998 placelat := strings.TrimSpace(r.FormValue("placelat"))
1999 placelong := strings.TrimSpace(r.FormValue("placelong"))
2000 placeurl := strings.TrimSpace(r.FormValue("placeurl"))
2001 if placename != "" || placelat != "" || placelong != "" || placeurl != "" {
2002 p := new(Place)
2003 p.Name = placename
2004 p.Latitude, _ = strconv.ParseFloat(placelat, 64)
2005 p.Longitude, _ = strconv.ParseFloat(placelong, 64)
2006 p.Url = placeurl
2007 honk.Place = p
2008 }
2009 timestart := strings.TrimSpace(r.FormValue("timestart"))
2010 if timestart != "" {
2011 t := new(Time)
2012 now := time.Now().Local()
2013 for _, layout := range []string{"2006-01-02 3:04pm", "2006-01-02 15:04", "3:04pm", "15:04"} {
2014 start, err := time.ParseInLocation(layout, timestart, now.Location())
2015 if err == nil {
2016 if start.Year() == 0 {
2017 start = time.Date(now.Year(), now.Month(), now.Day(), start.Hour(), start.Minute(), 0, 0, now.Location())
2018 }
2019 t.StartTime = start
2020 break
2021 }
2022 }
2023 timeend := r.FormValue("timeend")
2024 dur := parseDuration(timeend)
2025 if dur != 0 {
2026 t.Duration = Duration(dur)
2027 }
2028 if !t.StartTime.IsZero() {
2029 honk.What = "event"
2030 honk.Time = t
2031 }
2032 }
2033
2034 if honk.Public {
2035 honk.Whofore = 2
2036 } else {
2037 honk.Whofore = 3
2038 }
2039
2040 // back to markdown
2041 honk.Noise = noise
2042
2043 if r.FormValue("preview") == "preview" {
2044 honks := []*Honk{honk}
2045 reverbolate(user.ID, honks)
2046 templinfo := getInfo(r)
2047 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2048 templinfo["Honks"] = honks
2049 templinfo["MapLink"] = getmaplink(u)
2050 templinfo["InReplyTo"] = r.FormValue("rid")
2051 templinfo["Noise"] = r.FormValue("noise")
2052 templinfo["SavedFile"] = donkxid
2053 if tm := honk.Time; tm != nil {
2054 templinfo["ShowTime"] = " "
2055 templinfo["StartTime"] = tm.StartTime.Format("2006-01-02 15:04")
2056 if tm.Duration != 0 {
2057 templinfo["Duration"] = tm.Duration
2058 }
2059 }
2060 templinfo["IsPreview"] = true
2061 templinfo["UpdateXID"] = updatexid
2062 templinfo["ServerMessage"] = "honk preview"
2063 err := readviews.Execute(w, "honkpage.html", templinfo)
2064 if err != nil {
2065 elog.Print(err)
2066 }
2067 return nil
2068 }
2069
2070 if updatexid != "" {
2071 updatehonk(honk)
2072 oldjonks.Clear(honk.XID)
2073 } else {
2074 err := savehonk(honk)
2075 if err != nil {
2076 elog.Printf("uh oh")
2077 return nil
2078 }
2079 }
2080
2081 // reload for consistency
2082 honk.Donks = nil
2083 donksforhonks([]*Honk{honk})
2084
2085 go honkworldwide(user, honk)
2086
2087 return honk
2088}
2089
2090func showhonkers(w http.ResponseWriter, r *http.Request) {
2091 userid := UserID(login.GetUserInfo(r).UserID)
2092 templinfo := getInfo(r)
2093 templinfo["Honkers"] = gethonkers(userid)
2094 templinfo["HonkerCSRF"] = login.GetCSRF("submithonker", r)
2095 err := readviews.Execute(w, "honkers.html", templinfo)
2096 if err != nil {
2097 elog.Print(err)
2098 }
2099}
2100
2101func showchatter(w http.ResponseWriter, r *http.Request) {
2102 u := login.GetUserInfo(r)
2103 chatnewnone(UserID(u.UserID))
2104 chatter := loadchatter(UserID(u.UserID))
2105 for _, chat := range chatter {
2106 for _, ch := range chat.Chonks {
2107 filterchonk(ch)
2108 }
2109 }
2110
2111 templinfo := getInfo(r)
2112 templinfo["Chatter"] = chatter
2113 templinfo["ChonkCSRF"] = login.GetCSRF("sendchonk", r)
2114 err := readviews.Execute(w, "chatter.html", templinfo)
2115 if err != nil {
2116 elog.Print(err)
2117 }
2118}
2119
2120func submitchonk(w http.ResponseWriter, r *http.Request) {
2121 u := login.GetUserInfo(r)
2122 user, _ := butwhatabout(u.Username)
2123 noise := r.FormValue("noise")
2124 target := r.FormValue("target")
2125 format := "markdown"
2126 dt := time.Now().UTC()
2127 xid := fmt.Sprintf("%s/%s/%s", user.URL, "chonk", xfiltrate())
2128
2129 if !strings.HasPrefix(target, "https://") {
2130 target = fullname(target, user.ID)
2131 }
2132 if target == "" {
2133 http.Error(w, "who is that?", http.StatusInternalServerError)
2134 return
2135 }
2136 ch := Chonk{
2137 UserID: user.ID,
2138 XID: xid,
2139 Who: user.URL,
2140 Target: target,
2141 Date: dt,
2142 Noise: noise,
2143 Format: format,
2144 }
2145 donks, err := submitdonk(w, r)
2146 if err != nil && err != http.ErrMissingFile {
2147 return
2148 }
2149 if len(donks) > 0 {
2150 ch.Donks = append(ch.Donks, donks...)
2151 }
2152
2153 translatechonk(&ch)
2154 savechonk(&ch)
2155 // reload for consistency
2156 ch.Donks = nil
2157 donksforchonks([]*Chonk{&ch})
2158 go sendchonk(user, &ch)
2159
2160 http.Redirect(w, r, "/chatter", http.StatusSeeOther)
2161}
2162
2163var combocache = gencache.New(gencache.Options[UserID, []string]{Fill: func(userid UserID) ([]string, bool) {
2164 honkers := gethonkers(userid)
2165 var combos []string
2166 for _, h := range honkers {
2167 combos = append(combos, h.Combos...)
2168 }
2169 for i, c := range combos {
2170 if c == "-" {
2171 combos[i] = ""
2172 }
2173 }
2174 combos = oneofakind(combos)
2175 sort.Strings(combos)
2176 return combos, true
2177}, Invalidator: &honkerinvalidator})
2178
2179func showcombos(w http.ResponseWriter, r *http.Request) {
2180 templinfo := getInfo(r)
2181 err := readviews.Execute(w, "combos.html", templinfo)
2182 if err != nil {
2183 elog.Print(err)
2184 }
2185}
2186
2187func websubmithonker(w http.ResponseWriter, r *http.Request) {
2188 h := submithonker(w, r)
2189 if h == nil {
2190 return
2191 }
2192 http.Redirect(w, r, "/honkers", http.StatusSeeOther)
2193}
2194
2195func submithonker(w http.ResponseWriter, r *http.Request) *Honker {
2196 u := login.GetUserInfo(r)
2197 user, _ := butwhatabout(u.Username)
2198 name := strings.TrimSpace(r.FormValue("name"))
2199 url := strings.TrimSpace(r.FormValue("url"))
2200 peep := r.FormValue("peep")
2201 combos := strings.TrimSpace(r.FormValue("combos"))
2202 combos = " " + combos + " "
2203 honkerid, _ := strconv.ParseInt(r.FormValue("honkerid"), 10, 0)
2204
2205 re_namecheck := regexp.MustCompile("^[\\pL[:digit:]_.-]+$")
2206 if name != "" && !re_namecheck.MatchString(name) {
2207 http.Error(w, "please use a plainer name", http.StatusInternalServerError)
2208 return nil
2209 }
2210
2211 var meta HonkerMeta
2212 meta.Notes = strings.TrimSpace(r.FormValue("notes"))
2213 mj, _ := jsonify(&meta)
2214
2215 defer honkerinvalidator.Clear(user.ID)
2216
2217 // mostly dummy, fill in later...
2218 h := &Honker{
2219 ID: honkerid,
2220 }
2221
2222 if honkerid > 0 {
2223 if r.FormValue("delete") == "delete" {
2224 unfollowyou(user, honkerid, false)
2225 stmtDeleteHonker.Exec(honkerid)
2226 return h
2227 }
2228 if r.FormValue("unsub") == "unsub" {
2229 unfollowyou(user, honkerid, false)
2230 }
2231 if r.FormValue("sub") == "sub" {
2232 followyou(user, honkerid, false)
2233 }
2234 _, err := stmtUpdateHonker.Exec(name, combos, mj, honkerid, user.ID)
2235 if err != nil {
2236 elog.Printf("update honker err: %s", err)
2237 return nil
2238 }
2239 return h
2240 }
2241
2242 if url == "" {
2243 http.Error(w, "subscribing to nothing?", http.StatusInternalServerError)
2244 return nil
2245 }
2246
2247 flavor := "presub"
2248 if peep == "peep" {
2249 flavor = "peep"
2250 }
2251
2252 var err error
2253 honkerid, flavor, err = savehonker(user, url, name, flavor, combos, mj)
2254 if err != nil {
2255 http.Error(w, "had some trouble with that: "+err.Error(), http.StatusInternalServerError)
2256 return nil
2257 }
2258 if flavor == "presub" {
2259 followyou(user, honkerid, false)
2260 }
2261 h.ID = honkerid
2262 return h
2263}
2264
2265func hfcspage(w http.ResponseWriter, r *http.Request) {
2266 u := login.GetUserInfo(r)
2267
2268 filters := getfilters(UserID(u.UserID), filtAny)
2269
2270 templinfo := getInfo(r)
2271 templinfo["Filters"] = filters
2272 templinfo["FilterCSRF"] = login.GetCSRF("filter", r)
2273 err := readviews.Execute(w, "hfcs.html", templinfo)
2274 if err != nil {
2275 elog.Print(err)
2276 }
2277}
2278
2279func accountpage(w http.ResponseWriter, r *http.Request) {
2280 u := login.GetUserInfo(r)
2281 user, _ := butwhatabout(u.Username)
2282 templinfo := getInfo(r)
2283 templinfo["UserCSRF"] = login.GetCSRF("saveuser", r)
2284 templinfo["LogoutCSRF"] = login.GetCSRF("logout", r)
2285 templinfo["User"] = user
2286 about := user.About
2287 if ava := user.Options.Avatar; ava != "" {
2288 about += "\n\navatar: " + ava[strings.LastIndexByte(ava, '/')+1:]
2289 }
2290 if ban := user.Options.Banner; ban != "" {
2291 about += "\n\nbanner: " + ban[strings.LastIndexByte(ban, '/')+1:]
2292 }
2293 templinfo["WhatAbout"] = about
2294 err := readviews.Execute(w, "account.html", templinfo)
2295 if err != nil {
2296 elog.Print(err)
2297 }
2298}
2299
2300func dochpass(w http.ResponseWriter, r *http.Request) {
2301 err := login.ChangePassword(w, r)
2302 if err != nil {
2303 elog.Printf("error changing password: %s", err)
2304 }
2305 http.Redirect(w, r, "/account", http.StatusSeeOther)
2306}
2307
2308var oldfingers = gencache.New(gencache.Options[string, []byte]{Fill: func(orig string) ([]byte, bool) {
2309 if strings.HasPrefix(orig, "acct:") {
2310 orig = orig[5:]
2311 } else {
2312 orig, _ = url.QueryUnescape(orig)
2313 }
2314
2315 name := orig
2316 idx := strings.LastIndexByte(name, '/')
2317 if idx != -1 {
2318 url := fmt.Sprintf("https://%s/%s/%s", serverName, "u", name)
2319 name = name[idx+1:]
2320 if strings.HasPrefix(name, "@") {
2321 url = fmt.Sprintf("https://%s/%s", serverName, name)
2322 name = name[1:]
2323 }
2324 if url != orig {
2325 ilog.Printf("foreign request rejected")
2326 name = ""
2327 }
2328 } else {
2329 idx = strings.IndexByte(name, '@')
2330 if idx != -1 {
2331 name = name[:idx]
2332 if !(name+"@"+serverName == orig || name+"@"+masqName == orig) {
2333 ilog.Printf("foreign request rejected")
2334 name = ""
2335 }
2336 }
2337 }
2338 user, err := butwhatabout(name)
2339 if err != nil {
2340 return nil, false
2341 }
2342
2343 j := junk.New()
2344 pretty := fmt.Sprintf("https://%s/@%s", serverName, name)
2345 j["subject"] = fmt.Sprintf("acct:%s@%s", user.Name, masqName)
2346 j["aliases"] = []string{pretty, user.URL}
2347 l := junk.New()
2348 l["rel"] = "self"
2349 l["type"] = `application/activity+json`
2350 l["href"] = user.URL
2351 j["links"] = []junk.Junk{l}
2352 l2 := junk.New()
2353 l2["rel"] = "http://webfinger.net/rel/profile-page"
2354 l2["type"] = "text/html"
2355 l2["href"] = pretty
2356 l3 := junk.New()
2357 l3["rel"] = "http://webfinger.net/rel/avatar"
2358
2359 ext := filepath.Ext(user.Options.Avatar)
2360 if ext[1:] == "jpg" {
2361 l3["type"] = "image/jpeg"
2362 } else if ext[1:] == "png" {
2363 l3["type"] = "image/png"
2364 }
2365 l3["href"] = user.Options.Avatar
2366 j["links"] = []junk.Junk{l, l2, l3}
2367
2368 return j.ToBytes(), true
2369}})
2370
2371func fingerlicker(w http.ResponseWriter, r *http.Request) {
2372 orig := r.FormValue("resource")
2373
2374 dlog.Printf("finger lick: %s", orig)
2375
2376 j, ok := oldfingers.Get(orig)
2377 if ok {
2378 w.Header().Set("Content-Type", "application/jrd+json")
2379 w.Write(j)
2380 } else {
2381 http.NotFound(w, r)
2382 }
2383}
2384
2385func knowninformation(w http.ResponseWriter, r *http.Request) {
2386 j := junk.New()
2387 l := junk.New()
2388
2389 l["rel"] = `http://nodeinfo.diaspora.software/ns/schema/2.0`
2390 l["href"] = fmt.Sprintf("https://%s/nodeinfo/2.0", serverName)
2391 j["links"] = []junk.Junk{l}
2392
2393 w.Header().Set("Content-Type", "application/json")
2394 j.Write(w)
2395}
2396
2397func actualinformation(w http.ResponseWriter, r *http.Request) {
2398 j := junk.New()
2399
2400 soft := junk.New()
2401 soft["name"] = "honk"
2402 soft["version"] = softwareVersion
2403
2404 services := junk.New()
2405 services["inbound"] = []string{}
2406 services["outbound"] = []string{"rss2.0"}
2407
2408 users := junk.New()
2409 users["total"] = getusercount()
2410 users["activeHalfyear"] = getactiveusercount(6)
2411 users["activeMonth"] = getactiveusercount(1)
2412
2413 usage := junk.New()
2414 usage["users"] = users
2415 usage["localPosts"] = getlocalhonkcount()
2416
2417 j["version"] = "2.0"
2418 j["protocols"] = []string{"activitypub"}
2419 j["software"] = soft
2420 j["services"] = services
2421 j["openRegistrations"] = false
2422 j["usage"] = usage
2423
2424 w.Header().Set("Content-Type", "application/json")
2425 j.Write(w)
2426}
2427
2428func somedays() string {
2429 secs := 432000 + notrand.Int63n(432000)
2430 return fmt.Sprintf("%d", secs)
2431}
2432
2433func isurl(s string) bool {
2434 u, err := url.Parse(s)
2435 return err == nil && u.Scheme != "" && u.Host != ""
2436}
2437
2438func avatateautogen(r *http.Request) []byte {
2439 n := r.FormValue("a")
2440 return genAvatar(n)
2441}
2442
2443func avatate(w http.ResponseWriter, r *http.Request) {
2444 if develMode {
2445 loadAvatarColors()
2446 }
2447 var a []byte
2448 n := r.FormValue("a")
2449
2450 if isurl(n) {
2451 uinfo := login.GetUserInfo(r)
2452 if uinfo != nil {
2453 j, err := GetJunkFast(UserID(uinfo.UserID), n)
2454 if err != nil {
2455 dlog.Println("avatating: getting junk:", err)
2456 a = avatateautogen(r)
2457 }
2458 pfpurl, _ := j.GetString("icon", "url")
2459 res, err := http.Get(pfpurl)
2460 if err != nil {
2461 dlog.Println("avatating: getting pfp url:", err)
2462 a = avatateautogen(r)
2463 } else {
2464 defer res.Body.Close()
2465
2466 pfpbytes, err := io.ReadAll(res.Body)
2467 if err != nil {
2468 dlog.Println("avatating: bruh shits clapped:", err)
2469 a = avatateautogen(r)
2470 }
2471 a = pfpbytes
2472 }
2473 } else {
2474 a = avatateautogen(r)
2475 }
2476 } else {
2477 a = avatateautogen(r)
2478 }
2479
2480 if !develMode {
2481 w.Header().Set("Cache-Control", "max-age="+somedays())
2482 }
2483
2484 w.Write(a)
2485}
2486
2487func serveviewasset(w http.ResponseWriter, r *http.Request) {
2488 serveasset(w, r, viewDir)
2489}
2490func servedataasset(w http.ResponseWriter, r *http.Request) {
2491 if r.URL.Path == "/favicon.ico" {
2492 r.URL.Path = "/icon.png"
2493 }
2494 serveasset(w, r, dataDir)
2495}
2496
2497func serveasset(w http.ResponseWriter, r *http.Request, basedir string) {
2498 if !develMode {
2499 w.Header().Set("Cache-Control", "max-age=7776000")
2500 }
2501 http.ServeFile(w, r, basedir+"/views"+r.URL.Path)
2502}
2503func servehelp(w http.ResponseWriter, r *http.Request) {
2504 name := mux.Vars(r)["name"]
2505 if !develMode {
2506 w.Header().Set("Cache-Control", "max-age=3600")
2507 }
2508 http.ServeFile(w, r, viewDir+"/docs/"+name)
2509}
2510func servehtml(w http.ResponseWriter, r *http.Request) {
2511 u := login.GetUserInfo(r)
2512 templinfo := getInfo(r)
2513 templinfo["AboutMsg"] = aboutMsg
2514 templinfo["LoginMsg"] = loginMsg
2515 templinfo["HonkVersion"] = softwareVersion
2516 if r.URL.Path == "/about" {
2517 templinfo["Sensors"] = getSensors()
2518 }
2519 if u == nil && !develMode {
2520 w.Header().Set("Cache-Control", "max-age=60")
2521 }
2522 err := readviews.Execute(w, r.URL.Path[1:]+".html", templinfo)
2523 if err != nil {
2524 elog.Print(err)
2525 }
2526}
2527func serveemu(w http.ResponseWriter, r *http.Request) {
2528 emu := mux.Vars(r)["emu"]
2529
2530 w.Header().Set("Cache-Control", "max-age="+somedays())
2531 http.ServeFile(w, r, dataDir+"/emus/"+emu)
2532}
2533func servememe(w http.ResponseWriter, r *http.Request) {
2534 meme := mux.Vars(r)["meme"]
2535
2536 w.Header().Set("Cache-Control", "max-age="+somedays())
2537 _, err := os.Stat(dataDir + "/memes/" + meme)
2538 if err == nil {
2539 http.ServeFile(w, r, dataDir+"/memes/"+meme)
2540 } else {
2541 mux.Vars(r)["xid"] = meme
2542 servefile(w, r)
2543 }
2544}
2545
2546func servefile(w http.ResponseWriter, r *http.Request) {
2547 if friendorfoe(r.Header.Get("Accept")) {
2548 dlog.Printf("incompatible accept for donk")
2549 http.Error(w, "there are no activities here", http.StatusNotAcceptable)
2550 return
2551 }
2552 xid := mux.Vars(r)["xid"]
2553 preview := r.FormValue("preview") == "1"
2554 var media string
2555 var data []byte
2556 row := stmtGetFileData.QueryRow(xid)
2557 err := row.Scan(&media, &data)
2558 if err != nil {
2559 elog.Printf("error loading file: %s", err)
2560 http.NotFound(w, r)
2561 return
2562 }
2563 if preview && strings.HasPrefix(media, "image") {
2564 img, err := lilshrink(data)
2565 if err == nil {
2566 data = img.Data
2567 }
2568 }
2569 w.Header().Set("Content-Type", media)
2570 w.Header().Set("X-Content-Type-Options", "nosniff")
2571 w.Header().Set("Cache-Control", "max-age="+somedays())
2572 w.Write(data)
2573}
2574
2575func nomoroboto(w http.ResponseWriter, r *http.Request) {
2576 io.WriteString(w, "User-agent: *\n")
2577 io.WriteString(w, "Disallow: /a\n")
2578 io.WriteString(w, "Disallow: /d/\n")
2579 io.WriteString(w, "Disallow: /meme/\n")
2580 io.WriteString(w, "Disallow: /o\n")
2581 io.WriteString(w, "Disallow: /o/\n")
2582 io.WriteString(w, "Disallow: /help/\n")
2583 for _, u := range allusers() {
2584 fmt.Fprintf(w, "Disallow: /%s/%s/%s/\n", userSep, u.Username, honkSep)
2585 }
2586}
2587
2588type Hydration struct {
2589 Tophid int64
2590 Srvmsg template.HTML
2591 Honks string
2592 MeCount int64
2593 ChatCount int64
2594 Poses []int
2595}
2596
2597func webhydra(w http.ResponseWriter, r *http.Request) {
2598 u := login.GetUserInfo(r)
2599 userid := UserID(u.UserID)
2600 templinfo := getInfo(r)
2601 templinfo["HonkCSRF"] = login.GetCSRF("honkhonk", r)
2602 page := r.FormValue("page")
2603
2604 wanted, _ := strconv.ParseInt(r.FormValue("tophid"), 10, 0)
2605
2606 var hydra Hydration
2607
2608 var honks []*Honk
2609 switch page {
2610 case "atme":
2611 honks = gethonksforme(userid, wanted)
2612 honks = osmosis(honks, userid, false)
2613 menewnone(userid)
2614 hydra.Srvmsg = "at me!"
2615 case "longago":
2616 honks = gethonksfromlongago(userid, wanted)
2617 honks = osmosis(honks, userid, false)
2618 hydra.Srvmsg = "from long ago"
2619 case "home":
2620 honks = gethonksforuser(userid, wanted)
2621 honks = osmosis(honks, userid, true)
2622 hydra.Srvmsg = serverMsg
2623 case "first":
2624 honks = gethonksforuserfirstclass(userid, wanted)
2625 honks = osmosis(honks, userid, true)
2626 hydra.Srvmsg = "first class only"
2627 case "saved":
2628 honks = getsavedhonks(userid, wanted)
2629 templinfo["PageName"] = "saved"
2630 hydra.Srvmsg = "saved honks"
2631 case "combo":
2632 c := r.FormValue("c")
2633 honks = gethonksbycombo(userid, c, wanted)
2634 honks = osmosis(honks, userid, false)
2635 hydra.Srvmsg = templates.Sprintf("honks by combo: %s", c)
2636 case "convoy":
2637 c := r.FormValue("c")
2638 honks = gethonksbyconvoy(userid, c, 0)
2639 honks = osmosis(honks, userid, false)
2640 honks = threadsort(honks)
2641 honks, hydra.Poses = threadposes(honks, wanted)
2642 hydra.Srvmsg = templates.Sprintf("honks in convoy: %s", c)
2643 case "honker":
2644 xid := r.FormValue("xid")
2645 honks = gethonksbyxonker(userid, xid, wanted)
2646 miniform := templates.Sprintf(`<form action="/submithonker" method="POST">
2647 <input type="hidden" name="CSRF" value="%s">
2648 <input type="hidden" name="url" value="%s">
2649 <button tabindex=1 name="add honker" value="add honker">add honker</button>
2650 </form>`, login.GetCSRF("submithonker", r), xid)
2651 msg := templates.Sprintf(`honks by honker: <a href="%s" ref="noreferrer">%s</a>%s`, xid, xid, miniform)
2652 hydra.Srvmsg = msg
2653 case "user":
2654 uname := r.FormValue("uname")
2655 honks = gethonksbyuser(uname, u != nil && u.Username == uname, wanted)
2656 hydra.Srvmsg = templates.Sprintf("honks by user: %s", uname)
2657 default:
2658 http.NotFound(w, r)
2659 }
2660
2661 if len(honks) > 0 {
2662 if page == "convoy" {
2663 hydra.Tophid = honks[len(honks)-1].ID
2664 } else {
2665 hydra.Tophid = honks[0].ID
2666 }
2667 } else {
2668 hydra.Tophid = wanted
2669 }
2670 reverbolate(userid, honks)
2671
2672 user, _ := butwhatabout(u.Username)
2673
2674 var buf strings.Builder
2675 templinfo["Honks"] = honks
2676 templinfo["MapLink"] = getmaplink(u)
2677 templinfo["User"], _ = butwhatabout(u.Username)
2678 err := readviews.Execute(&buf, "honkfrags.html", templinfo)
2679 if err != nil {
2680 elog.Printf("frag error: %s", err)
2681 return
2682 }
2683 hydra.Honks = buf.String()
2684 hydra.MeCount = user.Options.MeCount
2685 hydra.ChatCount = user.Options.ChatCount
2686 w.Header().Set("Content-Type", "application/json")
2687 j, _ := jsonify(&hydra)
2688 io.WriteString(w, j)
2689}
2690
2691var honkline = make(chan bool)
2692
2693func honkhonkline() {
2694 for {
2695 select {
2696 case honkline <- true:
2697 default:
2698 return
2699 }
2700 }
2701}
2702
2703func apihandler(w http.ResponseWriter, r *http.Request) {
2704 u := login.GetUserInfo(r)
2705 userid := UserID(u.UserID)
2706 action := r.FormValue("action")
2707 wait, _ := strconv.ParseInt(r.FormValue("wait"), 10, 0)
2708 dlog.Printf("api request '%s' on behalf of %s", action, u.Username)
2709 switch action {
2710 case "honk":
2711 h := submithonk(w, r)
2712 if h == nil {
2713 return
2714 }
2715
2716 fmt.Fprintf(w, "%s", h.XID)
2717 case "donk":
2718 donks, err := submitdonk(w, r)
2719 if err != nil {
2720 http.Error(w, err.Error(), http.StatusBadRequest)
2721 return
2722 }
2723 if len(donks) == 0 {
2724 http.Error(w, "missing donk", http.StatusBadRequest)
2725 return
2726 }
2727 d := donks[0]
2728 donkxid := fmt.Sprintf("%s:%d", d.XID, d.FileID)
2729 w.Write([]byte(donkxid))
2730 case "zonkit":
2731 zonkit(w, r)
2732 case "gethonks":
2733 var honks []*Honk
2734 wanted, _ := strconv.ParseInt(r.FormValue("after"), 10, 0)
2735 page := r.FormValue("page")
2736 var waitchan <-chan time.Time
2737 requery:
2738 switch page {
2739 case "atme":
2740 honks = gethonksforme(userid, wanted)
2741 honks = osmosis(honks, userid, false)
2742 menewnone(userid)
2743 case "longago":
2744 honks = gethonksfromlongago(userid, wanted)
2745 honks = osmosis(honks, userid, false)
2746 case "home":
2747 honks = gethonksforuser(userid, wanted)
2748 honks = osmosis(honks, userid, true)
2749 case "myhonks":
2750 honks = gethonksbyuser(u.Username, true, wanted)
2751 honks = osmosis(honks, userid, true)
2752 case "saved":
2753 honks = getsavedhonks(userid, wanted)
2754 case "combo":
2755 c := r.FormValue("c")
2756 honks = gethonksbycombo(userid, c, wanted)
2757 honks = osmosis(honks, userid, false)
2758 case "convoy":
2759 c := r.FormValue("c")
2760 honks = gethonksbyconvoy(userid, c, 0)
2761 honks = osmosis(honks, userid, false)
2762 honks = threadsort(honks)
2763 honks, _ = threadposes(honks, wanted)
2764 case "honker":
2765 xid := r.FormValue("xid")
2766 honks = gethonksbyxonker(userid, xid, wanted)
2767 case "search":
2768 q := r.FormValue("q")
2769 honks = gethonksbysearch(userid, q, wanted)
2770 default:
2771 http.Error(w, "unknown page", http.StatusNotFound)
2772 return
2773 }
2774 if len(honks) == 0 && wait > 0 {
2775 if waitchan == nil {
2776 waitchan = time.After(time.Duration(wait) * time.Second)
2777 }
2778 select {
2779 case <-honkline:
2780 goto requery
2781 case <-waitchan:
2782 }
2783 }
2784 reverbolate(userid, honks)
2785 user, _ := butwhatabout(u.Username)
2786 j := junk.New()
2787 j["honks"] = honks
2788 j["mecount"] = user.Options.MeCount
2789 j["chatcount"] = user.Options.ChatCount
2790 j.Write(w)
2791 case "sendactivity":
2792 public := r.FormValue("public") == "1"
2793 user, _ := butwhatabout(u.Username)
2794 rcpts := boxuprcpts(user, r.Form["rcpt"], public)
2795 msg := []byte(r.FormValue("msg"))
2796 for rcpt := range rcpts {
2797 go deliverate(userid, rcpt, msg)
2798 }
2799 case "gethonkers":
2800 j := junk.New()
2801 j["honkers"] = gethonkers(userid)
2802 j.Write(w)
2803 case "savehonker":
2804 h := submithonker(w, r)
2805 if h == nil {
2806 return
2807 }
2808 fmt.Fprintf(w, "%d", h.ID)
2809 default:
2810 http.Error(w, "unknown action", http.StatusNotFound)
2811 return
2812 }
2813}
2814
2815func fiveoh(w http.ResponseWriter, r *http.Request) {
2816 if !develMode {
2817 return
2818 }
2819 fd, err := os.OpenFile("violations.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2820 if err != nil {
2821 elog.Printf("error opening violations! %s", err)
2822 return
2823 }
2824 defer fd.Close()
2825 io.Copy(fd, r.Body)
2826 fd.WriteString("\n")
2827}
2828
2829var endoftheworld = make(chan bool)
2830var readyalready = make(chan bool)
2831var workinprogress = 0
2832var requestWG sync.WaitGroup
2833var listenSocket net.Listener
2834
2835func enditall() {
2836 sig := make(chan os.Signal, 1)
2837 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
2838 <-sig
2839 ilog.Printf("stopping...")
2840 listenSocket.Close()
2841 for i := 0; i < workinprogress; i++ {
2842 endoftheworld <- true
2843 }
2844 if *cpuprofile != "" {
2845 pprof.StopCPUProfile()
2846 }
2847 if *memprofile != "" {
2848 pprof.WriteHeapProfile(memprofilefd)
2849 memprofilefd.Close()
2850 }
2851 ilog.Printf("waiting...")
2852 go func() {
2853 time.Sleep(10 * time.Second)
2854 elog.Printf("timed out waiting for requests to finish")
2855 os.Exit(0)
2856 }()
2857 for i := 0; i < workinprogress; i++ {
2858 <-readyalready
2859 }
2860 requestWG.Wait()
2861 ilog.Printf("apocalypse")
2862 closedatabases()
2863 os.Exit(0)
2864}
2865
2866func bgmonitor() {
2867 for {
2868 when := time.Now().Add(-3 * 24 * time.Hour).UTC().Format(dbtimeformat)
2869 _, err := stmtDeleteOldXonkers.Exec("pubkey", when)
2870 if err != nil {
2871 elog.Printf("error deleting old xonkers: %s", err)
2872 }
2873 zaggies.Flush()
2874 time.Sleep(50 * time.Minute)
2875 }
2876}
2877
2878func addcspheaders(next http.Handler) http.Handler {
2879 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2880 requestWG.Add(1)
2881 defer requestWG.Done()
2882 policy := "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'"
2883 if develMode {
2884 policy += "; report-uri /csp-violation"
2885 }
2886 w.Header().Set("Content-Security-Policy", policy)
2887 next.ServeHTTP(w, r)
2888 })
2889}
2890
2891func emuinit() {
2892 var emunames []string
2893 dir, err := os.Open(dataDir + "/emus")
2894 if err == nil {
2895 emunames, _ = dir.Readdirnames(0)
2896 dir.Close()
2897 }
2898 for _, e := range emunames {
2899 if len(e) <= 4 {
2900 continue
2901 }
2902 ext := e[len(e)-4:]
2903 emu := Emu{
2904 ID: fmt.Sprintf("/emu/%s", e),
2905 Name: e[:len(e)-4],
2906 Type: "image/" + ext[1:],
2907 }
2908 allemus = append(allemus, emu)
2909 }
2910 sort.Slice(allemus, func(i, j int) bool {
2911 return allemus[i].Name < allemus[j].Name
2912 })
2913}
2914
2915func redirectPretty(w http.ResponseWriter, r *http.Request) {
2916 last := path.Base(r.URL.Path)
2917 name := mux.Vars(r)["name"]
2918 aturl := "/@" + name
2919
2920 if last == name {
2921 last = ""
2922 }
2923 http.Redirect(w, r, path.Join(aturl, last), http.StatusMovedPermanently)
2924}
2925
2926var savedassetparams = make(map[string]string)
2927
2928func getassetparam(file string) string {
2929 if p, ok := savedassetparams[file]; ok {
2930 return p
2931 }
2932 data, err := os.ReadFile(file)
2933 if err != nil {
2934 return ""
2935 }
2936 hasher := sha512.New()
2937 hasher.Write(data)
2938
2939 return fmt.Sprintf("?v=%.8x", hasher.Sum(nil))
2940}
2941
2942func startWatcher() {
2943 watcher, err := gonix.NewWatcher()
2944 if err != nil {
2945 return
2946 }
2947 go func() {
2948 s := dataDir + "/views/local.css"
2949 for {
2950 err := watcher.WatchFile(s)
2951 if err != nil {
2952 break
2953 }
2954 err = watcher.WaitForChange()
2955 if err != nil {
2956 dlog.Printf("can't wait: %s", err)
2957 break
2958 }
2959 dlog.Printf("local.css changed")
2960 delete(savedassetparams, s)
2961 savedassetparams[s] = getassetparam(s)
2962 }
2963 }()
2964}
2965
2966var usefcgi bool
2967
2968func serve() {
2969 db := opendatabase()
2970 login.Init(login.InitArgs{Db: db, Logger: ilog, Insecure: develMode, SameSiteStrict: !develMode})
2971
2972 listener, err := openListener()
2973 if err != nil {
2974 elog.Fatal(err)
2975 }
2976 runBackendServer()
2977 go enditall()
2978 go redeliverator()
2979 go tracker()
2980 go syndicator()
2981 go bgmonitor()
2982 go qotd()
2983 loadLingo()
2984 emuinit()
2985
2986 var toload []string
2987 dents, _ := os.ReadDir(viewDir + "/views")
2988 for _, dent := range dents {
2989 name := dent.Name()
2990 if strings.HasSuffix(name, ".html") {
2991 toload = append(toload, viewDir+"/views/"+name)
2992 }
2993 }
2994
2995 readviews = templates.Load(develMode, toload...)
2996 if !develMode {
2997 assets := []string{
2998 viewDir + "/views/style.css",
2999 dataDir + "/views/local.css",
3000 viewDir + "/views/honkpage.js",
3001 viewDir + "/views/misc.js",
3002 dataDir + "/views/local.js",
3003 viewDir + "/views/manifest.webmanifest",
3004 viewDir + "/views/sw.js",
3005 }
3006 for _, s := range assets {
3007 savedassetparams[s] = getassetparam(s)
3008 }
3009 loadAvatarColors()
3010 }
3011 startWatcher()
3012
3013 securitizeweb()
3014
3015 mux := mux.NewRouter()
3016 mux.Use(login.Checker)
3017
3018 mux.Handle("/api", login.TokenRequired(http.HandlerFunc(apihandler)))
3019
3020 posters := mux.Methods("POST").Subrouter()
3021 getters := mux.Methods("GET").Subrouter()
3022
3023 getters.HandleFunc("/", homepage)
3024 getters.HandleFunc("/home", homepage)
3025 getters.HandleFunc("/front", homepage)
3026 getters.HandleFunc("/events", homepage)
3027 getters.HandleFunc("/robots.txt", nomoroboto)
3028 getters.HandleFunc("/rss", showrss)
3029 getters.HandleFunc("/@{name:[\\pL[:digit:]]+}", showuser)
3030 getters.HandleFunc("/@{name:[\\pL[:digit:]]+}.json", showuser)
3031 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}.json", showuser)
3032 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}", redirectPretty)
3033 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}", showonehonk)
3034 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/"+honkSep+"/{xid:[\\pL[:digit:]]+}.json", showonehonk)
3035 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/rss", showrss)
3036 posters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/inbox", inbox)
3037 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/outbox", outbox)
3038 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/followers", emptiness)
3039 getters.HandleFunc("/"+userSep+"/{name:[\\pL[:digit:]]+}/following", emptiness)
3040 getters.HandleFunc("/a", avatate)
3041 getters.HandleFunc("/o", thelistingoftheontologies)
3042 getters.HandleFunc("/o/{name:.+}", showontology)
3043 getters.HandleFunc("/d/{xid:[\\pL[:digit:].]+}", servefile)
3044 getters.HandleFunc("/emu/{emu:[^.]*[^/]+}", serveemu)
3045 getters.HandleFunc("/meme/{meme:[^.]*[^/]+}", servememe)
3046 getters.HandleFunc("/.well-known/webfinger", fingerlicker)
3047 getters.HandleFunc("/.well-known/nodeinfo", knowninformation)
3048 getters.HandleFunc("/nodeinfo/2.0", actualinformation)
3049
3050 getters.HandleFunc("/flag/{code:.+}", showflag)
3051
3052 getters.HandleFunc("/server", serveractor)
3053 posters.HandleFunc("/server/inbox", serverinbox)
3054 posters.HandleFunc("/inbox", serverinbox)
3055
3056 posters.HandleFunc("/csp-violation", fiveoh)
3057
3058 getters.HandleFunc("/style.css", serveviewasset)
3059 getters.HandleFunc("/sw.js", serveviewasset)
3060 getters.HandleFunc("/honkpage.js", serveviewasset)
3061 getters.HandleFunc("/misc.js", serveviewasset)
3062 getters.HandleFunc("/local.css", servedataasset)
3063 getters.HandleFunc("/local.js", servedataasset)
3064 getters.HandleFunc("/icon.png", servedataasset)
3065 getters.HandleFunc("/favicon.ico", servedataasset)
3066 getters.HandleFunc("/manifest.webmanifest", serveviewasset)
3067
3068 getters.HandleFunc("/about", servehtml)
3069 getters.HandleFunc("/login", servehtml)
3070 posters.HandleFunc("/dologin", login.LoginFunc)
3071 getters.HandleFunc("/logout", login.LogoutFunc)
3072 getters.HandleFunc("/help/{name:[\\pL[:digit:]_.-]+}", servehelp)
3073
3074 loggedin := mux.NewRoute().Subrouter()
3075 loggedin.Use(login.Required)
3076 loggedin.HandleFunc("/first", homepage)
3077 loggedin.HandleFunc("/chatter", showchatter)
3078 loggedin.Handle("/sendchonk", login.CSRFWrap("sendchonk", http.HandlerFunc(submitchonk)))
3079 loggedin.HandleFunc("/saved", homepage)
3080 loggedin.HandleFunc("/account", accountpage)
3081 loggedin.HandleFunc("/funzone", showfunzone)
3082 loggedin.HandleFunc("/chpass", dochpass)
3083 loggedin.HandleFunc("/atme", homepage)
3084 loggedin.HandleFunc("/longago", homepage)
3085 loggedin.HandleFunc("/hfcs", hfcspage)
3086 loggedin.HandleFunc("/xzone", xzone)
3087 loggedin.HandleFunc("/newhonk", newhonkpage)
3088 loggedin.HandleFunc("/edit", edithonkpage)
3089 loggedin.Handle("/honk", login.CSRFWrap("honkhonk", http.HandlerFunc(websubmithonk)))
3090 loggedin.Handle("/bonk", login.CSRFWrap("honkhonk", http.HandlerFunc(submitbonk)))
3091 loggedin.Handle("/zonkit", login.CSRFWrap("honkhonk", http.HandlerFunc(zonkit)))
3092 loggedin.Handle("/savehfcs", login.CSRFWrap("filter", http.HandlerFunc(savehfcs)))
3093 loggedin.Handle("/saveuser", login.CSRFWrap("saveuser", http.HandlerFunc(saveuser)))
3094 loggedin.Handle("/ximport", login.CSRFWrap("ximport", http.HandlerFunc(ximport)))
3095 loggedin.HandleFunc("/honkers", showhonkers)
3096 loggedin.HandleFunc("/h/{name:[\\pL[:digit:]_.-]+}", showhonker)
3097 loggedin.HandleFunc("/h", showhonker)
3098 loggedin.HandleFunc("/c/{name:[\\pL[:digit:]_.-]+}", showcombo)
3099 loggedin.HandleFunc("/c", showcombos)
3100 loggedin.HandleFunc("/t", showconvoy)
3101 loggedin.HandleFunc("/q", showsearch)
3102 loggedin.HandleFunc("/hydra", webhydra)
3103 loggedin.HandleFunc("/emus", showemus)
3104 loggedin.Handle("/submithonker", login.CSRFWrap("submithonker", http.HandlerFunc(websubmithonker)))
3105
3106 // mastoshit
3107 mastopost := mux.Methods("POST").Subrouter()
3108 mastoget := mux.Methods("GET").Subrouter()
3109
3110 mastoget.HandleFunc("/oauth/authorize", showoauthlogin)
3111 mastopost.HandleFunc("/oauth/authorize", oauthorize)
3112 mastopost.HandleFunc("/oauth/token", oauthtoken)
3113 mastoget.HandleFunc("/api/v1/instance", instance)
3114 mastopost.HandleFunc("/api/v1/apps", apiapps)
3115 mastoget.HandleFunc("/api/v1/accounts/verify_credentials", checktoken(verifycreds))
3116
3117 loggedmux := handlers.LoggingHandler(os.Stdout, mux)
3118 err = http.Serve(listener, loggedmux)
3119 if err != nil {
3120 elog.Fatal(err)
3121 }
3122 if usefcgi {
3123 err = fcgi.Serve(listener, mux)
3124 } else {
3125 err = http.Serve(listener, mux)
3126 }
3127 if err != nil && !errors.Is(err, net.ErrClosed) {
3128 elog.Printf("serve error: %s", err)
3129 }
3130 time.Sleep(15 * time.Second)
3131 elog.Printf("fell off the bottom")
3132}
3133
3134// Verifies that accesstoken is valid and injects the associated
3135// MastoApp in the request context
3136func checktoken(h http.HandlerFunc) http.HandlerFunc {
3137 return func(w http.ResponseWriter, r *http.Request) {
3138 authHeader := r.Header.Get("Authorization")
3139 split := strings.Split(authHeader, "Bearer")
3140 if len(split) != 2 {
3141 elog.Println("masto: bad access token format or lack thereof")
3142 w.WriteHeader(http.StatusBadRequest)
3143 return
3144 }
3145
3146 token := strings.ReplaceAll(split[1], " ", "")
3147 app := getMastoAppFromAccessToken(token)
3148 if app == nil {
3149 elog.Println("masto: invalid access token")
3150 w.WriteHeader(http.StatusUnauthorized)
3151 return
3152 }
3153
3154 fmt.Printf("logged in! app: %s\n", app.Name)
3155
3156 ctx := context.WithValue(r.Context(), "app", app)
3157 r = r.WithContext(ctx)
3158 h(w, r)
3159 }
3160}