summaryrefslogtreecommitdiffstats
path: root/internal/relay/relay.go
blob: 54d45714263eae828e034034317e2c47c2a00905 (plain) (blame)
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
package relay

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
	"nymdrop/internal/nym"
)

// One base64 layer remains between the raw file and the wire: the browser
// client base64-encodes the file into the plaintext before encrypting (see
// static/crypto.js, ~4/3 inflation). nym.Client.Send used to base64-encode
// the whole ciphertext a second time to embed it in a JSON message for the
// local nym-client's WebSocket control channel; it now sends the raw bytes
// via nym-client's binary protocol instead, so that second inflation is
// gone. The remaining ~4/3 inflation is still bounded above by nym-client's
// own hardcoded 16MB WebSocket message limit. This cap (11MB) predates the
// binary-protocol fix and still reflects the old two-layer math (safe raw
// file size ~8MB) — raising it towards the ~16MB/1.33 headroom the fix
// actually unlocked is a deliberate follow-up, not done here.
const maxPayloadBytes = 11 * 1024 * 1024 // 11 MB wire

// Relay receives ciphertext and forwards it through Nym. Nothing is written to disk.
type Relay struct {
	nym *nym.Client
}

func New(client *nym.Client) *Relay {
	return &Relay{nym: client}
}

// Forward reads ciphertext from r, sends it over Nym, then zeros the buffer.
func (r *Relay) Forward(body io.Reader) error {
	buf := make([]byte, maxPayloadBytes)
	n, err := io.ReadFull(body, buf)
	if err != nil && err != io.ErrUnexpectedEOF {
		return fmt.Errorf("read payload: %w", err)
	}
	payload := buf[:n]
	defer zeroBytes(payload)

	// Prepend a random nonce so identical submissions look different on the wire.
	nonce := make([]byte, 16)
	if _, err := rand.Read(nonce); err != nil {
		return fmt.Errorf("nonce: %w", err)
	}
	packet := append([]byte(hex.EncodeToString(nonce)+":"), payload...)
	defer zeroBytes(packet)

	return r.nym.Send(packet)
}

func zeroBytes(b []byte) {
	for i := range b {
		b[i] = 0
	}
}