client.go 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright 2016-2017 Vector Creations Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package gomatrixserverlib

import (
M
Mark Haines 已提交
19
	"bytes"
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"strings"
)

// A Client makes request to the federation listeners of matrix
// homeservers
type Client struct {
	client http.Client
}

// UserInfo represents information about a user.
type UserInfo struct {
	Sub string `json:"sub"`
}

// NewClient makes a new Client
func NewClient() *Client {
43 44 45 46 47 48 49 50
	return &Client{client: http.Client{Transport: newFederationTripper()}}
}

type federationTripper struct {
	transport http.RoundTripper
}

func newFederationTripper() *federationTripper {
51
	// TODO: Verify ceritificates
52
	return &federationTripper{
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
		transport: &http.Transport{
			// Set our own DialTLS function to avoid the default net/http SNI.
			// By default net/http and crypto/tls set the SNI to the target host.
			// By avoiding the default implementation we can keep the ServerName
			// as the empty string so that crypto/tls doesn't add SNI.
			DialTLS: func(network, addr string) (net.Conn, error) {
				rawconn, err := net.Dial(network, addr)
				if err != nil {
					return nil, err
				}
				// Wrap a raw connection ourselves since tls.Dial defaults the SNI
				conn := tls.Client(rawconn, &tls.Config{
					ServerName: "",
					// TODO: We should be checking that the TLS certificate we see here matches
					//       one of the allowed SHA-256 fingerprints for the server.
					InsecureSkipVerify: true,
				})
				if err := conn.Handshake(); err != nil {
					return nil, err
				}
				return conn, nil
			},
		},
	}
}

func makeHTTPSURL(u *url.URL, addr string) (httpsURL url.URL) {
	httpsURL = *u
	httpsURL.Scheme = "https"
	httpsURL.Host = addr
	return
}

func (f *federationTripper) RoundTrip(r *http.Request) (*http.Response, error) {
M
Mark Haines 已提交
87 88
	serverName := ServerName(r.URL.Host)
	dnsResult, err := LookupServer(serverName)
89 90 91 92 93 94 95 96 97 98 99 100
	if err != nil {
		return nil, err
	}
	var resp *http.Response
	for _, addr := range dnsResult.Addrs {
		u := makeHTTPSURL(r.URL, addr)
		r.URL = &u
		resp, err = f.transport.RoundTrip(r)
		if err == nil {
			return resp, nil
		}
	}
M
Mark Haines 已提交
101
	return nil, fmt.Errorf("no address found for matrix host %v", serverName)
102 103 104 105
}

// LookupUserInfo gets information about a user from a given matrix homeserver
// using a bearer access token.
M
Mark Haines 已提交
106
func (fc *Client) LookupUserInfo(matrixServer ServerName, token string) (u UserInfo, err error) {
107 108
	url := url.URL{
		Scheme:   "matrix",
M
Mark Haines 已提交
109
		Host:     string(matrixServer),
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
		Path:     "/_matrix/federation/v1/openid/userinfo",
		RawQuery: url.Values{"access_token": []string{token}}.Encode(),
	}

	var response *http.Response
	response, err = fc.client.Get(url.String())
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		var errorOutput []byte
		errorOutput, err = ioutil.ReadAll(response.Body)
		if err != nil {
			return
		}
		err = fmt.Errorf("HTTP %d : %s", response.StatusCode, errorOutput)
		return
	}

	err = json.NewDecoder(response.Body).Decode(&u)
	if err != nil {
		return
	}

	userParts := strings.SplitN(u.Sub, ":", 2)
M
Mark Haines 已提交
138
	if len(userParts) != 2 || userParts[1] != string(matrixServer) {
139 140 141 142 143 144
		err = fmt.Errorf("userID doesn't match server name '%v' != '%v'", u.Sub, matrixServer)
		return
	}

	return
}
M
Mark Haines 已提交
145 146 147 148 149 150 151 152 153 154 155

// LookupServerKeys lookups up the keys for a matrix server from a matrix server.
// The first argument is the name of the matrix server to download the keys from.
// The second argument is a map from (server name, key ID) pairs to timestamps.
// The (server name, key ID) pair identifies the key to download.
// The timestamps tell the server when the keys need to be valid until.
// Perspective servers can use that timestamp to determine whether they can
// return a cached copy of the keys or whether they will need to retrieve a fresh
// copy of the keys.
// Returns the keys or an error if there was a problem talking to the server.
func (fc *Client) LookupServerKeys(
M
Mark Haines 已提交
156
	matrixServer ServerName, keyRequests map[PublicKeyRequest]Timestamp,
M
Mark Haines 已提交
157 158 159
) (map[PublicKeyRequest]ServerKeys, error) {
	url := url.URL{
		Scheme: "matrix",
M
Mark Haines 已提交
160
		Host:   string(matrixServer),
M
Mark Haines 已提交
161 162 163 164 165 166 167 168 169
		Path:   "/_matrix/key/v2/query",
	}

	// The request format is:
	// { "server_keys": { "<server_name>": { "<key_id>": { "minimum_valid_until_ts": <ts> }}}
	type keyreq struct {
		MinimumValidUntilTS Timestamp `json:"minimum_valid_until_ts"`
	}
	request := struct {
M
Mark Haines 已提交
170 171
		ServerKeyMap map[ServerName]map[KeyID]keyreq `json:"server_keys"`
	}{map[ServerName]map[KeyID]keyreq{}}
M
Mark Haines 已提交
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
	for k, ts := range keyRequests {
		server := request.ServerKeyMap[k.ServerName]
		if server == nil {
			server = map[KeyID]keyreq{}
			request.ServerKeyMap[k.ServerName] = server
		}
		server[k.KeyID] = keyreq{ts}
	}

	requestBytes, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}

	response, err := fc.client.Post(url.String(), "application/json", bytes.NewBuffer(requestBytes))
	if response != nil {
		defer response.Body.Close()
	}
	if err != nil {
		return nil, err
	}

	if response.StatusCode != 200 {
		var errorOutput []byte
		if errorOutput, err = ioutil.ReadAll(response.Body); err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("HTTP %d : %s", response.StatusCode, errorOutput)
	}

	var body struct {
		ServerKeyList []ServerKeys `json:"server_keys"`
	}
	if err = json.NewDecoder(response.Body).Decode(&body); err != nil {
		return nil, err
	}

	result := map[PublicKeyRequest]ServerKeys{}
	for _, keys := range body.ServerKeyList {
		keys.FromServer = matrixServer
		// TODO: What happens if the same key ID appears in multiple responses?
		// We should probably take the response with the highest valid_until_ts.
		for keyID := range keys.VerifyKeys {
			result[PublicKeyRequest{keys.ServerName, keyID}] = keys
		}
		for keyID := range keys.OldVerifyKeys {
			result[PublicKeyRequest{keys.ServerName, keyID}] = keys
		}
	}
	return result, nil
}
223 224 225 226 227 228 229 230 231 232 233

// CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error
func (fc *Client) CreateMediaDownloadRequest(matrixServer ServerName, mediaID string) (*http.Response, error) {
	requestURL := "matrix://" + string(matrixServer) + "/_matrix/media/v1/download/" + string(matrixServer) + "/" + mediaID
	resp, err := fc.client.Get(requestURL)
	if err != nil {
		return nil, err
	}

	return resp, nil
}