This repository has been archived by the owner on Oct 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
233 lines (208 loc) · 6.36 KB
/
client.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// client.go - Katzenpost client library
// Copyright (C) 2018 David Stainton.
//
// This program 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.
//
// This program 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/>.
// Package client provides a Katzenpost client library.
package client
import (
"context"
"errors"
"fmt"
mrand "math/rand"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
"github.com/katzenpost/client/config"
"github.com/katzenpost/core/crypto/ecdh"
"github.com/katzenpost/core/crypto/rand"
"github.com/katzenpost/core/epochtime"
"github.com/katzenpost/core/log"
"github.com/katzenpost/core/pki"
registration "github.com/katzenpost/registration_client"
"gopkg.in/op/go-logging.v1"
)
const (
initialPKIConsensusTimeout = 45 * time.Second
)
func AutoRegisterRandomClient(cfg *config.Config) (*config.Config, *ecdh.PrivateKey, error) {
// Retrieve a copy of the PKI consensus document.
logFilePath := ""
backendLog, err := log.New(logFilePath, "DEBUG", false)
if err != nil {
return nil, nil, err
}
proxyCfg := cfg.UpstreamProxyConfig()
pkiClient, err := cfg.NewPKIClient(backendLog, proxyCfg)
if err != nil {
return nil, nil, err
}
currentEpoch, _, _ := epochtime.FromUnix(time.Now().Unix())
ctx, cancel := context.WithTimeout(context.Background(), initialPKIConsensusTimeout)
defer cancel()
doc, _, err := pkiClient.Get(ctx, currentEpoch)
if err != nil {
return nil, nil, err
}
// Pick a registration Provider.
registerProviders := []*pki.MixDescriptor{}
for _, provider := range doc.Providers {
if provider.RegistrationHTTPAddresses != nil {
registerProviders = append(registerProviders, provider)
}
}
if len(registerProviders) == 0 {
return nil, nil, errors.New("zero registration Providers found in the consensus")
}
mrand.Seed(time.Now().UTC().UnixNano())
registrationProvider := registerProviders[mrand.Intn(len(registerProviders))]
// Register with that Provider.
fmt.Println("registering client with mixnet Provider")
linkKey, err := ecdh.NewKeypair(rand.Reader)
if err != nil {
return nil, nil, err
}
account := &config.Account{
User: fmt.Sprintf("%x", linkKey.PublicKey().Bytes()),
Provider: registrationProvider.Name,
ProviderKeyPin: registrationProvider.IdentityKey,
}
// try to pick a registration address using a prefered transport
var addr string
loop0:
for _, t := range cfg.Debug.PreferedTransports {
for _, v := range registrationProvider.RegistrationHTTPAddresses {
if u, err := url.Parse(v); err == nil {
if strings.HasSuffix(u.Hostname(), string(t)) {
addr = v
break loop0
}
}
}
}
// default if there was no transport found with the prefered transport
if addr == "" {
addr = registrationProvider.RegistrationHTTPAddresses[0]
}
u, err := url.Parse(addr)
if err != nil {
return nil, nil, err
}
cfgRegistration := &config.Registration{
Address: u.Host,
Options: ®istration.Options{
Scheme: u.Scheme,
UseSocks: strings.HasPrefix(cfg.UpstreamProxy.Type, "socks"),
SocksNetwork: cfg.UpstreamProxy.Network,
SocksAddress: cfg.UpstreamProxy.Address,
},
}
cfg.Account = account
cfg.Registration = cfgRegistration
err = RegisterClient(cfg, linkKey.PublicKey())
if err != nil {
return nil, nil, err
}
return cfg, linkKey, nil
}
func RegisterClient(cfg *config.Config, linkKey *ecdh.PublicKey) error {
client, err := registration.New(cfg.Registration.Address, cfg.Registration.Options)
if err != nil {
return err
}
err = client.RegisterAccountWithLinkKey(cfg.Account.User, linkKey)
return err
}
// Client handles sending and receiving messages over the mix network
type Client struct {
cfg *config.Config
logBackend *log.Backend
log *logging.Logger
fatalErrCh chan error
haltedCh chan interface{}
haltOnce *sync.Once
session *Session
}
func (c *Client) Provider() string {
return c.cfg.Account.Provider
}
func (c *Client) initLogging() error {
f := c.cfg.Logging.File
if !c.cfg.Logging.Disable && c.cfg.Logging.File != "" {
if !filepath.IsAbs(f) {
return errors.New("log file path must be absolute path")
}
}
var err error
c.logBackend, err = log.New(f, c.cfg.Logging.Level, c.cfg.Logging.Disable)
if err == nil {
c.log = c.logBackend.GetLogger("katzenpost/client")
}
return err
}
func (c *Client) GetBackendLog() *log.Backend {
return c.logBackend
}
// GetLogger returns a new logger with the given name.
func (c *Client) GetLogger(name string) *logging.Logger {
return c.logBackend.GetLogger(name)
}
// Shutdown cleanly shuts down a given Client instance.
func (c *Client) Shutdown() {
c.haltOnce.Do(func() { c.halt() })
}
// Wait waits till the Client is terminated for any reason.
func (c *Client) Wait() {
<-c.haltedCh
}
func (c *Client) halt() {
c.log.Noticef("Starting graceful shutdown.")
if c.session != nil {
c.session.Shutdown()
}
close(c.fatalErrCh)
close(c.haltedCh)
}
// NewSession creates and returns a new session or an error.
func (c *Client) NewSession(linkKey *ecdh.PrivateKey) (*Session, error) {
var err error
timeout := time.Duration(c.cfg.Debug.SessionDialTimeout) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
c.session, err = NewSession(ctx, c.fatalErrCh, c.logBackend, c.cfg, linkKey)
return c.session, err
}
// New creates a new Client with the provided configuration.
func New(cfg *config.Config) (*Client, error) {
c := new(Client)
c.cfg = cfg
c.fatalErrCh = make(chan error)
c.haltedCh = make(chan interface{})
c.haltOnce = new(sync.Once)
if err := c.initLogging(); err != nil {
return nil, err
}
c.log.Noticef("😼 Katzenpost is still pre-alpha. DO NOT DEPEND ON IT FOR STRONG SECURITY OR ANONYMITY. 😼")
// Start the fatal error watcher.
go func() {
err, ok := <-c.fatalErrCh
if !ok {
return
}
c.log.Warningf("Shutting down due to error: %v", err)
c.Shutdown()
}()
return c, nil
}