-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendto.go
209 lines (177 loc) · 5.05 KB
/
sendto.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package sendto
import (
"context"
"embed"
"errors"
"flag"
"fmt"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"strings"
"time"
"tailscale.com/client/tailscale"
"tailscale.com/hostinfo"
"tailscale.com/ipn"
"tailscale.com/tsnet"
"github.com/frankh/sendto/pkg/api"
"github.com/frankh/sendto/pkg/db"
)
const defaultHostname = "sendto"
var (
verbose = flag.Bool("verbose", false, "be verbose")
controlURL = flag.String("control-url", ipn.DefaultControlURL, "the URL base of the control plane (i.e. coordination server)")
sqlitefile = flag.String("sqlitedb", "sqlite.db", "path of SQLite database to store files and messages")
dev = flag.String("dev-listen", "", "if non-empty, listen on this addr and run in dev mode; auto-set sqlitedb if empty and don't use tsnet")
hostname = flag.String("hostname", defaultHostname, "service name")
)
//go:embed frontend/public
var embeddedFS embed.FS
var staticFS fs.FS
var localClient *tailscale.LocalClient
var database db.DB
func init() {
var err error
staticFS, err = fs.Sub(embeddedFS, "frontend/public")
if err != nil {
panic(err)
}
homeTmpl = template.Must(template.ParseFS(staticFS, "index.html"))
receiveTmpl = template.Must(template.ParseFS(staticFS, "receive.html"))
}
func Run() error {
flag.Parse()
hostinfo.SetApp("sendto")
database = db.NewSqliteDB(*sqlitefile)
sendHandler := api.SendHandler{database}
go func() {
for {
time.Sleep(10 * time.Minute)
database.ClearExpired()
}
}()
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
http.HandleFunc("/api/send", withUser(sendHandler.Serve))
http.HandleFunc("/r/", withUser(serveReceive))
http.HandleFunc("/", serveSendto)
if *dev != "" {
// override default hostname for dev mode
if *hostname == defaultHostname {
if h, p, err := net.SplitHostPort(*dev); err == nil {
if h == "" {
h = "localhost"
}
*hostname = fmt.Sprintf("%s:%s", h, p)
}
}
log.Printf("Running in dev mode on %s ...", *dev)
log.Fatal(http.ListenAndServe(*dev, nil))
}
if *hostname == "" {
return errors.New("--hostname, if specified, cannot be empty")
}
srv := &tsnet.Server{
Dir: ".tsnet-state",
ControlURL: *controlURL,
Hostname: *hostname,
Logf: func(format string, args ...any) {
// Show the log line with the interactive tailscale login link even when verbose is off
if strings.Contains(format, "To start this tsnet server") {
log.Printf(format, args...)
}
},
}
if *verbose {
srv.Logf = log.Printf
}
if err := srv.Start(); err != nil {
return err
}
localClient, _ = srv.LocalClient()
l80, err := srv.Listen("tcp", ":80")
if err != nil {
return err
}
log.Printf("Serving http://%s/ ...", *hostname)
if err := http.Serve(l80, nil); err != nil {
return err
}
return nil
}
var (
homeTmpl *template.Template
receiveTmpl *template.Template
)
func serveSendto(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "HTTP Method Unsupported", http.StatusBadRequest)
return
}
to := strings.TrimPrefix(r.URL.Path, "/")
if strings.Contains(to, "/") {
http.Error(w, "Not found", http.StatusNotFound)
return
}
to = findUser(to)
homeTmpl.Execute(w, struct{ To string }{To: to})
}
func findUser(to string) string {
st, err := localClient.Status(context.Background())
if err != nil {
return ""
}
for _, user := range st.User {
if strings.Split(user.LoginName, "@")[0] == to {
return user.LoginName
}
}
return ""
}
func serveReceive(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "HTTP Method Unsupported", http.StatusBadRequest)
return
}
id := strings.TrimPrefix(r.URL.Path, "/r/")
message, err := database.Load(id)
if err != nil {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
login, err := currentUser(r)
if err != nil || message.To != login {
http.Error(w, "Wrong user", http.StatusNotFound)
return
}
receiveTmpl.Execute(w, message)
}
// acceptHTML returns whether the request can accept a text/html response.
func acceptHTML(r *http.Request) bool {
return strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/html")
}
func devMode() bool { return *dev != "" }
func currentUser(r *http.Request) (string, error) {
login := ""
if devMode() {
login = "foo@example.com"
} else {
res, err := localClient.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
return "", err
}
login = res.UserProfile.LoginName
}
return login, nil
}
func withUser(next func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
login, err := currentUser(r)
if err != nil {
http.Error(w, "Bad login information", http.StatusBadRequest)
return
}
next(w, r.WithContext(context.WithValue(r.Context(), "login", login)))
})
}