-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (79 loc) · 2.1 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
_ "embed"
)
type Payload struct {
Ttl uint32 `json:"ttl"`
}
var (
Version = "dev"
CommitHash = "n/a"
BuildTimestamp = "n/a"
//go:embed banner.txt
banner string
flagVersion bool
config *Config
)
func main() {
print(banner)
flag.BoolVar(&flagVersion, "version", false, "Print the tool version and exit.")
flag.Parse()
if flagVersion {
fmt.Printf("jctp %s \n\nRevision : %s \nTimestamp : %s \n", Version, CommitHash, BuildTimestamp)
os.Exit(0)
}
config = loadConfig()
http.HandleFunc("/", getRoot)
address := fmt.Sprintf("%s:%d", config.Server.Address, config.Server.Port)
log.Printf("listening on %s", address)
err := http.ListenAndServe(address, nil)
if errors.Is(err, http.ErrServerClosed) {
log.Fatal("server closed")
} else if err != nil {
log.Fatalf("error starting server: %s", err)
}
}
// as per https://datatracker.ietf.org/doc/html/draft-uberti-behave-turn-rest-00#section-2.2
type UbertiTurnResponse struct {
Username string `json:"username"`
Password string `json:"password"`
Ttl uint32 `json:"ttl"`
Urls []string `json:"uris"`
}
func getRoot(w http.ResponseWriter, r *http.Request) {
log.Printf("Incoming: %s %s", r.Method, r.RemoteAddr)
params := parseParams(r.RequestURI)
payload := Payload{
Ttl: config.Cloudflare.Ttl,
}
credentials, err := requestCredentials(config.Cloudflare.KeyId, params, payload)
if err != nil {
log.Printf("Failed to request credentials: %s", err)
}
urls := []string{}
for _, url := range credentials.IceServers.Urls {
if strings.HasPrefix(url, "turn:") || strings.HasPrefix(url, "turns:") {
urls = append(urls, url)
}
}
responsePayload := &UbertiTurnResponse{
Username: credentials.IceServers.Username,
Password: credentials.IceServers.Password,
Ttl: config.Cloudflare.Ttl,
Urls: urls,
}
jsonPayload, err := json.Marshal(responsePayload)
if err != nil {
log.Printf("Failed to marshal payload: %s\n", err)
}
w.Header().Add("Content-Type", "application/json")
w.Write(jsonPayload)
}