File: post.go

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (63 lines) | stat: -rw-r--r-- 1,537 bytes parent folder | download
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
package fixchain

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/google/certificate-transparency/go/x509"
)

// PostChainToLog attempts to post the given chain to the Certificate
// Transparency log at the given url, using the given http client.
// PostChainToLog returns a FixError if it is unable to post the chain either
// because client.Post() failed, or the http response code returned was not 200.
// It is up to the caller to handle such errors appropriately.
func PostChainToLog(chain []*x509.Certificate, client *http.Client, url string) *FixError {
	// Format the chain ready to be posted to the log.
	type Chain struct {
		Chain [][]byte `json:"chain"`
	}
	var m Chain
	for _, c := range chain {
		m.Chain = append(m.Chain, c.Raw)
	}
	j, err := json.Marshal(m)
	if err != nil {
		log.Fatalf("Can't marshal: %s", err)
	}

	// Post the chain!
	resp, err := client.Post(url+"/ct/v1/add-chain", "application/json", bytes.NewReader(j))
	if err != nil {
		return &FixError{
			Type:  PostFailed,
			Chain: chain,
			Error: fmt.Errorf("can't post: %s", err),
		}
	}

	defer resp.Body.Close()
	jo, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return &FixError{
			Type:  LogPostFailed,
			Chain: chain,
			Error: fmt.Errorf("can't read response: %s", err),
		}
	}

	if resp.StatusCode != 200 {
		return &FixError{
			Type:  LogPostFailed,
			Chain: chain,
			Error: fmt.Errorf("can't handle response code %d: %s", resp.StatusCode, jo),
			Code:  resp.StatusCode,
		}
	}

	return nil
}