summaryrefslogtreecommitdiff
path: root/regress/lib/libressl/goressl/ressl_test.go
blob: 665d4e0cefbada165960088fbd056ac4a9731eab (plain)
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
package ressl

import (
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strings"
	"testing"
)

// createCAFile writes a PEM encoded version of the certificate out to a
// temporary file, for use by ressl.
func createCAFile(cert []byte) (string, error) {
	f, err := ioutil.TempFile("", "ressl")
	if err != nil {
		return "", fmt.Errorf("failed to create file: %v", err)
	}
	defer f.Close()
	block := &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: cert,
	}
	if err := pem.Encode(f, block); err != nil {
		return "", fmt.Errorf("failed to encode certificate: %v", err)
	}
	return f.Name(), nil
}

const httpContent = "Hello, ressl!"

func TestResslBasic(t *testing.T) {
	ts := httptest.NewTLSServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintln(w, httpContent)
			},
		),
	)
	defer ts.Close()

	u, err := url.Parse(ts.URL)
	if err != nil {
		t.Fatalf("Failed to parse URL %q: %v", ts.URL, err)
	}

	caFile, err := createCAFile(ts.TLS.Certificates[0].Certificate[0])
	if err != nil {
		t.Fatalf("Failed to create CA file: %v", err)
	}
	defer os.Remove(caFile)

	if err := Init(); err != nil {
		t.Fatal(err)
	}

	cfg, err := NewConfig()
	if err != nil {
		t.Fatal(err)
	}
	defer cfg.Free()
	cfg.SetCAFile(caFile)

	ssl, err := New(cfg)
	if err != nil {
		t.Fatal(err)
	}
	defer ssl.Free()

	t.Logf("Connecting to %s", u.Host)

	if err := ssl.Connect(u.Host, ""); err != nil {
		t.Fatal(err)
	}
	defer ssl.Close()

	n, err := ssl.Write([]byte("GET / HTTP/1.0\n\n"))
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("Wrote %d bytes...", n)

	buf := make([]byte, 1024)
	n, err = ssl.Read(buf)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("Read %d bytes...", n)

	if !strings.Contains(string(buf), httpContent) {
		t.Errorf("Response does not contain %q", httpContent)
	}

	if err := ssl.Close(); err != nil {
		t.Fatal(err)
	}
}