Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ jobs:
- name: Lint
uses: golangci/golangci-lint-action@v8
with:
version: v2.1.6
version: v2.15.0
6 changes: 3 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package simplesyslog

import (
"crypto/tls"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -60,8 +59,9 @@ type Client struct {
// - NewClient(ConnectionTCP, ":514")
// - NewClient(ConnectionTLS, "172.0.0.1:514")
// - NewClient(ConnectionHTTP, "https://example.com:8080/syslog")
func NewClient(connectionType ConnectionType, address string, tlsconfig *tls.Config) (*Client, error) {
connWriter, err := NewConnectionWriter(connectionType, address, tlsconfig)
// - NewClient(ConnectionTLS, "172.0.0.1:514", WithTLSConfig(config), WithTimeout(10*time.Second))
func NewClient(connectionType ConnectionType, address string, opts ...Option) (*Client, error) {
connWriter, err := NewConnectionWriter(connectionType, address, opts...)
if err != nil {
return nil, fmt.Errorf("could not create connection writer: %w", err)
}
Expand Down
24 changes: 21 additions & 3 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -81,7 +82,7 @@ func testNewClientUDP(t *testing.T) {
/*
* Send the message 'foo bar baz' to the syslog server
*/
client, err := NewClient(ConnectionUDP, host, nil)
client, err := NewClient(ConnectionUDP, host)
if err != nil {
sendErr <- fmt.Errorf("could not initialize server: %s", err)
return
Expand Down Expand Up @@ -140,7 +141,7 @@ func testNewClientTCP(t *testing.T, useTLS bool) {
if useTLS {
connectionType = ConnectionTLS
}
client, err := NewClient(connectionType, host, &tls.Config{InsecureSkipVerify: true})
client, err := NewClient(connectionType, host, WithTLSConfig(&tls.Config{InsecureSkipVerify: true}))
if err != nil {
sendErr <- fmt.Errorf("could not initialize server: %s", err)
return
Expand Down Expand Up @@ -239,7 +240,7 @@ func testNewClientHTTPSpecific(t *testing.T, sendFunc sendFuncType) {
/*
* Send the message 'foo bar baz' to the syslog server
*/
client, err := NewClient(ConnectionHTTP, ts.URL, tlsConfig)
client, err := NewClient(ConnectionHTTP, ts.URL, WithTLSConfig(tlsConfig))
if err != nil {
sendErr <- fmt.Errorf("could not initialize server: %s", err)
return
Expand Down Expand Up @@ -300,3 +301,20 @@ func init() {
MinVersion: tls.VersionTLS11,
}
}

func TestWithTimeout(t *testing.T) {
release := make(chan struct{})
ts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { <-release }))
defer ts.Close()
defer close(release)

client, err := NewClient(ConnectionHTTP, ts.URL, WithTimeout(50*time.Millisecond))
if err != nil {
t.Fatalf("could not create client: %s", err)
}
defer func() { _ = client.Close() }()
var netErr net.Error
if err := client.SendRaw("foo"); !errors.As(err, &netErr) || !netErr.Timeout() {
t.Fatalf("expected timeout error, got: %v", err)
}
}
56 changes: 47 additions & 9 deletions connectionwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"strings"
"time"
)

// connWriter is used to write to the connection.
Expand All @@ -22,7 +23,33 @@ type ConnectionWriter interface {
Close() error
}

func NewConnectionWriter(connectionType ConnectionType, address string, tlsconfig *tls.Config) (ConnectionWriter, error) {
// Option configures the connection made by NewClient or NewConnectionWriter.
type Option func(*options)

type options struct {
tlsConfig *tls.Config
timeout time.Duration
}

// WithTLSConfig sets the TLS configuration for TLS and HTTPS connections.
func WithTLSConfig(config *tls.Config) Option {
return func(o *options) { o.tlsConfig = config }
}

// WithTimeout limits how long establishing the connection and sending each
// message may block. A message that hits the timeout fails with an error. On
// TCP and TLS, a write only blocks once the send buffer is full, so a stalled
// server is noticed late; if part of a message was written by then, the
// connection is closed. A timeout of 0 means no limit.
func WithTimeout(timeout time.Duration) Option {
return func(o *options) { o.timeout = timeout }
}

func NewConnectionWriter(connectionType ConnectionType, address string, opts ...Option) (ConnectionWriter, error) {
var o options
for _, opt := range opts {
opt(&o)
}
// Validate data
switch connectionType {
case ConnectionUDP, ConnectionTCP, ConnectionTLS, ConnectionHTTP:
Expand All @@ -35,28 +62,29 @@ func NewConnectionWriter(connectionType ConnectionType, address string, tlsconfi
panic("DefaultTransport is not of type *http.Transport")
}
transport := defaultTransport
if tlsconfig != nil {
if o.tlsConfig != nil {
transport = defaultTransport.Clone()
transport.TLSClientConfig = tlsconfig
transport.TLSClientConfig = o.tlsConfig
}
return &httpWriter{
httpURL: address,
client: http.Client{Transport: transport},
client: http.Client{Transport: transport, Timeout: o.timeout},
}, nil
}

var conn net.Conn
var err error
// connect via udp / tcp / tls
dialer := &net.Dialer{Timeout: o.timeout}
if connectionType == ConnectionTLS {
conn, err = tls.Dial(string(ConnectionTCP), address, tlsconfig)
conn, err = tls.DialWithDialer(dialer, string(ConnectionTCP), address, o.tlsConfig)
} else {
conn, err = net.Dial(string(connectionType), address)
conn, err = dialer.Dial(string(connectionType), address)
}
if err != nil {
return nil, err
}
return &basicWriter{conn: conn}, nil
return &basicWriter{conn: conn, timeout: o.timeout}, nil
}

type httpWriter struct {
Expand All @@ -77,10 +105,10 @@ func (h *httpWriter) WriteString(s string, contentType string) (int, error) {
if err != nil {
return 0, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return 0, fmt.Errorf("HTTP request to write the message failed with status code %d", resp.StatusCode)
}
defer func() { _ = resp.Body.Close() }()
h.bytesWritten += int64(len(s))
return len(s), nil
}
Expand Down Expand Up @@ -120,7 +148,8 @@ func (h *httpWriter) SourceIP() (net.IP, error) {
// basicWriter writes messages to a TCP/UDP connection.
type basicWriter struct {
conn net.Conn
bytesWritten int64 // Number of bytes written
timeout time.Duration // Limit for each write, 0 for none
bytesWritten int64 // Number of bytes written
}

// WriteString writes a string to the connection.
Expand All @@ -130,9 +159,18 @@ func (b *basicWriter) WriteString(s string, contentType string) (int, error) {
if !strings.HasSuffix(s, "\n") {
s += "\n"
}
if b.timeout > 0 {
if err := b.conn.SetWriteDeadline(time.Now().Add(b.timeout)); err != nil {
return 0, err
}
}
// Send the message via TCP/UDP
n, err := fmt.Fprint(b.conn, s)
b.bytesWritten += int64(n)
if n > 0 && err != nil {
// Partial write, connection is unusable from now on, so close it
_ = b.conn.Close()
}
return n, err
}

Expand Down
Loading