-
Notifications
You must be signed in to change notification settings - Fork 0
/
syslog.go
421 lines (351 loc) · 8.49 KB
/
syslog.go
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
101
102
103
104
105
106
107
108
109
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Copyright (c) 2022
// Author: Jeff Weisberg <tcp4me.com!jaw>
// Created: 2022-Jul-24 15:52 (EDT)
// Function: syslog client (RFC 5424)
package syslog
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"os"
"strings"
"sync"
"time"
)
// RFC 5424 - base
// RFC 6587 - tcp
// RFC 5426 - udp
// RFC 5425 - tls
const (
rfc5424time = "2006-01-02T15:04:05.999999Z07:00"
maxSize = 8192
unixSock = "/dev/log"
)
var defaultPort = map[string]string{
"udp": "514",
"tcp": "514", // 6587 3.3 - This protocol has no standardized port assignment
"tls": "6514",
}
// Structured contains RFC5424 structed data
type Structured struct {
Name string `json:"name"`
Enterprise string `json:"enterprise"` // can be a dotted number (eg. 32473.23.9)
Param map[string]string `json:"param"`
}
type L struct {
proto string // unix, udp, tcp, tls
addr string // filename | addr:port
withLen bool // frame encoding includes length (tcp, tls)
withConnect bool // connect at init
legacy bool // use legacy bsd format (rfc 3164)
facility Priority
hostname string
appName string
procId string
maxSize int
timeout time.Duration
retryDelay time.Duration
dialer *net.Dialer
tlsConf *tls.Config
lock sync.Mutex // to guard conn
conn io.WriteCloser // net.Conn
}
// Message contains a message to transmit
type Message struct {
time time.Time
Message string `json:"message"`
SData []*Structured `json:"structured"`
}
type OptFunc func(*L) error
// New creates a new syslog
func New(optfn ...OptFunc) (*L, error) {
l := &L{
proto: "unix",
addr: unixSock,
procId: "-",
appName: "-",
hostname: "-",
maxSize: maxSize,
}
for _, fn := range optfn {
err := fn(l)
if err != nil {
return nil, err
}
}
if l.dialer == nil {
l.dialer = &net.Dialer{Timeout: l.timeout}
}
if l.withConnect {
_, err := l.connect()
if err != nil {
return nil, err
}
}
return l, nil
}
// Close closes a syslog when it is no longer needed
func (l *L) Close() {
l.lock.Lock()
defer l.lock.Unlock()
if l.conn != nil {
l.conn.Close()
l.conn = nil
}
}
func (l *L) connect() (io.WriteCloser, error) {
l.lock.Lock()
defer l.lock.Unlock()
if l.conn != nil {
return l.conn, nil
}
var err error
var conn io.WriteCloser
switch l.proto {
case "udp", "tcp":
conn, err = l.dialer.Dial(l.proto, l.addr)
case "tls":
conn, err = tls.DialWithDialer(l.dialer, "tcp", l.addr, l.tlsConf)
case "unix":
conn, err = net.Dial("unixdgram", l.addr)
case "file":
conn, err = os.OpenFile(l.addr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
}
if err != nil {
return nil, err
}
l.conn = conn
return conn, nil
}
// Send sends a syslog message
func (l *L) Send(sev Priority, m Message) error {
m.time = time.Now()
pkt, err := l.marshal(sev, &m)
if err != nil {
return err
}
// try + retry
for i := 0; i < 3; i++ {
var conn io.WriteCloser
conn, err = l.connect()
if err != nil {
time.Sleep(10 * time.Millisecond)
continue
}
if nc, ok := conn.(net.Conn); ok {
if l.timeout != 0 {
nc.SetDeadline(time.Now().Add(l.timeout))
}
}
_, err = conn.Write([]byte(pkt))
if err != nil {
l.Close()
time.Sleep(10 * time.Millisecond)
continue
}
break
}
return err
}
func (l *L) marshal(sev Priority, m *Message) (string, error) {
prio := l.priority(sev)
ts := m.time.UTC().Format(rfc5424time)
var msg string
if l.legacy {
// rfc 3164
msg = fmt.Sprintf("<%d> %s %s %s[%s]: %s", prio, ts, l.hostname,
l.appName, l.procId, m.cleanMessage())
} else {
msg = fmt.Sprintf("<%d>1 %s %s %s %s - %s %s", prio,
ts, l.hostname, l.appName, l.procId, /* msg-id */
m.structuredData(), m.cleanMessage())
}
if l.maxSize != 0 && len(msg) > l.maxSize {
msg = msg[0:l.maxSize]
}
if l.withLen {
msg = fmt.Sprintf("%d %s", len(msg), msg)
}
return msg, nil
}
func (m *Message) cleanMessage() string {
s := strings.Map(func(ch rune) rune {
if ch == '\n' {
return ' '
}
if ch < ' ' {
return -1
}
return ch
}, m.Message)
return s
}
func (m *Message) structuredData() string {
res := bytes.NewBuffer(nil)
for _, sd := range m.SData {
if sd.Enterprise == "" {
fmt.Fprintf(res, "[%s", sd.Name)
} else {
fmt.Fprintf(res, "[%s@%s", sd.Name, sd.Enterprise)
}
for k, v := range sd.Param {
fmt.Fprintf(res, ` %s="%s"`, k, sdValue(v))
}
fmt.Fprintf(res, "]")
}
if res.Len() == 0 {
return "-"
}
return res.String()
}
func sdValue(s string) string {
// 5424 6.3.3
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `"`, `\"`)
s = strings.ReplaceAll(s, `]`, `\]`)
return s
}
func (l *L) priority(sev Priority) Priority {
return (l.facility << 3) | sev
}
// TextMessage converts a plain text string into a Message
func TextMessage(txt string) Message {
return Message{Message: txt}
}
// WithDst specifies a destination to send syslog messages
// proto should be a supported syslog protocol: usp, tcp, tls, unix
func WithDst(proto, addr string) OptFunc {
return func(l *L) error {
switch proto {
case "udp", "tcp", "tls":
var host, port string
if strings.Contains(addr, ":") {
h, p, err := net.SplitHostPort(addr)
if err != nil {
return fmt.Errorf("cannot parse dst addr '%s': %v", addr, err)
}
host, port = h, p
} else {
host = addr
}
if port == "" {
port = defaultPort[proto]
}
l.proto = proto
l.addr = net.JoinHostPort(host, port)
case "unix", "file":
l.proto, l.addr = proto, addr
default:
return fmt.Errorf("invalid dst protocol '%s', try udp|tcp|tls|unix", proto)
}
switch proto {
case "tcp", "tls":
l.withLen = true
}
return nil
}
}
// WithConnect will attempt to establish a connection at init
func WithConnect() OptFunc {
return func(l *L) error {
l.withConnect = true
return nil
}
}
// WithLegacyFormat causes legacy format (rfc 3164) essages to be sent
// not all features are supported using the legacy format
func WithLegacyFormat() OptFunc {
return func(l *L) error {
l.legacy = true
return nil
}
}
// WithTimeout specifies a timeout used while sending
func WithTimeout(dur time.Duration) OptFunc {
return func(l *L) error {
l.timeout = dur
return nil
}
}
// WithHostname specifies the local system name
// typically, the value returned by os.Hostname() should be used
func WithHostname(name string) OptFunc {
return func(l *L) error {
if name != "" {
l.hostname = name
}
return nil
}
}
// WithAppName specifies the name of the program
// typically, the value of os.Args(0) should be used
func WithAppName(name string) OptFunc {
return func(l *L) error {
if name != "" {
l.appName = name
}
return nil
}
}
// WithProcessId specifies the process id
func WithProcessId(id string) OptFunc {
return func(l *L) error {
if id != "" {
l.procId = id
}
return nil
}
}
// WithFacility specifies the syslog facility to use
func WithFacility(fac Priority) OptFunc {
return func(l *L) error {
l.facility = fac
return nil
}
}
// WithFacilityName specifies the name of the syslog facility to use
func WithFacilityName(fac string) OptFunc {
return func(l *L) error {
f, err := Facility(fac)
if err != nil {
return err
}
l.facility = f
return nil
}
}
// WithTLSConfig specifies a *tls.Config to use when sending over TLS
func WithTLSConfig(cf *tls.Config) OptFunc {
return func(l *L) error {
l.tlsConf = cf
return nil
}
}
// WithDialer specifies a *net.Dialer to use when making network connections
func WithDialer(d *net.Dialer) OptFunc {
return func(l *L) error {
l.dialer = d
return nil
}
}
// WithRetryDelay specifies a delay to wait when retrying
func WithRetryDelay(dur time.Duration) OptFunc {
return func(l *L) error {
l.retryDelay = dur
return nil
}
}
// Debug sends a message at Debug severity
func (l *L) Debug(txt string) error { return l.Send(SevDebug, TextMessage(txt)) }
// Emerg sends a message at Emerg severity
func (l *L) Emerg(txt string) error { return l.Send(SevEmerg, TextMessage(txt)) }
// Err sends a message at Err severity
func (l *L) Err(txt string) error { return l.Send(SevErr, TextMessage(txt)) }
// Info sends a message at Info severity
func (l *L) Info(txt string) error { return l.Send(SevInfo, TextMessage(txt)) }
// Notice sends a message at Notice severity
func (l *L) Notice(txt string) error { return l.Send(SevNotice, TextMessage(txt)) }
// Warning sends a message at Warning severity
func (l *L) Warning(txt string) error { return l.Send(SevWarning, TextMessage(txt)) }