forked from btcsuite/btcwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
2949 lines (2571 loc) · 87.1 KB
/
rpcserver.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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013, 2014 Conformal Systems LLC <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package main
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/btcjson/btcws"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/websocket"
"github.com/soapboxsys/ombwallet/chain"
"github.com/soapboxsys/ombwallet/txstore"
"github.com/soapboxsys/ombwallet/waddrmgr"
// NOTICE the crucial import
_ "github.com/soapboxsys/ombudslib/rpcexten"
)
// Error types to simplify the reporting of specific categories of
// errors, and their btcjson.Error creation.
type (
// DeserializationError describes a failed deserializaion due to bad
// user input. It cooresponds to btcjson.ErrDeserialization.
DeserializationError struct {
error
}
// InvalidParameterError describes an invalid parameter passed by
// the user. It cooresponds to btcjson.ErrInvalidParameter.
InvalidParameterError struct {
error
}
// ParseError describes a failed parse due to bad user input. It
// cooresponds to btcjson.ErrParse.
ParseError struct {
error
}
// InvalidAddressOrKeyError describes a parse, network mismatch, or
// missing address error when decoding or validating an address or
// key. It cooresponds to btcjson.ErrInvalidAddressOrKey.
InvalidAddressOrKeyError struct {
error
}
)
// Errors variables that are defined once here to avoid duplication below.
var (
ErrNeedPositiveAmount = InvalidParameterError{
errors.New("amount must be positive"),
}
ErrNeedPositiveMinconf = InvalidParameterError{
errors.New("minconf must be positive"),
}
ErrAddressNotInWallet = InvalidAddressOrKeyError{
errors.New("address not found in wallet"),
}
ErrNoAccountSupport = btcjson.Error{
Code: btcjson.ErrWalletInvalidAccountName.Code,
Message: "btcwallet does not support non-default accounts",
}
ErrUnloadedWallet = btcjson.Error{
Code: btcjson.ErrWallet.Code,
Message: "Request requires a wallet but wallet has not loaded yet",
}
ErrNeedsChainSvr = btcjson.Error{
Code: btcjson.ErrWallet.Code,
Message: "Request requires chain connected chain server",
}
)
// TODO(jrick): There are several error paths which 'replace' various errors
// with a more appropiate error from the btcjson package. Create a map of
// these replacements so they can be handled once after an RPC handler has
// returned and before the error is marshaled.
// checkAccountName verifies that the passed account name is for the default
// account or '*' to represent all accounts. This is necessary to return
// errors to RPC clients for invalid account names, as account support is
// currently missing from btcwallet.
func checkAccountName(account string) error {
if account != "" && account != "*" {
return ErrNoAccountSupport
}
return nil
}
// checkDefaultAccount verifies that the passed account name is the default
// account. This is necessary to return errors to RPC clients for invalid
// account names, as account support is currently missing from btcwallet.
func checkDefaultAccount(account string) error {
if account != "" {
return ErrNoAccountSupport
}
return nil
}
type websocketClient struct {
conn *websocket.Conn
authenticated bool
remoteAddr string
allRequests chan []byte
responses chan []byte
quit chan struct{} // closed on disconnect
wg sync.WaitGroup
}
func newWebsocketClient(c *websocket.Conn, authenticated bool, remoteAddr string) *websocketClient {
return &websocketClient{
conn: c,
authenticated: authenticated,
remoteAddr: remoteAddr,
allRequests: make(chan []byte),
responses: make(chan []byte),
quit: make(chan struct{}),
}
}
func (c *websocketClient) send(b []byte) error {
select {
case c.responses <- b:
return nil
case <-c.quit:
return errors.New("websocket client disconnected")
}
}
// isManagerLockedError returns whether or not the passed error is due to the
// address manager being locked.
func isManagerLockedError(err error) bool {
merr, ok := err.(waddrmgr.ManagerError)
return ok && merr.ErrorCode == waddrmgr.ErrLocked
}
// isManagerWrongPassphraseError returns whether or not the passed error is due
// to the address manager being provided with an invalid passprhase.
func isManagerWrongPassphraseError(err error) bool {
merr, ok := err.(waddrmgr.ManagerError)
return ok && merr.ErrorCode == waddrmgr.ErrWrongPassphrase
}
// isManagerDuplicateError returns whether or not the passed error is due to a
// duplicate item being provided to the address manager.
func isManagerDuplicateError(err error) bool {
merr, ok := err.(waddrmgr.ManagerError)
if !ok {
return false
}
return merr.ErrorCode == waddrmgr.ErrDuplicate
}
// parseListeners splits the list of listen addresses passed in addrs into
// IPv4 and IPv6 slices and returns them. This allows easy creation of the
// listeners on the correct interface "tcp4" and "tcp6". It also properly
// detects addresses which apply to "all interfaces" and adds the address to
// both slices.
func parseListeners(addrs []string) ([]string, []string, error) {
ipv4ListenAddrs := make([]string, 0, len(addrs)*2)
ipv6ListenAddrs := make([]string, 0, len(addrs)*2)
for _, addr := range addrs {
host, _, err := net.SplitHostPort(addr)
if err != nil {
// Shouldn't happen due to already being normalized.
return nil, nil, err
}
// Empty host or host of * on plan9 is both IPv4 and IPv6.
if host == "" || (host == "*" && runtime.GOOS == "plan9") {
ipv4ListenAddrs = append(ipv4ListenAddrs, addr)
ipv6ListenAddrs = append(ipv6ListenAddrs, addr)
continue
}
// Parse the IP.
ip := net.ParseIP(host)
if ip == nil {
return nil, nil, fmt.Errorf("'%s' is not a valid IP "+
"address", host)
}
// To4 returns nil when the IP is not an IPv4 address, so use
// this determine the address type.
if ip.To4() == nil {
ipv6ListenAddrs = append(ipv6ListenAddrs, addr)
} else {
ipv4ListenAddrs = append(ipv4ListenAddrs, addr)
}
}
return ipv4ListenAddrs, ipv6ListenAddrs, nil
}
// genCertPair generates a key/cert pair to the paths provided.
func genCertPair(certFile, keyFile string) error {
log.Infof("Generating TLS certificates...")
// Create directories for cert and key files if they do not yet exist.
certDir, _ := filepath.Split(certFile)
keyDir, _ := filepath.Split(keyFile)
if err := os.MkdirAll(certDir, 0700); err != nil {
return err
}
if err := os.MkdirAll(keyDir, 0700); err != nil {
return err
}
// Generate cert pair.
org := "btcwallet autogenerated cert"
validUntil := time.Now().Add(time.Hour * 24 * 365 * 10)
cert, key, err := btcutil.NewTLSCertPair(org, validUntil, nil)
if err != nil {
return err
}
// Write cert and key files.
if err = ioutil.WriteFile(certFile, cert, 0666); err != nil {
return err
}
if err = ioutil.WriteFile(keyFile, key, 0600); err != nil {
if rmErr := os.Remove(certFile); rmErr != nil {
log.Warnf("Cannot remove written certificates: %v", rmErr)
}
return err
}
log.Info("Done generating TLS certificates")
return nil
}
// rpcServer holds the items the RPC server may need to access (auth,
// config, shutdown, etc.)
type rpcServer struct {
wallet *Wallet
chainSvr *chain.Client
createOK bool
handlerLookup func(string) (requestHandler, bool)
handlerLock sync.Locker
listeners []net.Listener
authsha [sha256.Size]byte
upgrader websocket.Upgrader
maxPostClients int64 // Max concurrent HTTP POST clients.
maxWebsocketClients int64 // Max concurrent websocket clients.
// Channels to register or unregister a websocket client for
// websocket notifications.
registerWSC chan *websocketClient
unregisterWSC chan *websocketClient
// Channels read from other components from which notifications are
// created.
connectedBlocks <-chan waddrmgr.BlockStamp
disconnectedBlocks <-chan waddrmgr.BlockStamp
newCredits <-chan txstore.Credit
newDebits <-chan txstore.Debits
minedCredits <-chan txstore.Credit
minedDebits <-chan txstore.Debits
managerLocked <-chan bool
confirmedBalance <-chan btcutil.Amount
unconfirmedBalance <-chan btcutil.Amount
//chainServerConnected <-chan bool
registerWalletNtfns chan struct{}
// enqueueNotification and dequeueNotification handle both sides of an
// infinitly growing queue for websocket client notifications.
enqueueNotification chan wsClientNotification
dequeueNotification chan wsClientNotification
// notificationHandlerQuit is closed when the notification handler
// goroutine shuts down. After this is closed, no more notifications
// will be sent to any websocket client response channel.
notificationHandlerQuit chan struct{}
wg sync.WaitGroup
quit chan struct{}
quitMtx sync.Mutex
}
// newRPCServer creates a new server for serving RPC client connections, both
// HTTP POST and websocket.
func newRPCServer(listenAddrs []string, maxPost, maxWebsockets int64) (*rpcServer, error) {
login := cfg.Username + ":" + cfg.Password
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
s := rpcServer{
handlerLookup: unloadedWalletHandlerFunc,
handlerLock: new(sync.Mutex),
authsha: sha256.Sum256([]byte(auth)),
maxPostClients: maxPost,
maxWebsocketClients: maxWebsockets,
upgrader: websocket.Upgrader{
// Allow all origins.
CheckOrigin: func(r *http.Request) bool { return true },
},
registerWSC: make(chan *websocketClient),
unregisterWSC: make(chan *websocketClient),
registerWalletNtfns: make(chan struct{}),
enqueueNotification: make(chan wsClientNotification),
dequeueNotification: make(chan wsClientNotification),
notificationHandlerQuit: make(chan struct{}),
quit: make(chan struct{}),
}
// Setup TLS if not disabled.
listenFunc := net.Listen
if !cfg.DisableServerTLS {
// Check for existence of cert file and key file
if !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {
// if both files do not exist, we generate them.
err := genCertPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
}
keypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{keypair},
MinVersion: tls.VersionTLS12,
}
// Change the standard net.Listen function to the tls one.
listenFunc = func(net string, laddr string) (net.Listener, error) {
return tls.Listen(net, laddr, &tlsConfig)
}
} else {
log.Info("Server TLS is disabled")
}
ipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)
if err != nil {
return nil, err
}
listeners := make([]net.Listener, 0,
len(ipv6ListenAddrs)+len(ipv4ListenAddrs))
for _, addr := range ipv4ListenAddrs {
listener, err := listenFunc("tcp4", addr)
if err != nil {
log.Warnf("RPCS: Can't listen on %s: %v", addr,
err)
continue
}
listeners = append(listeners, listener)
}
for _, addr := range ipv6ListenAddrs {
listener, err := listenFunc("tcp6", addr)
if err != nil {
log.Warnf("RPCS: Can't listen on %s: %v", addr,
err)
continue
}
listeners = append(listeners, listener)
}
if len(listeners) == 0 {
return nil, errors.New("no valid listen address")
}
s.listeners = listeners
return &s, nil
}
// Start starts a HTTP server to provide standard RPC and extension
// websocket connections for any number of btcwallet clients.
func (s *rpcServer) Start() {
s.wg.Add(3)
go s.notificationListener()
go s.notificationQueue()
go s.notificationHandler()
log.Trace("Starting RPC server")
serveMux := http.NewServeMux()
const rpcAuthTimeoutSeconds = 10
httpServer := &http.Server{
Handler: serveMux,
// Timeout connections which don't complete the initial
// handshake within the allowed timeframe.
ReadTimeout: time.Second * rpcAuthTimeoutSeconds,
}
serveMux.Handle("/", throttledFn(s.maxPostClients,
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/json")
r.Close = true
if err := s.checkAuthHeader(r); err != nil {
log.Warnf("Unauthorized client connection attempt")
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
s.wg.Add(1)
s.PostClientRPC(w, r)
s.wg.Done()
}))
serveMux.Handle("/ws", throttledFn(s.maxWebsocketClients,
func(w http.ResponseWriter, r *http.Request) {
authenticated := false
switch s.checkAuthHeader(r) {
case nil:
authenticated = true
case ErrNoAuth:
// nothing
default:
// If auth was supplied but incorrect, rather than simply
// being missing, immediately terminate the connection.
log.Warnf("Disconnecting improperly authorized " +
"websocket client")
http.Error(w, "401 Unauthorized.", http.StatusUnauthorized)
return
}
conn, err := s.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("Cannot websocket upgrade client %s: %v",
r.RemoteAddr, err)
return
}
wsc := newWebsocketClient(conn, authenticated, r.RemoteAddr)
s.WebsocketClientRPC(wsc)
}))
for _, listener := range s.listeners {
s.wg.Add(1)
go func(listener net.Listener) {
log.Infof("RPCS: RPC server listening on %s", listener.Addr())
_ = httpServer.Serve(listener)
log.Tracef("RPCS: RPC listener done for %s", listener.Addr())
s.wg.Done()
}(listener)
}
}
// Stop gracefully shuts down the rpc server by stopping and disconnecting all
// clients, disconnecting the chain server connection, and closing the wallet's
// account files.
func (s *rpcServer) Stop() {
s.quitMtx.Lock()
defer s.quitMtx.Unlock()
select {
case <-s.quit:
return
default:
}
log.Warn("Server shutting down")
// Stop the connected wallet and chain server, if any.
s.handlerLock.Lock()
if s.wallet != nil {
s.wallet.Stop()
}
if s.chainSvr != nil {
s.chainSvr.Stop()
}
s.handlerLock.Unlock()
// Stop all the listeners.
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
log.Errorf("Cannot close listener %s: %v",
listener.Addr(), err)
}
}
// Signal the remaining goroutines to stop.
close(s.quit)
}
func (s *rpcServer) WaitForShutdown() {
// First wait for the wallet and chain server to stop, if they
// were ever set.
s.handlerLock.Lock()
if s.wallet != nil {
s.wallet.WaitForShutdown()
}
if s.chainSvr != nil {
s.chainSvr.WaitForShutdown()
}
s.handlerLock.Unlock()
s.wg.Wait()
}
type noopLocker struct{}
func (noopLocker) Lock() {}
func (noopLocker) Unlock() {}
// SetWallet sets the wallet dependency component needed to run a fully
// functional bitcoin wallet RPC server. If wallet is nil, this informs the
// server that the createencryptedwallet RPC method is valid and must be called
// by a client before any other wallet methods are allowed.
func (s *rpcServer) SetWallet(wallet *Wallet) {
s.handlerLock.Lock()
defer s.handlerLock.Unlock()
if wallet == nil {
s.handlerLookup = missingWalletHandlerFunc
s.createOK = true
return
}
s.wallet = wallet
s.registerWalletNtfns <- struct{}{}
if s.chainSvr != nil {
// If the chain server rpc client is also set, there's no reason
// to keep the mutex around. Make the locker simply execute
// noops instead.
s.handlerLock = noopLocker{}
// With both the wallet and chain server set, all handlers are
// ok to run.
s.handlerLookup = lookupAnyHandler
}
}
// SetChainServer sets the chain server client component needed to run a fully
// functional bitcoin wallet RPC server. This should be set even before the
// client is connected, as any request handlers should return the error for
// a never connected client, rather than panicking (or never being looked up)
// if the client was never conneceted and added.
func (s *rpcServer) SetChainServer(chainSvr *chain.Client) {
s.handlerLock.Lock()
defer s.handlerLock.Unlock()
s.chainSvr = chainSvr
if s.wallet != nil {
// If the wallet had already been set, there's no reason to keep
// the mutex around. Make the locker simply execute noops
// instead.
s.handlerLock = noopLocker{}
// With both the chain server and wallet set, all handlers are
// ok to run.
s.handlerLookup = lookupAnyHandler
}
}
// HandlerClosure creates a closure function for handling requests of the given
// method. This may be a request that is handled directly by btcwallet, or
// a chain server request that is handled by passing the request down to btcd.
//
// NOTE: These handlers do not handle special cases, such as the authenticate
// method. Each of these must be checked beforehand (the method is already
// known) and handled accordingly.
func (s *rpcServer) HandlerClosure(method string) requestHandlerClosure {
s.handlerLock.Lock()
defer s.handlerLock.Unlock()
// With the lock held, make copies of these pointers for the closure.
wallet := s.wallet
chainSvr := s.chainSvr
if handler, ok := s.handlerLookup(method); ok {
return func(request []byte, raw *rawRequest) btcjson.Reply {
cmd, err := btcjson.ParseMarshaledCmd(request)
if err != nil {
return makeResponse(raw.ID, nil,
btcjson.ErrInvalidRequest)
}
result, err := handler(wallet, chainSvr, cmd)
return makeResponse(raw.ID, result, err)
}
}
return func(request []byte, raw *rawRequest) btcjson.Reply {
if chainSvr == nil {
err := btcjson.Error{
Code: -1,
Message: "Chain server is disconnected",
}
return makeResponse(raw.ID, nil, err)
}
res, err := chainSvr.RawRequest(raw.Method, raw.Params)
// The raw result will only marshal correctly if called with the
// MarshalJSON method, and that method requires a pointer receiver.
return makeResponse(raw.ID, &res, err)
}
}
// ErrNoAuth represents an error where authentication could not succeed
// due to a missing Authorization HTTP header.
var ErrNoAuth = errors.New("no auth")
// checkAuthHeader checks the HTTP Basic authentication supplied by a client
// in the HTTP request r. It errors with ErrNoAuth if the request does not
// contain the Authorization header, or another non-nil error if the
// authentication was provided but incorrect.
//
// This check is time-constant.
func (s *rpcServer) checkAuthHeader(r *http.Request) error {
authhdr := r.Header["Authorization"]
if len(authhdr) == 0 {
return ErrNoAuth
}
authsha := sha256.Sum256([]byte(authhdr[0]))
cmp := subtle.ConstantTimeCompare(authsha[:], s.authsha[:])
if cmp != 1 {
return errors.New("bad auth")
}
return nil
}
// throttledFn wraps an http.HandlerFunc with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed.
func throttledFn(threshold int64, f http.HandlerFunc) http.Handler {
return throttled(threshold, f)
}
// throttled wraps an http.Handler with throttling of concurrent active
// clients by responding with an HTTP 429 when the threshold is crossed.
func throttled(threshold int64, h http.Handler) http.Handler {
var active int64
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
current := atomic.AddInt64(&active, 1)
defer atomic.AddInt64(&active, -1)
if current-1 >= threshold {
log.Warnf("Reached threshold of %d concurrent active clients", threshold)
http.Error(w, "429 Too Many Requests", 429)
return
}
h.ServeHTTP(w, r)
})
}
type rawRequest struct {
// "jsonrpc" value isn't checked so we exclude it.
ID interface{} `json:"id"`
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
}
// String returns a sanitized string for the request which may be safely
// logged. It is intended to strip private keys, passphrases, and any other
// secrets from request parameters before they may be saved to a log file.
//
// This intentionally implements the fmt.Stringer interface to prevent
// accidental leaking of secrets.
func (r *rawRequest) String() string {
// These are considered unsafe to log, so sanitize parameters.
switch r.Method {
case "encryptwallet", "importprivkey", "importwallet",
"signrawtransaction", "walletpassphrase",
"walletpassphrasechange":
return fmt.Sprintf(`{"id":%v,"method":"%s","params":SANITIZED %d parameters}`,
r.ID, r.Method, len(r.Params))
}
return fmt.Sprintf(`{"id":%v,"method":"%s","params":%v}`, r.ID,
r.Method, r.Params)
}
// idPointer returns a pointer to the passed ID, or nil if the interface is nil.
// Interface pointers are usually a red flag of doing something incorrectly,
// but this is only implemented here to work around an oddity with btcjson,
// which uses empty interface pointers for response IDs.
func idPointer(id interface{}) (p *interface{}) {
if id != nil {
p = &id
}
return
}
// invalidAuth checks whether a websocket request is a valid (parsable)
// authenticate request and checks the supplied username and passphrase
// against the server auth.
func (s *rpcServer) invalidAuth(request []byte) bool {
cmd, err := btcjson.ParseMarshaledCmd(request)
if err != nil {
return false
}
authCmd, ok := cmd.(*btcws.AuthenticateCmd)
if !ok {
return false
}
// Check credentials.
login := authCmd.Username + ":" + authCmd.Passphrase
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
authSha := sha256.Sum256([]byte(auth))
return subtle.ConstantTimeCompare(authSha[:], s.authsha[:]) != 1
}
func (s *rpcServer) WebsocketClientRead(wsc *websocketClient) {
for {
_, request, err := wsc.conn.ReadMessage()
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
log.Warnf("Websocket receive failed from client %s: %v",
wsc.remoteAddr, err)
}
close(wsc.allRequests)
break
}
wsc.allRequests <- request
}
}
func (s *rpcServer) WebsocketClientRespond(wsc *websocketClient) {
// A for-select with a read of the quit channel is used instead of a
// for-range to provide clean shutdown. This is necessary due to
// WebsocketClientRead (which sends to the allRequests chan) not closing
// allRequests during shutdown if the remote websocket client is still
// connected.
out:
for {
select {
case request, ok := <-wsc.allRequests:
if !ok {
// client disconnected
break out
}
var raw rawRequest
if err := json.Unmarshal(request, &raw); err != nil {
if !wsc.authenticated {
// Disconnect immediately.
break out
}
resp := makeResponse(raw.ID, nil,
btcjson.ErrInvalidRequest)
mresp, err := json.Marshal(resp)
// We expect the marshal to succeed. If it
// doesn't, it indicates some non-marshalable
// type in the response.
if err != nil {
panic(err)
}
err = wsc.send(mresp)
if err != nil {
break out
}
continue
}
if raw.Method == "authenticate" {
if wsc.authenticated || s.invalidAuth(request) {
// Disconnect immediately.
break out
}
wsc.authenticated = true
resp := makeResponse(raw.ID, nil, nil)
// Expected to never fail.
mresp, err := json.Marshal(resp)
if err != nil {
panic(err)
}
err = wsc.send(mresp)
if err != nil {
break out
}
continue
}
if !wsc.authenticated {
// Disconnect immediately.
break out
}
switch raw.Method {
case "stop":
s.Stop()
resp := makeResponse(raw.ID,
"btcwallet stopping.", nil)
mresp, err := json.Marshal(resp)
// Expected to never fail.
if err != nil {
panic(err)
}
err = wsc.send(mresp)
if err != nil {
break out
}
default:
f := s.HandlerClosure(raw.Method)
wsc.wg.Add(1)
go func(request []byte, raw *rawRequest) {
resp := f(request, raw)
mresp, err := json.Marshal(resp)
if err != nil {
// Completely unexpected error, but have seen
// it happen regardless. Log the sanitized
// request and begin clean shutdown, panicing
// if shutdown takes too long.
log.Criticalf("Unexpected error marshaling "+
"response for request '%s': %v",
raw, err)
wsc.wg.Done()
s.Stop()
go func() {
time.Sleep(30 * time.Second)
panic("shutdown took too long")
}()
return
}
_ = wsc.send(mresp)
wsc.wg.Done()
}(request, &raw)
}
case <-s.quit:
break out
}
}
// Remove websocket client from notification group, or if the server is
// shutting down, wait until the notification handler has finished
// running. This is needed to ensure that no more notifications will be
// sent to the client's responses chan before it's closed below.
select {
case s.unregisterWSC <- wsc:
case <-s.quit:
<-s.notificationHandlerQuit
}
// allow client to disconnect after all handler goroutines are done
wsc.wg.Wait()
close(wsc.responses)
s.wg.Done()
}
func (s *rpcServer) WebsocketClientSend(wsc *websocketClient) {
const deadline time.Duration = 2 * time.Second
out:
for {
select {
case response, ok := <-wsc.responses:
if !ok {
// client disconnected
break out
}
err := wsc.conn.SetWriteDeadline(time.Now().Add(deadline))
if err != nil {
log.Warnf("Cannot set write deadline on "+
"client %s: %v", wsc.remoteAddr, err)
}
err = wsc.conn.WriteMessage(websocket.TextMessage,
response)
if err != nil {
log.Warnf("Failed websocket send to client "+
"%s: %v", wsc.remoteAddr, err)
break out
}
case <-s.quit:
break out
}
}
close(wsc.quit)
log.Infof("Disconnected websocket client %s", wsc.remoteAddr)
s.wg.Done()
}
// WebsocketClientRPC starts the goroutines to serve JSON-RPC requests and
// notifications over a websocket connection for a single client.
func (s *rpcServer) WebsocketClientRPC(wsc *websocketClient) {
log.Infof("New websocket client %s", wsc.remoteAddr)
// Clear the read deadline set before the websocket hijacked
// the connection.
if err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {
log.Warnf("Cannot remove read deadline: %v", err)
}
// Add client context so notifications duplicated to each
// client are received by this client.
select {
case s.registerWSC <- wsc:
case <-s.quit:
return
}
// WebsocketClientRead is intentionally not run with the waitgroup
// so it is ignored during shutdown. This is to prevent a hang during
// shutdown where the goroutine is blocked on a read of the
// websocket connection if the client is still connected.
go s.WebsocketClientRead(wsc)
s.wg.Add(2)
go s.WebsocketClientRespond(wsc)
go s.WebsocketClientSend(wsc)
<-wsc.quit
}
// maxRequestSize specifies the maximum number of bytes in the request body
// that may be read from a client. This is currently limited to 4MB.
const maxRequestSize = 1024 * 1024 * 4
// PostClientRPC processes and replies to a JSON-RPC client request.
func (s *rpcServer) PostClientRPC(w http.ResponseWriter, r *http.Request) {
body := http.MaxBytesReader(w, r.Body, maxRequestSize)
rpcRequest, err := ioutil.ReadAll(body)
if err != nil {
// TODO: what if the underlying reader errored?
http.Error(w, "413 Request Too Large.",
http.StatusRequestEntityTooLarge)
return
}
// First check whether wallet has a handler for this request's method.
// If unfound, the request is sent to the chain server for further
// processing. While checking the methods, disallow authenticate
// requests, as they are invalid for HTTP POST clients.
var raw rawRequest
err = json.Unmarshal(rpcRequest, &raw)
if err != nil {
resp := makeResponse(raw.ID, nil, btcjson.ErrInvalidRequest)
mresp, err := json.Marshal(resp)
// We expect the marshal to succeed. If it doesn't, it
// indicates some non-marshalable type in the response.
if err != nil {
panic(err)
}
_, err = w.Write(mresp)
if err != nil {
log.Warnf("Cannot write invalid request request to "+
"client: %v", err)
}
return
}
// Create the response and error from the request. Three special cases
// are handled for the authenticate and stop request methods.
var resp btcjson.Reply
switch raw.Method {
case "authenticate":
// Drop it.
return
case "stop":
s.Stop()
resp = makeResponse(raw.ID, "btcwallet stopping.", nil)
default:
resp = s.HandlerClosure(raw.Method)(rpcRequest, &raw)