tls_client_cffi_src

package
v1.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: BSD-3-Clause Imports: 23 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

tls_client_cffi_src provides and manages a CFFI (C Foreign Function Interface) which allows code in other languages to interact with the module.

Index

Constants

View Source
const ErrWsReadTimeout = "websocket read timeout"

ErrWsReadTimeout is the error message returned by WsRead when no message arrived in time. The connection stays usable after it.

Variables

This section is empty.

Functions

func BuildResponse

func BuildResponse(sessionId string, withSession bool, resp *http.Response, cookies []*http.Cookie, input RequestInput) (Response, *TLSClientError)

BuildResponse constructs a client response from a given HTTP response. The client response can then be sent to the interface consumer.

func ClearSessionCache

func ClearSessionCache()

ClearSessionCache empties the client session storage.

func GetClient

func GetClient(sessionId string) (tls_client.HttpClient, error)

GetClient returns the client with the given sessionId from the client session storage. If there is no client with the given sessionId, it returns an error.

func RemoveSession

func RemoveSession(sessionId string)

RemoveSession deletes the client with the given sessionId from the client session storage.

func WsClose added in v1.17.0

func WsClose(input WsCloseInput) (WsCloseOutput, *TLSClientError)

WsClose closes an active WebSocket connection and removes it from the connection store. A WsRead blocked on the same connection returns with an error.

func WsConnect added in v1.17.0

func WsConnect(input WsConnectInput) (WsConnectOutput, *TLSClientError)

WsConnect establishes a WebSocket connection using either an existing session or an inline TLS client configuration. It returns a connectionId that must be used for subsequent WsRead, WsWrite, and WsClose calls.

When SessionId is provided the existing TLS client is reused as-is and never modified: the caller must have created that session with forceHttp1: true, otherwise the handshake fails when the server negotiates h2. When creating an inline client, HTTP/1.1 is enforced automatically because WebSocket requires it.

func WsRead added in v1.17.0

func WsRead(input WsReadInput) (WsReadOutput, *TLSClientError)

WsRead returns the next message from an active WebSocket connection, blocking until one arrives. If TimeoutMilliseconds is > 0 and nothing arrives in time, an ErrWsReadTimeout error is returned and the connection stays open. Any other read error (including a close from the peer) closes the connection and removes it from the store. Text messages are returned as-is; binary messages are base64-encoded.

func WsStats added in v1.17.0

func WsStats(input WsStatsInput) (WsStatsOutput, *TLSClientError)

WsStats returns a snapshot of a live connection for diagnosing silent stalls: message counters, how long ago the last message was read / written, how long writes block, whether a message is waiting for WsRead, and (linux) the kernel's TCP_INFO for the socket to the server or proxy. It never touches the wire. A connection that already failed or was closed is gone from the store.

func WsWrite added in v1.17.0

func WsWrite(input WsWriteInput) (WsWriteOutput, *TLSClientError)

WsWrite sends a message over an active WebSocket connection. Safe to call concurrently with WsRead and with other WsWrite calls on the same connection. A failed write closes the connection and removes it from the store. For binary messages (MessageType 2) the Data field must be base64-encoded.

Types

type AddCookiesToSessionInput

type AddCookiesToSessionInput struct {
	SessionId string   `json:"sessionId"`
	Url       string   `json:"url"`
	Cookies   []Cookie `json:"cookies"`
}

type CandidateCipherSuite added in v1.7.0

type CandidateCipherSuite struct {
	KdfId  string `json:"kdfId"`
	AeadId string `json:"aeadId"`
}

type CandidateCipherSuites added in v1.7.0

type CandidateCipherSuites []CandidateCipherSuite

func (CandidateCipherSuites) Translate added in v1.7.0

type Cookie struct {
	Expires  Timestamp `json:"expires"`
	Domain   string    `json:"domain"`
	Name     string    `json:"name"`
	Path     string    `json:"path"`
	Value    string    `json:"value"`
	MaxAge   int       `json:"maxAge"`
	Secure   bool      `json:"secure"`
	HttpOnly bool      `json:"httpOnly"`
}

type CookiesFromSessionOutput

type CookiesFromSessionOutput struct {
	Id      string   `json:"id"`
	Cookies []Cookie `json:"cookies"`
}

type CustomTlsClient

type CustomTlsClient struct {
	H2Settings                              map[string]uint32     `json:"h2Settings"`
	H2SettingsOrder                         []string              `json:"h2SettingsOrder"`
	H3Settings                              map[string]uint64     `json:"h3Settings"`
	H3SettingsOrder                         []string              `json:"h3SettingsOrder"`
	H3PseudoHeaderOrder                     []string              `json:"h3PseudoHeaderOrder"`
	HeaderPriority                          *PriorityParam        `json:"headerPriority"`
	CertCompressionAlgos                    []string              `json:"certCompressionAlgos"`
	Ja3String                               string                `json:"ja3String"`
	TrustAnchorsPayload                     string                `json:"trustAnchorsPayload"`
	KeyShareCurves                          []string              `json:"keyShareCurves"`
	ALPNProtocols                           []string              `json:"alpnProtocols"`
	ALPSProtocols                           []string              `json:"alpsProtocols"`
	ECHCandidatePayloads                    []uint16              `json:"ECHCandidatePayloads"`
	ECHCandidateCipherSuites                CandidateCipherSuites `json:"ECHCandidateCipherSuites"`
	PriorityFrames                          []PriorityFrames      `json:"priorityFrames"`
	PseudoHeaderOrder                       []string              `json:"pseudoHeaderOrder"`
	SupportedDelegatedCredentialsAlgorithms []string              `json:"supportedDelegatedCredentialsAlgorithms"`
	SupportedSignatureAlgorithms            []string              `json:"supportedSignatureAlgorithms"`
	SupportedVersions                       []string              `json:"supportedVersions"`
	ConnectionFlow                          uint32                `json:"connectionFlow"`
	RecordSizeLimit                         uint16                `json:"recordSizeLimit"`
	StreamId                                uint32                `json:"streamId"`
	H3PriorityParam                         uint32                `json:"h3PriorityParam"`
	H3SendGreaseFrames                      bool                  `json:"h3SendGreaseFrames"`
	AllowHttp                               bool                  `json:"allowHttp"`
}

CustomTlsClient contains custom TLS specifications to construct a client from.

type DestroyOutput

type DestroyOutput struct {
	Id      string `json:"id"`
	Success bool   `json:"success"`
}

type DestroySessionInput

type DestroySessionInput struct {
	SessionId string `json:"sessionId"`
}

type GetCookiesFromSessionInput

type GetCookiesFromSessionInput struct {
	SessionId string `json:"sessionId"`
	Url       string `json:"url"`
}

type PriorityFrames

type PriorityFrames struct {
	PriorityParam PriorityParam `json:"priorityParam"`
	StreamID      uint32        `json:"streamID"`
}

type PriorityParam

type PriorityParam struct {
	StreamDep uint32 `json:"streamDep"`
	Exclusive bool   `json:"exclusive"`
	Weight    uint8  `json:"weight"`
}

type RequestInput

type RequestInput struct {
	CertificatePinningHosts     map[string][]string `json:"certificatePinningHosts"`
	CustomTlsClient             *CustomTlsClient    `json:"customTlsClient"`
	TransportOptions            *TransportOptions   `json:"transportOptions"`
	Headers                     map[string]string   `json:"headers"`
	DefaultHeaders              map[string][]string `json:"defaultHeaders"`
	ConnectHeaders              map[string][]string `json:"connectHeaders"`
	LocalAddress                *string             `json:"localAddress"`
	ServerNameOverwrite         *string             `json:"serverNameOverwrite"`
	ProxyUrl                    *string             `json:"proxyUrl"`
	RequestBody                 *string             `json:"requestBody"`
	RequestHostOverride         *string             `json:"requestHostOverride"`
	SessionId                   *string             `json:"sessionId"`
	StreamOutputBlockSize       *int                `json:"streamOutputBlockSize"`
	StreamOutputEOFSymbol       *string             `json:"streamOutputEOFSymbol"`
	StreamOutputPath            *string             `json:"streamOutputPath"`
	RequestMethod               string              `json:"requestMethod"`
	RequestUrl                  string              `json:"requestUrl"`
	TLSClientIdentifier         string              `json:"tlsClientIdentifier"`
	HeaderOrder                 []string            `json:"headerOrder"`
	RequestCookies              []Cookie            `json:"requestCookies"`
	TimeoutMilliseconds         int                 `json:"timeoutMilliseconds"`
	TimeoutSeconds              int                 `json:"timeoutSeconds"`
	CatchPanics                 bool                `json:"catchPanics"`
	FollowRedirects             bool                `json:"followRedirects"`
	ForceHttp1                  bool                `json:"forceHttp1"`
	DisableHttp3                bool                `json:"disableHttp3"`
	DisableSessionTickets       bool                `json:"disableSessionTickets"`
	WithProtocolRacing          bool                `json:"withProtocolRacing"`
	InsecureSkipVerify          bool                `json:"insecureSkipVerify"`
	IsByteRequest               bool                `json:"isByteRequest"`
	IsByteResponse              bool                `json:"isByteResponse"`
	IsRotatingProxy             bool                `json:"isRotatingProxy"`
	DisableIPV6                 bool                `json:"disableIPV6"`
	DisableIPV4                 bool                `json:"disableIPV4"`
	WithDebug                   bool                `json:"withDebug"`
	WithCustomCookieJar         bool                `json:"withCustomCookieJar"`
	WithoutCookieJar            bool                `json:"withoutCookieJar"`
	WithRandomTLSExtensionOrder bool                `json:"withRandomTLSExtensionOrder"`
}

RequestInput is the data a Python client can construct a client and request from.

type Response

type Response struct {
	Cookies      map[string]string   `json:"cookies"`
	Headers      map[string][]string `json:"headers"`
	Id           string              `json:"id"`
	Body         string              `json:"body"`
	SessionId    string              `json:"sessionId,omitempty"`
	Target       string              `json:"target"`
	UsedProtocol string              `json:"usedProtocol"`
	Status       int                 `json:"status"`
}

Response is the response that is sent back to the Python client.

type TLSClientError

type TLSClientError struct {
	// contains filtered or unexported fields
}

func BuildRequest

func BuildRequest(input RequestInput) (*http.Request, *TLSClientError)

BuildRequest constructs a HTTP request from a given RequestInput.

func CreateClient

func CreateClient(requestInput RequestInput) (client tls_client.HttpClient, sessionID string, withSession bool, clientErr *TLSClientError)

CreateClient creates a new client from a given RequestInput.

The RequestInput should only contain a TLSClientIdentifier or a CustomTlsClient. If both are provided, an error will be returned.

func NewTLSClientError

func NewTLSClientError(err error) *TLSClientError

func (*TLSClientError) Error

func (e *TLSClientError) Error() string

type Timestamp

type Timestamp struct {
	time.Time
}

func (*Timestamp) MarshalJSON added in v1.5.0

func (p *Timestamp) MarshalJSON() ([]byte, error)

func (*Timestamp) UnmarshalJSON

func (p *Timestamp) UnmarshalJSON(bytes []byte) error

type TransportOptions added in v1.5.0

type TransportOptions struct {
	// IdleConnTimeout is the maximum amount of time an idle (keep-alive)
	// connection will remain idle before closing itself. Zero means no limit.
	IdleConnTimeout        *time.Duration `json:"idleConnTimeout"`
	MaxIdleConns           int            `json:"maxIdleConns"`
	MaxIdleConnsPerHost    int            `json:"maxIdleConnsPerHost"`
	MaxConnsPerHost        int            `json:"maxConnsPerHost"`
	MaxResponseHeaderBytes int64          `json:"maxResponseHeaderBytes"` // Zero means to use a default limit.
	WriteBufferSize        int            `json:"writeBufferSize"`        // If zero, a default (currently 4KB) is used.
	ReadBufferSize         int            `json:"readBufferSize"`         // If zero, a default (currently 4KB) is used.
	DisableKeepAlives      bool           `json:"disableKeepAlives"`
	DisableCompression     bool           `json:"disableCompression"`
	// ReadIdleTimeout sends an HTTP/2 health-check PING when no frame has been
	// received for this long. Zero disables it.
	ReadIdleTimeout time.Duration `json:"readIdleTimeout"`
	// PingTimeout closes the connection when that PING is not acknowledged in
	// time. Zero means 15 seconds.
	PingTimeout time.Duration `json:"pingTimeout"`
	// ResponseHeaderTimeout is the time to wait for the response headers after
	// the request has been written, over HTTP/1.1 and HTTP/2. Zero means no
	// timeout.
	ResponseHeaderTimeout time.Duration `json:"responseHeaderTimeout"`
}

TransportOptions contains settings for the underlying http transport of the tls client

type WsCloseInput added in v1.17.0

type WsCloseInput struct {
	ConnectionId string `json:"connectionId"`
}

WsCloseInput contains the parameters for closing a WebSocket connection.

type WsCloseOutput added in v1.17.0

type WsCloseOutput struct {
	Id      string `json:"id"`
	Success bool   `json:"success"`
}

WsCloseOutput is returned after closing a WebSocket connection.

type WsConnectInput added in v1.17.0

type WsConnectInput struct {
	SessionId                    *string           `json:"sessionId"`
	CustomTlsClient              *CustomTlsClient  `json:"customTlsClient"`
	ProxyUrl                     *string           `json:"proxyUrl"`
	ServerNameOverwrite          *string           `json:"serverNameOverwrite"`
	Url                          string            `json:"url"`
	TLSClientIdentifier          string            `json:"tlsClientIdentifier"`
	Headers                      map[string]string `json:"headers"`
	HeaderOrder                  []string          `json:"headerOrder"`
	HandshakeTimeoutMilliseconds int               `json:"handshakeTimeoutMilliseconds"`
	ReadBufferSize               int               `json:"readBufferSize"`
	WriteBufferSize              int               `json:"writeBufferSize"`
	InsecureSkipVerify           bool              `json:"insecureSkipVerify"`
	WithRandomTLSExtensionOrder  bool              `json:"withRandomTLSExtensionOrder"`
	DisableIPV6                  bool              `json:"disableIPV6"`
	DisableIPV4                  bool              `json:"disableIPV4"`
}

WsConnectInput contains the parameters for establishing a WebSocket connection. Either SessionId (to reuse an existing TLS session) or TLSClientIdentifier / CustomTlsClient (to create an inline client) must be provided.

type WsConnectOutput added in v1.17.0

type WsConnectOutput struct {
	Id           string `json:"id"`
	ConnectionId string `json:"connectionId"`
	SessionId    string `json:"sessionId,omitempty"`
	Status       int    `json:"status"`
}

WsConnectOutput is returned after a successful WebSocket handshake.

type WsReadInput added in v1.17.0

type WsReadInput struct {
	ConnectionId        string `json:"connectionId"`
	TimeoutMilliseconds int    `json:"timeoutMilliseconds"`
}

WsReadInput contains the parameters for reading a single message from a WebSocket connection.

type WsReadOutput added in v1.17.0

type WsReadOutput struct {
	Id           string `json:"id"`
	ConnectionId string `json:"connectionId"`
	MessageType  int    `json:"messageType"`
	Data         string `json:"data"`
}

WsReadOutput contains a message received from a WebSocket connection. MessageType 1 = text, 2 = binary (Data is base64-encoded for binary messages).

type WsStatsInput added in v1.17.0

type WsStatsInput struct {
	ConnectionId string `json:"connectionId"`
}

WsStatsInput contains the parameters for reading a WebSocket connection's diagnostics.

type WsStatsOutput added in v1.17.0

type WsStatsOutput struct {
	Tcp                 *WsTcpInfo `json:"tcp,omitempty"`
	Id                  string     `json:"id"`
	ConnectionId        string     `json:"connectionId"`
	LocalAddr           string     `json:"localAddr"`
	RemoteAddr          string     `json:"remoteAddr"`
	AgeMs               int64      `json:"ageMs"`
	MessagesRead        int64      `json:"messagesRead"`
	MessagesWritten     int64      `json:"messagesWritten"`
	BytesRead           int64      `json:"bytesRead"`
	BytesWritten        int64      `json:"bytesWritten"`
	MsSinceLastRead     int64      `json:"msSinceLastRead"`
	MsSinceLastWrite    int64      `json:"msSinceLastWrite"`
	LastWriteDurationMs int64      `json:"lastWriteDurationMs"`
	MaxWriteDurationMs  int64      `json:"maxWriteDurationMs"`
	UnreadPending       bool       `json:"unreadPending"`
}

WsStatsOutput is a diagnostic snapshot of a WebSocket connection. Counters are application messages (not control frames). MsSince* are -1 when nothing was read / written yet.

type WsTcpInfo added in v1.17.0

type WsTcpInfo struct {
	State               uint8  `json:"state"` // 1 = ESTABLISHED
	Retransmits         uint8  `json:"retransmits"`
	Backoff             uint8  `json:"backoff"`
	RtoMs               uint32 `json:"rtoMs"`
	RttMs               uint32 `json:"rttMs"`
	Unacked             uint32 `json:"unacked"`
	Lost                uint32 `json:"lost"`
	TotalRetrans        uint32 `json:"totalRetrans"`
	NotsentBytes        uint32 `json:"notsentBytes"`
	MsSinceLastDataSent uint32 `json:"msSinceLastDataSent"`
	MsSinceLastDataRecv uint32 `json:"msSinceLastDataRecv"`
	MsSinceLastAckRecv  uint32 `json:"msSinceLastAckRecv"`
}

WsTcpInfo is the kernel's view of the TCP socket (linux TCP_INFO). With a proxy this is the connection to the proxy. Growing Unacked / Retransmits with a stale MsSinceLastAckRecv means our bytes are not being acknowledged: the path is dead even though writes still "succeed".

type WsWriteInput added in v1.17.0

type WsWriteInput struct {
	ConnectionId        string `json:"connectionId"`
	Data                string `json:"data"`
	MessageType         int    `json:"messageType"`
	TimeoutMilliseconds int    `json:"timeoutMilliseconds"`
}

WsWriteInput contains the parameters for sending a message over a WebSocket connection. For binary messages (MessageType 2), Data must be base64-encoded. TimeoutMilliseconds > 0 bounds how long the write may block (peer not reading, dead path); a write that times out closes the connection. 0 = no deadline.

type WsWriteOutput added in v1.17.0

type WsWriteOutput struct {
	Id           string `json:"id"`
	ConnectionId string `json:"connectionId"`
	Success      bool   `json:"success"`
}

WsWriteOutput is returned after sending a WebSocket message.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL