forked from phin1x/go-ipp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapter-socket.go
213 lines (177 loc) · 5.35 KB
/
adapter-socket.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
package ipp
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
)
var SocketNotFoundError = errors.New("unable to locate CUPS socket")
var CertNotFoundError = errors.New("unable to locate CUPS certificate")
var (
DefaultSocketSearchPaths = []string{"/var/run/cupsd", "/var/run/cups/cups.sock", "/run/cups/cups.sock"}
DefaultCertSearchPaths = []string{"/etc/cups/certs/0", "/run/cups/certs/0"}
)
const DefaultRequestRetryLimit = 3
type SocketAdapter struct {
host string
useTLS bool
SocketSearchPaths []string
CertSearchPaths []string
//RequestRetryLimit is the number of times a request will be retried when receiving an authorized status. This usually happens when a CUPs cert is expired, and a retry will use the newly generated cert. Default 3.
RequestRetryLimit int
}
func NewSocketAdapter(host string, useTLS bool) *SocketAdapter {
return &SocketAdapter{
host: host,
useTLS: useTLS,
SocketSearchPaths: DefaultSocketSearchPaths,
CertSearchPaths: DefaultCertSearchPaths,
RequestRetryLimit: DefaultRequestRetryLimit,
}
}
// SendRequest performs the given IPP request to the given URL, returning the IPP response or an error if one occurred.
// Additional data will be written to an io.Writer if additionalData is not nil
func (h *SocketAdapter) SendRequest(url string, r *Request, additionalData io.Writer) (*Response, error) {
for i := 0; i < h.RequestRetryLimit; i++ {
// encode request
payload, err := r.Encode()
if err != nil {
return nil, fmt.Errorf("unable to encode IPP request: %w", err)
}
var body io.Reader
size := len(payload)
if r.File != nil && r.FileSize != -1 {
size += r.FileSize
body = io.MultiReader(bytes.NewBuffer(payload), r.File)
} else {
body = bytes.NewBuffer(payload)
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, fmt.Errorf("unable to create HTTP request: %w", err)
}
sock, err := h.GetSocket()
if err != nil {
return nil, err
}
// if cert isn't found, do a request to generate it
cert, err := h.GetCert()
if err != nil && err != CertNotFoundError {
return nil, err
}
req.Header.Set("Content-Length", strconv.Itoa(size))
req.Header.Set("Content-Type", ContentTypeIPP)
req.Header.Set("Authorization", fmt.Sprintf("Local %s", cert))
unixClient := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", sock)
},
},
}
// send request
httpResp, err := unixClient.Do(req)
if err != nil {
return nil, fmt.Errorf("unable to perform HTTP request: %w", err)
}
if httpResp.StatusCode == http.StatusUnauthorized {
// retry with newly generated cert
httpResp.Body.Close()
continue
}
if httpResp.StatusCode != http.StatusOK {
httpResp.Body.Close()
return nil, fmt.Errorf("server did not return Status OK: %d", httpResp.StatusCode)
}
// buffer response to avoid read issues
buf := new(bytes.Buffer)
if httpResp.ContentLength > 0 {
buf.Grow(int(httpResp.ContentLength))
}
if _, err := io.Copy(buf, httpResp.Body); err != nil {
httpResp.Body.Close()
return nil, fmt.Errorf("unable to buffer response: %w", err)
}
httpResp.Body.Close()
// decode reply
ippResp, err := NewResponseDecoder(buf).Decode(additionalData)
if err != nil {
return nil, fmt.Errorf("unable to decode IPP response: %w", err)
}
if err = ippResp.CheckForErrors(); err != nil {
return nil, fmt.Errorf("received error IPP response: %w", err)
}
return ippResp, nil
}
return nil, errors.New("request retry limit exceeded")
}
// GetSocket returns the path to the cupsd socket by searching SocketSearchPaths
func (h *SocketAdapter) GetSocket() (string, error) {
for _, path := range h.SocketSearchPaths {
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
continue
} else if os.IsPermission(err) {
return "", errors.New("unable to access socket: Access denied")
}
return "", fmt.Errorf("unable to access socket: %w", err)
}
if fi.Mode()&os.ModeSocket != 0 {
return path, nil
}
}
return "", SocketNotFoundError
}
// GetCert returns the current CUPs authentication certificate by searching CertSearchPaths
func (h *SocketAdapter) GetCert() (string, error) {
for _, path := range h.CertSearchPaths {
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
continue
} else if os.IsPermission(err) {
return "", errors.New("unable to access certificate: Access denied")
}
return "", fmt.Errorf("unable to access certificate: %w", err)
}
defer f.Close()
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, f); err != nil {
return "", fmt.Errorf("unable to access certificate: %w", err)
}
return buf.String(), nil
}
return "", CertNotFoundError
}
func (h *SocketAdapter) GetHttpUri(namespace string, object interface{}) string {
proto := "http"
if h.useTLS {
proto = "https"
}
uri := fmt.Sprintf("%s://%s", proto, h.host)
if namespace != "" {
uri = fmt.Sprintf("%s/%s", uri, namespace)
}
if object != nil {
uri = fmt.Sprintf("%s/%v", uri, object)
}
return uri
}
func (h *SocketAdapter) TestConnection() error {
sock, err := h.GetSocket()
if err != nil {
return err
}
conn, err := net.Dial("unix", sock)
if err != nil {
return err
}
conn.Close()
return nil
}