Repository navigation
Expand file tree
/
Copy pathctrlsock.go
More file actions
511 lines (421 loc) · 12.6 KB
/
Copy pathctrlsock.go
File metadata and controls
511 lines (421 loc) · 12.6 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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner (pzz@apevzner.com)
* See LICENSE for license terms and conditions
*
* Control socket handler
*
* ipp-usb runs a HTTP server on a top of the unix domain control
* socket.
*
* Currently it is only used to obtain a per-device status from the
* running daemon. Using HTTP here sounds as overkill, but taking
* in account that it costs us virtually nothing and this mechanism
* is well-extendable, this is a good choice
*/
package main
import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net"
"net/http"
"os"
"sync"
"syscall"
)
const (
// CtrlsockAPIVersion is the current ipp-usb API version.
//
// The protocol is versioned independently of the *ipp-usb* software
// release. The protocol version identifies the *ipp-usb* release in
// which the latest protocol changes were introduced. It remains
// unchanged across software releases that do not change the protocol.
CtrlsockAPIVersion = "0.9.35"
// Common MIME types
ctrlSockMIMEJSON = "application/json"
ctrlSockMIMEText = "text/plain; charset=utf-8"
// ctrlSockMAXRequestSize is the size limit for the POST request body
ctrlSockMAXRequestSize = 65536
)
var (
// CtrlsockAddr contains control socket address in
// a form of the net.UnixAddr structure
CtrlsockAddr = &net.UnixAddr{Name: PathControlSocket, Net: "unix"}
// ctrlsockServer is a HTTP server that runs on a top of
// the status socket
ctrlsockServer = http.Server{
Handler: http.HandlerFunc(ctrlsockHandler),
ErrorLog: log.New(Log.LineWriter(LogError, '!'), "", 0),
}
// ctrlsockConnTable tracks control socket connections,
// indexed by remote address
ctrlsockConnTable = map[string]*ctrlsockConn{}
// ctrlsockConnTableLock protects the ctrlsockConnTable
ctrlsockConnTableLock sync.Mutex
)
// ctrlsockCONFData is the data record for POST /get/conf and POST /set/conf
// requests and response.
type ctrlsockCONFData struct {
// Device identification
MFG string `json:"usb_MFG,omitempty"`
MDL string `json:"usb_MDL,omitempty"`
SN string `json:"usb_SN,omitempty" `
HWID string `json:"usb_HWID,omitempty"`
URI string `json:"usb_URI,omitempty"`
// Device configuration
Disabled *bool `json:"disabled,omitempty"`
}
// ctrlsockCONFDatafromDevState fills ctrlsockCONFData from
// the DevState structure
func ctrlsockCONFDatafromDevState(state *DevState) ctrlsockCONFData {
disabled := state.Disabled
data := ctrlsockCONFData{
MDL: state.MDL,
MFG: state.MFG,
SN: state.SN,
HWID: state.HWID,
URI: state.URIString(),
Disabled: &disabled,
}
return data
}
// ctrlsockJSONResponse is the common structure for all JSON responses.
type ctrlsockJSONResponse struct {
Err string `json:"err,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// ctrlsockConnAddress is the unique fake address for
// the control socket connection.
type ctrlsockConnAddress string
// newCtrlsockConnAddress returns the new unique ctrlsockConnAddress.
func newCtrlsockConnAddress() ctrlsockConnAddress {
var buf [16]byte
rand.Read(buf[:])
const format = "" +
"%8.8x-" +
"%4.4x-" +
"%4.4x-" +
"%4.4x-" +
"%12.12x"
s := fmt.Sprintf(
format,
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16])
return ctrlsockConnAddress(s)
}
// Network returns network name for the ctrlsockConnAddress.
// It implements the net.Addr interface.
func (ctrlsockConnAddress) Network() string {
return "unix"
}
// String returns string form of ctrlsockConnAddress.
// It implements the net.Addr interface.
func (addr ctrlsockConnAddress) String() string {
return string(addr)
}
// ctrlsockConn wraps net.UnixConn and adds unique remote
// address.
type ctrlsockConn struct {
*net.UnixConn // Underlying connection
remote ctrlsockConnAddress // Remote address
}
// newCtrlsockConn wraps net.UnixConn into ctrlsockConn
func newCtrlsockConn(conn *net.UnixConn) net.Conn {
addr := newCtrlsockConnAddress()
conn2 := &ctrlsockConn{UnixConn: conn, remote: addr}
Log.Debug('+', "ctrlsock: connection accepted: %s", addr)
ctrlsockConnTableLock.Lock()
ctrlsockConnTable[addr.String()] = conn2
ctrlsockConnTableLock.Unlock()
return conn2
}
// getCtrlsockConn returns ctrlsockConn for the incoming http.Request
func getCtrlsockConn(r *http.Request) *ctrlsockConn {
ctrlsockConnTableLock.Lock()
defer ctrlsockConnTableLock.Unlock()
return ctrlsockConnTable[r.RemoteAddr]
}
// Close closes the connection.
func (conn ctrlsockConn) Close() error {
addr := conn.remote
Log.Debug('-', "ctrlsock: connection closed: %s", addr)
ctrlsockConnTableLock.Lock()
delete(ctrlsockConnTable, addr.String())
ctrlsockConnTableLock.Unlock()
return conn.UnixConn.Close()
}
// RemoteAddr returns remote address of ctrlsockConn.
func (conn ctrlsockConn) RemoteAddr() net.Addr {
return conn.remote
}
// Ucred returns peer credential for the connection
// represented by ctrlsockConn.
func (conn ctrlsockConn) Ucred() (*syscall.Ucred, error) {
rawConn, err := conn.SyscallConn()
if err != nil {
return nil, err
}
var ucred *syscall.Ucred
var err2 error
err = rawConn.Control(func(fd uintptr) {
ucred, err2 = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
})
switch {
case err != nil:
return nil, err
case err2 != nil:
return nil, err2
}
return ucred, nil
}
// ctrlsockListener wraps net.UnixListener and
// adds unique remote address to each accepted connection.
type ctrlsockListener struct {
*net.UnixListener // Underlying net.UnixListener
}
// ctrlsockListen returns new ctrlsockListener
func ctrlsockListen(addr *net.UnixAddr) (net.Listener, error) {
l, err := net.ListenUnix("unix", CtrlsockAddr)
if err != nil {
return nil, err
}
return ctrlsockListener{l}, nil
}
// Accept returns new connection
func (l ctrlsockListener) Accept() (net.Conn, error) {
conn, err := l.UnixListener.AcceptUnix()
if err != nil {
return nil, err
}
return newCtrlsockConn(conn), nil
}
// ctrlsockHandler handles HTTP requests that come over the
// control socket
func ctrlsockHandler(w http.ResponseWriter, r *http.Request) {
// Catch panics to log
defer func() {
v := recover()
if v != nil {
Log.Panic(v)
}
}()
// Obtain peer credentials
conn := getCtrlsockConn(r)
if conn == nil {
ctrlsockRequestError(w, r, http.StatusInternalServerError,
"unknown connection from "+r.RemoteAddr)
return
}
ucred, err := conn.Ucred()
if err != nil {
ctrlsockRequestError(w, r, http.StatusInternalServerError,
err.Error())
return
}
Log.Debug(' ', "ctrlsock: request from UID=%v", ucred.Uid)
// Check request method
if r.Method != "GET" && r.Method != "POST" {
message := r.Method + ": method not supported"
ctrlsockRequestError(w, r, http.StatusMethodNotAllowed, message)
return
}
// Parse POST request parameters
var rq ctrlsockCONFData
if r.Method == "POST" {
// Validate content type
contentType := r.Header.Get("Content-Type")
mediatype, _, err := mime.ParseMediaType(contentType)
if err != nil {
ctrlsockRequestError(w, r, http.StatusBadRequest,
"Invalid or missing Content-Type")
return
}
if mediatype != "application/json" {
ctrlsockRequestError(w, r, http.StatusUnsupportedMediaType,
"Content-Type must be application/json")
return
}
// Parse body
rd := io.LimitReader(r.Body, ctrlSockMAXRequestSize)
err = json.NewDecoder(rd).Decode(&rq)
if err != nil {
ctrlsockRequestError(w, r, http.StatusBadRequest, err.Error())
return
}
}
// Dispatch the request
var mime string
var data []byte
var status int
switch {
case r.Method == "GET" && r.URL.Path == "/devices":
mime, data, status, err = ctrlsockGETDevices()
case r.Method == "GET" && r.URL.Path == "/status":
mime, data, status, err = ctrlsockGETStatus()
case r.Method == "GET" && r.URL.Path == "/version":
mime, data, status, err = ctrlsockGETVersion()
case r.Method == "POST" && r.URL.Path == "/get/conf":
mime, data, status, err = ctrlsockPOSTGetConf(rq)
case r.Method == "POST" && r.URL.Path == "/set/conf":
status, err = AuthAdminRequest(Log, int(ucred.Uid))
if err == nil {
mime, data, status, err = ctrlsockPOSTSetConf(rq)
}
default:
ctrlsockRequestError(w, r, http.StatusNotFound, "Not found")
return
}
// Send the response
if err != nil {
ctrlsockRequestError(w, r, status, err.Error())
return
}
ctrlsockRequestComplete(w, r, http.StatusOK, data, mime)
}
// ctrlsockRequestComplete completes the control socket request
func ctrlsockRequestComplete(w http.ResponseWriter, r *http.Request,
status int, data []byte, mime string) {
ctrlsockRequestLog(r, status, "")
w.Header().Set("Content-Type", mime)
httpNoCache(w)
w.WriteHeader(http.StatusOK)
w.Write(data)
}
// ctrlsockRequestError completes control socket request with the error.
func ctrlsockRequestError(w http.ResponseWriter, r *http.Request,
status int, message string) {
if message == "" {
message = http.StatusText(status)
}
ctrlsockRequestLog(r, status, message)
http.Error(w, message, status)
}
// ctrlsockRequestLog writes logging information related to
// the request processing.
func ctrlsockRequestLog(r *http.Request, status int, message string) {
Log.Debug(' ', "ctrlsock: %s %s -- %3.3d %s",
r.Method, r.URL, status, message)
}
// ctrlsockGETDevices handles the GET /devices request
func ctrlsockGETDevices() (string, []byte, int, error) {
return "", nil, http.StatusNotImplemented, errors.New("not implemented")
}
// ctrlsockGETStatus handles the GET /status request
func ctrlsockGETStatus() (string, []byte, int, error) {
return ctrlSockMIMEText, StatusFormat(), http.StatusOK, nil
}
// ctrlsockGETVersion handles the GET /version request
func ctrlsockGETVersion() (string, []byte, int, error) {
return ctrlSockMIMEText, []byte(CtrlsockAPIVersion), http.StatusOK, nil
}
// ctrlsockPOSTGetConf handles the POST /get/conf request
func ctrlsockPOSTGetConf(rq ctrlsockCONFData) (string, []byte, int, error) {
states := DevStateSearch(rq.MFG, rq.MDL, rq.SN, rq.HWID, rq.URI)
items := make([]ctrlsockCONFData, 0, len(states))
for _, state := range states {
if state.MDL == "" || state.MFG == "" || state.SN == "" {
continue
}
item := ctrlsockCONFDatafromDevState(state)
items = append(items, item)
}
response := ctrlsockJSONResponse{Data: items}
buf := bytes.Buffer{}
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
encoder.Encode(response)
return ctrlSockMIMEJSON, buf.Bytes(), http.StatusOK, nil
}
// ctrlsockPOSTSetConf handles the POST /get/conf request
func ctrlsockPOSTSetConf(rq ctrlsockCONFData) (string, []byte, int, error) {
var err error
switch {
case rq.MFG != "" && rq.MDL != "" && rq.SN != "":
case rq.HWID != "" && rq.SN != "":
case rq.URI != "":
default:
err = errors.New("ambiguous request")
}
response := ctrlsockJSONResponse{}
if err == nil {
states := DevStateSearch(rq.MFG, rq.MDL, rq.SN, rq.HWID, rq.URI)
if len(states) == 0 {
err = errors.New("device not found")
} else {
state := states[0]
save := false
if rq.Disabled != nil {
state.Disabled = *rq.Disabled
save = true
}
if save {
err = PnPUpdateState(state)
if err == nil {
state.Save()
}
}
if err == nil {
response.Data = ctrlsockCONFDatafromDevState(state)
}
}
}
if err != nil {
response.Err = err.Error()
}
buf := bytes.Buffer{}
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
encoder.Encode(response)
return ctrlSockMIMEJSON, buf.Bytes(), http.StatusOK, nil
}
// CtrlsockStart starts control socket server
func CtrlsockStart() error {
Log.Debug(' ', "ctrlsock: listening at %q", PathControlSocket)
// Listen the socket
os.Remove(PathControlSocket)
listener, err := ctrlsockListen(CtrlsockAddr)
if err != nil {
return err
}
// Make socket accessible to everybody. Error is ignored,
// it's not a reason to abort ipp-usb
os.Chmod(PathControlSocket, 0777)
// Start HTTP server on a top of the listening socket
go func() {
ctrlsockServer.Serve(listener)
}()
return nil
}
// CtrlsockStop stops the control socket server
func CtrlsockStop() {
Log.Debug(' ', "ctrlsock: shutdown")
ctrlsockServer.Close()
}
// CtrlsockDial connects to the control socket of the running
// ipp-usb daemon
func CtrlsockDial() (net.Conn, error) {
conn, err := net.DialUnix("unix", nil, CtrlsockAddr)
if err == nil {
return conn, err
}
if neterr, ok := err.(*net.OpError); ok {
if syserr, ok := neterr.Err.(*os.SyscallError); ok {
switch syserr.Err {
case syscall.ECONNREFUSED, syscall.ENOENT:
err = ErrNoIppUsb
case syscall.EACCES, syscall.EPERM:
err = ErrAccess
}
}
}
return conn, err
}