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