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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
|
// This file is part of gnsregistrar, a GNS registrar implementation.
// Copyright (C) 2022 Martin Schanzenbach
//
// gnsregistrar is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// gnsregistrar is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later
package gnsregistrar
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"gopkg.in/ini.v1"
"taler.net/taler-go.git/pkg/merchant"
)
type RegistrationMetadata struct {
Expiration uint64 `json:"expiration"`
Paid bool `json:"paid"`
}
type IdentityInfo struct {
Pubkey string `json:"pubkey"`
Name string `json:"name"`
}
type GnunetError struct {
Description string `json:"error"`
Code uint32 `json:"error_code"`
}
type RecordData struct {
Value string `json:"value"`
RecordType string `json:"record_type"`
RelativeExpiration uint64 `json:"relative_expiration"`
IsPrivate bool `json:"is_private"`
IsRelativeExpiration bool `json:"is_relative_expiration"`
IsSupplemental bool `json:"is_supplemental"`
IsShadow bool `json:"is_shadow"`
IsMaintenance bool `json:"is_maintenance"`
}
type NamestoreRecord struct {
RecordName string `json:"record_name"`
Records []RecordData `json:"data"`
}
// Registrar is the primary object of the service
type Registrar struct {
// The main router
Router *mux.Router
// Our configuration from the config.json
Cfg *ini.File
// Map of supported validators as defined in the configuration
Validators map[string]bool
// landing page
LandingTpl *template.Template
// name page
NameTpl *template.Template
// all names page
AllNamesTpl *template.Template
// Merchant object
Merchant merchant.Merchant
// Relative record expiration (NOT registration expiration!)
RelativeDelegationExpiration time.Duration
// Registration expiration (NOT record expiration!)
RelativeRegistrationExpiration time.Duration
// Name of our root zone
RootZoneName string
// Key of our root zone
RootZoneKey string
// Suggested suffix for our zone
SuffixHint string
// Gnunet REST API basename
GnunetUrl string
// Registration policy; fcfs or paid
RegistrationPolicy string
// Cost for a registration
RegistrationCost uint64
// Currency to use
RegistrationCostCurrency string
}
type VersionResponse struct {
// libtool-style representation of the Merchant protocol version, see
// https://www.gnu.org/software/libtool/manual/html_node/Versioning.html#Versioning
// The format is "current:revision:age".
Version string `json:"version"`
}
func (t *Registrar) configResponse(w http.ResponseWriter, r *http.Request) {
cfg := VersionResponse{
Version: "0:0:0",
}
w.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(cfg)
w.Write(response)
}
func (t *Registrar) landingPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fullData := map[string]interface{}{
"suffixHint": t.SuffixHint,
"zoneKey": t.RootZoneKey,
}
t.LandingTpl.Execute(w, fullData)
return
}
func (t *Registrar) registerName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var namestoreRequest NamestoreRecord
var delegationRecord RecordData
var metadataRecord RecordData
var gnunetError GnunetError
var registrationMetadata RegistrationMetadata
w.Header().Set("Content-Type", "text/html; charset=utf-8")
delegationRecord.IsPrivate = false
delegationRecord.IsRelativeExpiration = true
delegationRecord.IsSupplemental = false
delegationRecord.IsMaintenance = false
delegationRecord.IsShadow = false
delegationRecord.RecordType = "PKEY" // FIXME get from value
delegationRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
delegationRecord.Value = r.URL.Query().Get("zkey")
metadataRecord.IsPrivate = true
metadataRecord.IsRelativeExpiration = true
metadataRecord.IsSupplemental = false
metadataRecord.IsMaintenance = true
metadataRecord.IsShadow = false
metadataRecord.RecordType = "TXT" // FIXME use new recory type
metadataRecord.RelativeExpiration = uint64(t.RelativeDelegationExpiration.Microseconds())
registrationMetadata = RegistrationMetadata{
Paid: false,
Expiration: uint64(time.Now().Add(t.RelativeRegistrationExpiration).UnixMicro()),
}
metadataRecordValue, err := json.Marshal(registrationMetadata)
if nil != err {
http.Redirect(w, r, "/name?label="+vars["label"] + "&error=Registration failed", http.StatusSeeOther)
return
}
metadataRecord.Value = string(metadataRecordValue)
namestoreRequest.RecordName = vars["label"]
namestoreRequest.Records = []RecordData{delegationRecord,metadataRecord}
reqString, _ := json.Marshal(namestoreRequest)
// FIXME handle errors here
fmt.Println(namestoreRequest)
resp, err := http.Post(t.GnunetUrl+"/namestore/" + t.RootZoneName, "application/json", bytes.NewBuffer(reqString))
resp.Body.Close()
if http.StatusNoContent != resp.StatusCode {
fmt.Printf("Got error: %d\n", resp.StatusCode)
json.NewDecoder(resp.Body).Decode(&gnunetError)
fmt.Println(gnunetError.Code)
fmt.Println(err)
http.Redirect(w, r, "/name?label="+vars["label"] + "&error=" + gnunetError.Description, http.StatusSeeOther)
return
}
http.Redirect(w, r, "/name/"+ vars["label"] + "?registered=true", http.StatusSeeOther)
return
}
func (t *Registrar) searchPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
http.Redirect(w, r, "/name/"+r.URL.Query().Get("label"), http.StatusSeeOther)
return
}
func (t *Registrar) buyPage(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if t.RegistrationCost == 0 {
http.Redirect(w, r, "/name/"+vars["label"]+"/register?zkey="+r.URL.Query().Get("zkey"), http.StatusSeeOther)
return
}
http.Redirect(w, r, "/name/"+vars["label"]+"?error=Not implemented", http.StatusSeeOther)
return
}
func (t *Registrar) namePage(w http.ResponseWriter, r *http.Request) {
var metadataResponse RegistrationMetadata
var namestoreResponse NamestoreRecord
vars := mux.Vars(r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
var available = false
var value = ""
var registeredUntil = "unkown"
var registered = r.URL.Query().Get("registered") == "true"
// FIXME redirect back if label empty
resp, err := http.Get(t.GnunetUrl + "/namestore/" + t.RootZoneName + "/" + vars["label"] + "?include_maintenance=yes")
if err != nil {
fmt.Printf("Failed to get zone contents")
return
}
defer resp.Body.Close()
if http.StatusOK == resp.StatusCode {
respData, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
err = json.NewDecoder(bytes.NewReader(respData)).Decode(&namestoreResponse)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
for _, record := range namestoreResponse.Records {
if record.RecordType == "PKEY" {
value = record.Value
}
if record.RecordType == "TXT" {
err = json.Unmarshal([]byte(record.Value), &metadataResponse)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
registeredUntil = time.UnixMicro(int64(metadataResponse.Expiration)).String()
}
}
} else {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
available = value == ""
fullData := map[string]interface{}{
"label": vars["label"],
"error": r.URL.Query().Get("error"),
"cost": t.RegistrationCost,
"currency": t.RegistrationCostCurrency,
"available": available,
"currentValue": value,
"suffixHint": t.SuffixHint,
"registrationPolicy": t.RegistrationPolicy,
"registeredUntil": registeredUntil,
"registrationSuccess": registered,
}
t.NameTpl.Execute(w, fullData)
return
}
func (t *Registrar) allNamesPage(w http.ResponseWriter, r *http.Request) {
var namestoreResponse []NamestoreRecord
w.Header().Set("Content-Type", "text/html; charset=utf-8")
resp, err := http.Get(t.GnunetUrl + "/namestore/" + t.RootZoneName)
if err != nil {
fmt.Printf("Failed to get zone contents")
return
}
defer resp.Body.Close()
if http.StatusOK != resp.StatusCode {
fmt.Printf("Failed to get zone contents. Retcode=%d", resp.StatusCode)
return
}
respData, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
err = json.NewDecoder(bytes.NewReader(respData)).Decode(&namestoreResponse)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
return
}
fmt.Println(namestoreResponse)
t.AllNamesTpl.Execute(w, namestoreResponse)
return
}
func (t *Registrar) setupHandlers() {
t.Router = mux.NewRouter().StrictSlash(true)
t.Router.HandleFunc("/", t.landingPage).Methods("GET")
t.Router.HandleFunc("/name/{label}", t.namePage).Methods("GET")
t.Router.HandleFunc("/name/{label}/buy", t.buyPage).Methods("GET")
t.Router.HandleFunc("/name/{label}/register", t.registerName).Methods("GET")
t.Router.HandleFunc("/search", t.searchPage).Methods("GET")
t.Router.HandleFunc("/names", t.allNamesPage).Methods("GET")
/* ToS API */
// t.Router.HandleFunc("/terms", t.termsResponse).Methods("GET")
// t.Router.HandleFunc("/privacy", t.privacyResponse).Methods("GET")
/* Config API */
t.Router.HandleFunc("/config", t.configResponse).Methods("GET")
/* Assets HTML */
t.Router.PathPrefix("/css").Handler(http.StripPrefix("/css", http.FileServer(http.Dir("./static/css"))))
}
// Initialize the gnsregistrar instance with cfgfile
func (t *Registrar) Initialize(cfgfile string) {
var identityResponse IdentityInfo
_cfg, err := ini.Load(cfgfile)
if err != nil {
fmt.Printf("Failed to read config: %v", err)
os.Exit(1)
}
t.Cfg = _cfg
if t.Cfg.Section("gns-registrar").Key("production").MustBool(false) {
fmt.Println("Production mode enabled")
}
landingTplFile := t.Cfg.Section("gns-registrar").Key("registrar_landing").MustString("web/templates/landing.html")
t.LandingTpl, err = template.ParseFiles(landingTplFile)
if err != nil {
fmt.Println(err)
}
nameTplFile := t.Cfg.Section("gns-registrar").Key("registrar_name").MustString("web/templates/name.html")
t.NameTpl, err = template.ParseFiles(nameTplFile)
if err != nil {
fmt.Println(err)
}
allNamesTplFile := t.Cfg.Section("gns-registrar").Key("registrar_all_names").MustString("web/templates/names.html")
t.AllNamesTpl, err = template.ParseFiles(allNamesTplFile)
if err != nil {
fmt.Println(err)
}
t.RegistrationCost = t.Cfg.Section("gns-registrar").Key("registration_cost").MustUint64(0)
recordExp := t.Cfg.Section("gns-registrar").Key("relative_delegation_expiration").MustString("24h")
registrationExp := t.Cfg.Section("gns-registrar").Key("registration_expiration").MustString("8760h")
fmt.Println(recordExp)
fmt.Println(registrationExp)
t.RelativeRegistrationExpiration, _ = time.ParseDuration(registrationExp)
t.RelativeDelegationExpiration, _ = time.ParseDuration(recordExp)
fmt.Println(t.RelativeDelegationExpiration)
fmt.Println(t.RelativeRegistrationExpiration)
t.RegistrationCostCurrency = t.Cfg.Section("gns-registrar").Key("registration_cost_currency").MustString("EUR")
t.SuffixHint = t.Cfg.Section("gns-registrar").Key("suffix_hint").MustString("example.alt")
t.RootZoneName = t.Cfg.Section("gns-registrar").Key("root_zone_name").MustString("test")
t.GnunetUrl = t.Cfg.Section("gns-registrar").Key("gnunet_baseurl_private").MustString("http://localhost:7776")
resp, err := http.Get(t.GnunetUrl + "/identity/name/" + t.RootZoneName)
if err != nil {
fmt.Printf("Failed to get zone key")
return
}
defer resp.Body.Close()
if http.StatusNotFound == resp.StatusCode {
fmt.Printf("Zone not found.")
os.Exit(1)
} else if http.StatusOK == resp.StatusCode {
respData, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
os.Exit(1)
}
err = json.NewDecoder(bytes.NewReader(respData)).Decode(&identityResponse)
if err != nil {
fmt.Printf("Failed to get zone contents" + err.Error())
os.Exit(1)
}
t.RootZoneKey = identityResponse.Pubkey
} else {
fmt.Printf("Failed to get zone contents" + err.Error())
os.Exit(1)
}
merchURL := t.Cfg.Section("gns-registrar").Key("merchant_baseurl_private").MustString("http://merchant.gnsregistrar/instances/myInstance")
merchToken := t.Cfg.Section("gns-registrar").Key("merchant_token").MustString("secretAccessToken")
t.Merchant = merchant.NewMerchant(merchURL, merchToken)
t.setupHandlers()
}
|