-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyslog.go
More file actions
321 lines (266 loc) · 9.43 KB
/
syslog.go
File metadata and controls
321 lines (266 loc) · 9.43 KB
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
package main
import (
"context"
"fmt"
"io"
"net"
"os"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// ================================================================================
// SYSLOG SERVICE - Handles syslog message formatting and sending
// Follows Single Responsibility Principle: manages message formatting and transmission
// ================================================================================
// FramingMethod specifies the framing method for TCP per RFC 6587
type FramingMethod string
const (
// OctetCounting implements octet counting method (RFC 6587 Section 3.4.1)
OctetCounting FramingMethod = "octet-counting"
// NonTransparent implements non-transparent framing (RFC 6587 Section 3.4.2)
NonTransparent FramingMethod = "non-transparent"
)
// SyslogConfig holds the configuration for sending syslog messages
type SyslogConfig struct {
Address string `json:"Address"`
Port string `json:"Port"`
Protocol string `json:"Protocol"`
Messages []string `json:"Messages"`
FramingMethod FramingMethod `json:"FramingMethod"`
Facility uint8 `json:"Facility"`
Severity uint8 `json:"Severity"`
Hostname string `json:"Hostname"`
Appname string `json:"Appname"`
UseRFC5424 bool `json:"UseRFC5424"`
UseTLS bool `json:"UseTLS"`
TLSVerify bool `json:"TLSVerify"`
CACertPath string `json:"CACertPath"`
ClientCertPath string `json:"ClientCertPath"`
ClientKeyPath string `json:"ClientKeyPath"`
}
// SyslogResponse contains the result of send operations
type SyslogResponse struct {
SentMessages []string `json:"sentMessages"`
Errors []string `json:"errors"`
}
// SyslogService handles syslog message sending operations
type SyslogService struct {
ctx context.Context
}
// NewSyslogService creates a new SyslogService instance
func NewSyslogService() *SyslogService {
return &SyslogService{}
}
// SetContext sets the Wails runtime context
func (s *SyslogService) SetContext(ctx context.Context) {
s.ctx = ctx
}
// SendSyslogMessages sends syslog messages and returns the result
func (s *SyslogService) SendSyslogMessages(config SyslogConfig) SyslogResponse {
response := SyslogResponse{
SentMessages: []string{},
Errors: []string{},
}
// Validate configuration
if err := validateConfig(&config); err != nil {
response.Errors = append(response.Errors, fmt.Sprintf("Invalid configuration: %v", err))
return response
}
// Emit start event
runtime.EventsEmit(s.ctx, "syslog:sending", map[string]interface{}{
"total": len(config.Messages),
})
fullAddress := net.JoinHostPort(config.Address, config.Port)
// Establish connection
conn, err := dialConnection(config.Address, config.Port, config.Protocol, config.UseTLS, config.TLSVerify, config.CACertPath, config.ClientCertPath, config.ClientKeyPath)
if err != nil {
response.Errors = append(response.Errors, fmt.Sprintf("Error connecting to %s: %v", fullAddress, err))
return response
}
defer conn.Close()
// Send messages based on protocol
if config.Protocol == "tcp" {
return s.sendTCPMessages(conn, config)
}
return s.sendUDPMessages(conn, config)
}
// sendTCPMessages sends TCP messages with proper framing per RFC 6587
func (s *SyslogService) sendTCPMessages(conn net.Conn, config SyslogConfig) SyslogResponse {
response := SyslogResponse{
SentMessages: []string{},
Errors: []string{},
}
// Create framer with appropriate configuration
framer := NewFramer(FramingConfig{
Method: config.FramingMethod,
ValidateUTF8: true,
MaxMessageLength: 0,
})
totalMessages := len(config.Messages)
for i, message := range config.Messages {
// Build syslog message
syslogMsg, err := buildSyslogMessage(config, message)
if err != nil {
response.Errors = append(response.Errors, fmt.Sprintf("Error building message: %v", err))
continue
}
// Apply TCP framing
framedMsg, err := framer.Frame(syslogMsg)
if err != nil {
response.Errors = append(response.Errors, fmt.Sprintf("Error framing message: %v", err))
continue
}
// Set write deadline
if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
runtime.LogWarning(s.ctx, fmt.Sprintf("Failed to set write deadline: %v", err))
}
// Send with robust handling
if err := writeAll(conn, framedMsg); err != nil {
runtime.LogError(s.ctx, fmt.Sprintf("Error sending message: %v", err))
response.Errors = append(response.Errors, fmt.Sprintf("Error sending message: %v", err))
} else {
runtime.LogDebug(s.ctx, fmt.Sprintf("Sent message: %s", syslogMsg))
response.SentMessages = append(response.SentMessages, syslogMsg)
}
// Emit progress event
runtime.EventsEmit(s.ctx, "syslog:progress", map[string]interface{}{
"current": i + 1,
"total": totalMessages,
"percent": float64(i+1) / float64(totalMessages) * 100,
})
}
// Emit completion event
runtime.EventsEmit(s.ctx, "syslog:complete", map[string]interface{}{
"sent": len(response.SentMessages),
"errors": len(response.Errors),
})
return response
}
// sendUDPMessages sends UDP messages (one message per packet)
func (s *SyslogService) sendUDPMessages(conn net.Conn, config SyslogConfig) SyslogResponse {
response := SyslogResponse{
SentMessages: []string{},
Errors: []string{},
}
totalMessages := len(config.Messages)
for i, message := range config.Messages {
syslogMsg, err := buildSyslogMessage(config, message)
if err != nil {
response.Errors = append(response.Errors, fmt.Sprintf("Error building message: %v", err))
continue
}
if err := conn.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
runtime.LogWarning(s.ctx, fmt.Sprintf("Failed to set write deadline: %v", err))
}
if err := writeAll(conn, []byte(syslogMsg)); err != nil {
runtime.LogError(s.ctx, fmt.Sprintf("Error sending message: %v", err))
response.Errors = append(response.Errors, fmt.Sprintf("Error sending message: %v", err))
} else {
runtime.LogDebug(s.ctx, fmt.Sprintf("Sent message: %s", syslogMsg))
response.SentMessages = append(response.SentMessages, syslogMsg)
}
runtime.EventsEmit(s.ctx, "syslog:progress", map[string]interface{}{
"current": i + 1,
"total": totalMessages,
"percent": float64(i+1) / float64(totalMessages) * 100,
})
}
runtime.EventsEmit(s.ctx, "syslog:complete", map[string]interface{}{
"sent": len(response.SentMessages),
"errors": len(response.Errors),
})
return response
}
// ================================================================================
// SYSLOG MESSAGE FORMATTING HELPERS
// ================================================================================
// buildSyslogMessage constructs a valid syslog message per RFC 5424 or RFC 3164
func buildSyslogMessage(config SyslogConfig, message string) (string, error) {
priority := config.Facility*8 + config.Severity
if priority > 191 {
return "", fmt.Errorf("invalid priority %d (facility=%d, severity=%d)", priority, config.Facility, config.Severity)
}
if config.UseRFC5424 {
return buildRFC5424Message(priority, config, message), nil
}
return buildRFC3164Message(priority, config, message), nil
}
// buildRFC5424Message constructs message per RFC 5424
func buildRFC5424Message(priority uint8, config SyslogConfig, message string) string {
timestamp := time.Now().UTC().Format("2006-01-02T15:04:05.000Z07:00")
hostname := config.Hostname
if hostname == "" {
hostname = "-"
}
appname := config.Appname
if appname == "" {
appname = "-"
}
return fmt.Sprintf("<%d>1 %s %s %s - - - %s",
priority, timestamp, hostname, appname, message)
}
// buildRFC3164Message constructs message per RFC 3164 (BSD syslog)
func buildRFC3164Message(priority uint8, config SyslogConfig, message string) string {
timestamp := time.Now().Format("Jan 2 15:04:05")
hostname := config.Hostname
if hostname == "" {
hostname, _ = os.Hostname()
if hostname == "" {
hostname = "localhost"
}
}
appname := config.Appname
if appname == "" {
appname = "app"
}
return fmt.Sprintf("<%d>%s %s %s: %s",
priority, timestamp, hostname, appname, message)
}
// writeAll ensures all bytes are written (handles partial writes)
func writeAll(w io.Writer, data []byte) error {
totalWritten := 0
dataLen := len(data)
for totalWritten < dataLen {
n, err := w.Write(data[totalWritten:])
if err != nil {
return fmt.Errorf("write failed after %d/%d bytes: %w", totalWritten, dataLen, err)
}
totalWritten += n
}
return nil
}
// validateConfig validates and normalizes configuration
func validateConfig(config *SyslogConfig) error {
if config.Address == "" {
return fmt.Errorf("address is required")
}
if config.Port == "" {
return fmt.Errorf("port is required")
}
if config.Facility > 23 {
return fmt.Errorf("facility must be 0-23 (got %d)", config.Facility)
}
if config.Severity > 7 {
return fmt.Errorf("severity must be 0-7 (got %d)", config.Severity)
}
if config.FramingMethod == "" {
if config.Protocol == "tcp" {
config.FramingMethod = RecommendedFramingMethod()
}
}
if config.FramingMethod != "" && !IsValidFramingMethod(config.FramingMethod) {
return fmt.Errorf("invalid framing method '%s'", config.FramingMethod)
}
if config.Hostname == "" {
hostname, err := os.Hostname()
if err == nil && hostname != "" {
config.Hostname = hostname
} else {
config.Hostname = "localhost"
}
}
if config.Appname == "" {
config.Appname = "sendlog"
}
return nil
}