-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshare.go
More file actions
251 lines (221 loc) · 5.88 KB
/
share.go
File metadata and controls
251 lines (221 loc) · 5.88 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
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
shareReadTimeout = 5 * time.Second
shareMaxBytes = 1 << 20 // 1 MB max per job
)
var (
shareListener net.Listener
shareMu sync.Mutex
shareRunning atomic.Bool
shareConnCount atomic.Int64
shareJobCount atomic.Int64
)
// ShareStatus describes the current state of the printer sharing service.
type ShareStatus struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Port int `json:"port"`
Printer string `json:"printer"`
Address string `json:"address,omitempty"`
Connections int64 `json:"connections"`
JobsServed int64 `json:"jobs_served"`
LocalAddresses []string `json:"local_addresses"`
}
// getShareStatus returns the current sharing status.
func getShareStatus() ShareStatus {
cfg := getConfig()
addr := ""
if shareRunning.Load() && shareListener != nil {
addr = shareListener.Addr().String()
}
// Collect local IPv4 addresses from network interfaces
var localAddrs []string
ifaces, _ := net.Interfaces()
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
continue
}
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok {
continue
}
ip4 := ipnet.IP.To4()
if ip4 == nil || (ip4[0] == 169 && ip4[1] == 254) {
continue
}
localAddrs = append(localAddrs, ip4.String())
}
}
return ShareStatus{
Enabled: cfg.ShareEnabled,
Running: shareRunning.Load(),
Port: cfg.SharePort,
Printer: cfg.SharePrinter,
Address: addr,
Connections: shareConnCount.Load(),
JobsServed: shareJobCount.Load(),
LocalAddresses: localAddrs,
}
}
// startShareServer starts the TCP proxy listener for sharing a USB printer.
func startShareServer() {
cfg := getConfig()
if !cfg.ShareEnabled {
log.Printf("[share] Printer sharing disabled")
return
}
startShareListener(cfg.SharePort)
}
// startShareListener starts listening on the given port.
func startShareListener(port int) {
shareMu.Lock()
defer shareMu.Unlock()
if shareRunning.Load() {
return
}
addr := fmt.Sprintf("0.0.0.0:%d", port)
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Printf("[share] Cannot listen on %s: %v", addr, err)
return
}
shareListener = ln
shareRunning.Store(true)
log.Printf("[share] Sharing printer on %s (port %d)", addr, port)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if shareRunning.Load() {
log.Printf("[share] Accept error: %v", err)
}
return
}
shareConnCount.Add(1)
go handleShareConnection(conn)
}
}()
}
// stopShareListener stops the sharing listener.
func stopShareListener() {
shareMu.Lock()
defer shareMu.Unlock()
if !shareRunning.Load() {
return
}
shareRunning.Store(false)
if shareListener != nil {
shareListener.Close()
shareListener = nil
}
log.Printf("[share] Printer sharing stopped")
}
// getSharePrinterName resolves which local printer to use for sharing.
func getSharePrinterName() string {
cfg := getConfig()
if cfg.SharePrinter != "" {
return cfg.SharePrinter
}
if cfg.DefaultPrinter != "" {
return cfg.DefaultPrinter
}
local, _ := listLocalPrinters()
if len(local) > 0 {
return local[0].Name
}
return ""
}
// getShareModelResponse builds a synthetic ~!I response for the shared printer.
func getShareModelResponse() string {
cfg := getConfig()
printerName := cfg.SharePrinter
if printerName == "" {
printerName = cfg.DefaultPrinter
}
// Find the local printer to get its model
local, _ := listLocalPrinters()
model := "TSC TDP-244 Plus"
for _, p := range local {
if p.Name == printerName || printerName == "" {
if p.Model != "" {
model = p.Model
} else {
model = "TSC " + p.Name
}
break
}
}
// Format like a real TSC ~!I response
return fmt.Sprintf("%s\r\nV1.0\r\nShared via tsc-bridge\r\n", model)
}
// handleShareConnection reads data from a network client.
// If it's a ~!I probe, responds with printer info so scanners can identify it.
// Otherwise, forwards the TSPL2 data to the local printer.
func handleShareConnection(conn net.Conn) {
defer conn.Close()
remote := conn.RemoteAddr().String()
log.Printf("[share] Connection from %s", remote)
// Read initial bytes with a short timeout to detect probes
conn.SetReadDeadline(time.Now().Add(1 * time.Second))
head := make([]byte, 16)
n, err := conn.Read(head)
if err != nil || n == 0 {
return
}
head = head[:n]
// Check if this is a ~!I probe (used by network scanners)
trimmed := bytes.TrimSpace(head)
if bytes.Equal(trimmed, []byte("~!I")) || strings.HasPrefix(string(trimmed), "~!I") {
response := getShareModelResponse()
conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
conn.Write([]byte(response))
log.Printf("[share] Probe from %s — responded with model info", remote)
return
}
// Not a probe — it's a print job. Read the rest of the data.
conn.SetReadDeadline(time.Now().Add(shareReadTimeout))
rest, err := io.ReadAll(io.LimitReader(conn, shareMaxBytes))
if err != nil && err != io.EOF {
log.Printf("[share] Read error from %s: %v", remote, err)
}
data := append(head, rest...)
if len(data) == 0 {
return
}
printerName := getSharePrinterName()
if printerName == "" {
log.Printf("[share] No local printer available for job from %s", remote)
return
}
if err := rawPrint(printerName, data); err != nil {
log.Printf("[share] Print failed for job from %s: %v", remote, err)
return
}
shareJobCount.Add(1)
log.Printf("[share] Printed %d bytes from %s to %s", len(data), remote, printerName)
}
// toggleShare enables or disables printer sharing dynamically.
func toggleShare(enable bool) {
if enable {
cfg := getConfig()
startShareListener(cfg.SharePort)
} else {
stopShareListener()
}
}