-
Notifications
You must be signed in to change notification settings - Fork 50
/
proxmox.go
522 lines (438 loc) · 12.3 KB
/
proxmox.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
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
512
513
514
515
516
517
518
519
520
521
522
package proxmox
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/buger/goterm"
"github.com/gorilla/websocket"
)
const (
DefaultUserAgent = "go-proxmox/dev"
TagFormat = "go-proxmox+%s"
)
var ErrNotAuthorized = errors.New("not authorized to access endpoint")
func IsNotAuthorized(err error) bool {
return errors.Is(err, ErrNotAuthorized)
}
var ErrTimeout = errors.New("the operation has timed out")
func IsTimeout(err error) bool {
return errors.Is(err, ErrTimeout)
}
var ErrNotFound = errors.New("unable to find the item you are looking for")
func IsNotFound(err error) bool {
return errors.Is(err, ErrNotFound)
}
var ErrNoop = errors.New("nothing to do")
func IsErrNoop(err error) bool {
return errors.Is(err, ErrNoop)
}
func MakeTag(v string) string {
return fmt.Sprintf(TagFormat, v)
}
type Client struct {
httpClient *http.Client
userAgent string
baseURL string
token string
credentials *Credentials
version *Version
session *Session
log LeveledLoggerInterface
}
func NewClient(baseURL string, opts ...Option) *Client {
c := &Client{
baseURL: baseURL,
userAgent: DefaultUserAgent,
log: &LeveledLogger{Level: LevelError},
}
for _, o := range opts {
o(c)
}
if c.httpClient == nil {
c.httpClient = http.DefaultClient
}
return c
}
func (c *Client) Version(ctx context.Context) (*Version, error) {
return c.version, c.Get(ctx, "/version", &c.version)
}
func (c *Client) Req(ctx context.Context, method, path string, data []byte, v interface{}) error {
if strings.HasPrefix(path, "/") {
path = c.baseURL + path
}
c.log.Debugf("SEND: %s - %s", method, path)
var body io.Reader
if data != nil {
if path != (c.baseURL + "/access/ticket") {
// don't show passwords in the logs
if len(data) < 2048 {
c.log.Debugf("DATA: %s", string(data))
} else {
c.log.Debugf("DATA: %s", "truncated due to length")
}
}
body = bytes.NewBuffer(data)
}
req, err := http.NewRequestWithContext(ctx, method, path, body)
if err != nil {
return err
}
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
c.authHeaders(&req.Header)
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
if path == (c.baseURL + "/access/ticket") {
// received an unauthorized while trying to create a session
return ErrNotAuthorized
}
if c.credentials != nil && c.session == nil {
// credentials passed but no session started, try a login and retry the request
if _, err = c.Ticket(ctx, c.credentials); err != nil {
return err
}
return c.Req(ctx, method, path, data, v)
}
return ErrNotAuthorized
}
return c.handleResponse(res, v)
}
func (c *Client) Get(ctx context.Context, p string, v interface{}) error {
return c.Req(ctx, http.MethodGet, p, nil, v)
}
func (c *Client) Post(ctx context.Context, p string, d interface{}, v interface{}) error {
var data []byte
if d != nil {
var err error
data, err = json.Marshal(d)
if err != nil {
return err
}
}
return c.Req(ctx, http.MethodPost, p, data, v)
}
func (c *Client) Put(ctx context.Context, p string, d interface{}, v interface{}) error {
var data []byte
if d != nil {
var err error
data, err = json.Marshal(d)
if err != nil {
return err
}
}
return c.Req(ctx, http.MethodPut, p, data, v)
}
func (c *Client) Delete(ctx context.Context, p string, v interface{}) error {
return c.Req(ctx, http.MethodDelete, p, nil, v)
}
// Upload - There is some weird 16kb limit hardcoded in proxmox for the max POST size, hopefully in the future we make
// a func to scp the file to the node directly as this API endpoint is kind of janky. For now big ISOs/vztmpl should
// be put somewhere and a use DownloadUrl. code link for posterity, I think they meant to do 16mb and got the bit math wrong
// https://git.proxmox.com/?p=pve-manager.git;a=blob;f=PVE/HTTPServer.pm;h=8a0c308ea6d6601b886b0dec2bada3d4c3da65d0;hb=HEAD#l36
// the task returned is the imgcopy from the tmp file to where the node actually wants the iso and you should wait for that
// to complete before using the iso
func (c *Client) Upload(path string, fields map[string]string, file *os.File, v interface{}) error {
if strings.HasPrefix(path, "/") {
path = c.baseURL + path
}
var b bytes.Buffer
w := multipart.NewWriter(&b)
for name, val := range fields {
if err := w.WriteField(name, val); err != nil {
return err
}
}
if _, err := w.CreateFormFile("filename", filepath.Base(file.Name())); err != nil {
return err
}
header := b.Len()
if err := w.Close(); err != nil {
return err
}
body := io.MultiReader(bytes.NewReader(b.Bytes()[:header]),
file,
bytes.NewReader(b.Bytes()[header:]))
req, err := http.NewRequest(http.MethodPost, path, body)
if err != nil {
return err
}
fi, err := file.Stat()
if err != nil {
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
req.ContentLength = int64(b.Len()) + fi.Size()
c.authHeaders(&req.Header)
res, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer func() { _ = res.Body.Close() }()
return c.handleResponse(res, &v)
}
func (c *Client) authHeaders(header *http.Header) {
header.Add("User-Agent", c.userAgent)
header.Add("Accept", "application/json")
if c.token != "" {
header.Add("Authorization", "PVEAPIToken="+c.token)
} else if c.session != nil {
header.Add("Cookie", "PVEAuthCookie="+c.session.Ticket)
header.Add("CSRFPreventionToken", c.session.CSRFPreventionToken)
}
}
func (c *Client) handleResponse(res *http.Response, v interface{}) error {
if res.StatusCode == http.StatusInternalServerError ||
res.StatusCode == http.StatusNotImplemented {
return errors.New(res.Status)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
c.log.Debugf("RECV: %d - %s", res.StatusCode, res.Status)
if res.Request != nil && res.Request.URL != nil {
if res.Request.URL.String() != (c.baseURL + "/access/ticket") {
// don't show tokens out of the logs
c.log.Debugf("BODY: %s", string(body))
}
}
if res.StatusCode == http.StatusBadRequest {
var errorskey map[string]json.RawMessage
if err := json.Unmarshal(body, &errorskey); err != nil {
return err
}
if body, ok := errorskey["errors"]; ok {
return fmt.Errorf("bad request: %s - %s", res.Status, body)
}
return fmt.Errorf("bad request: %s - %s", res.Status, string(body))
}
// if nil passed don't bother to do any unmarshalling
if nil == v {
return nil
}
// account for everything being in a data key
var datakey map[string]json.RawMessage
if err := json.Unmarshal(body, &datakey); err != nil {
return err
}
if body, ok := datakey["data"]; ok {
return json.Unmarshal(body, &v)
}
return json.Unmarshal(body, &v) // assume passed in type fully supports response
}
func (c *Client) TermWebSocket(path string, term *Term) (chan []byte, chan []byte, chan error, func() error, error) {
if strings.HasPrefix(path, "/") {
path = strings.Replace(c.baseURL, "https://", "wss://", 1) + path
}
var tlsConfig *tls.Config
transport := c.httpClient.Transport.(*http.Transport)
if transport != nil {
tlsConfig = transport.TLSClientConfig
}
c.log.Debugf("connecting to websocket: %s", path)
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 30 * time.Second,
TLSClientConfig: tlsConfig,
}
dialerHeaders := http.Header{}
c.authHeaders(&dialerHeaders)
conn, _, err := dialer.Dial(path, dialerHeaders)
if err != nil {
return nil, nil, nil, nil, err
}
// start the session by sending user@realm:ticket
if err := conn.WriteMessage(websocket.BinaryMessage, []byte(term.User+":"+term.Ticket+"\n")); err != nil {
return nil, nil, nil, nil, err
}
// it sends back the same thing you just sent so catch it drop it
_, msg, err := conn.ReadMessage()
if err != nil || string(msg) != "OK" {
if err := conn.Close(); err != nil {
return nil, nil, nil, nil, fmt.Errorf("error closing websocket: %s", err.Error())
}
return nil, nil, nil, nil, fmt.Errorf("unable to establish websocket: %s", err.Error())
}
type size struct {
height int
width int
}
// start the session by sending user@realm:ticket
tsize := size{
height: goterm.Height(),
width: goterm.Width(),
}
c.log.Debugf("sending terminal size: %d x %d", tsize.height, tsize.width)
if err := conn.WriteMessage(websocket.BinaryMessage, []byte(fmt.Sprintf("1:%d:%d:", tsize.height, tsize.width))); err != nil {
return nil, nil, nil, nil, err
}
send := make(chan []byte)
recv := make(chan []byte)
errs := make(chan error)
done := make(chan struct{})
ticker := time.NewTicker(30 * time.Second)
resize := make(chan size)
go func(tsize size) {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
resized := size{
height: goterm.Height(),
width: goterm.Width(),
}
if tsize.height != resized.height ||
tsize.width != resized.width {
tsize = resized
resize <- resized
}
}
}
}(tsize)
closer := func() error {
close(done)
time.Sleep(1 * time.Second)
close(send)
close(recv)
close(errs)
ticker.Stop()
return conn.Close()
}
go func() {
for {
select {
case <-done:
return
default:
_, msg, err := conn.ReadMessage()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
if !websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
return
}
errs <- err
}
recv <- msg
}
}
}()
go func() {
for {
select {
case <-done:
if err := conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
errs <- err
}
return
case <-ticker.C:
c.log.Debugf("sending wss keep alive")
if err := conn.WriteMessage(websocket.BinaryMessage, []byte("2")); err != nil {
errs <- err
}
case resized := <-resize:
c.log.Debugf("resizing terminal window: %d x %d", resized.height, resized.width)
if err := conn.WriteMessage(websocket.BinaryMessage, []byte(fmt.Sprintf("1:%d:%d:", resized.height, resized.width))); err != nil {
errs <- err
}
case msg := <-send:
c.log.Debugf("sending: %s", msg)
send := append([]byte(fmt.Sprintf("0:%d:", len(msg))), msg...)
if err := conn.WriteMessage(websocket.BinaryMessage, send); err != nil {
errs <- err
}
}
}
}()
return send, recv, errs, closer, nil
}
func (c *Client) VNCWebSocket(path string, vnc *VNC) (chan []byte, chan []byte, chan error, func() error, error) {
if strings.HasPrefix(path, "/") {
path = strings.Replace(c.baseURL, "https://", "wss://", 1) + path
}
var tlsConfig *tls.Config
transport := c.httpClient.Transport.(*http.Transport)
if transport != nil {
tlsConfig = transport.TLSClientConfig
}
c.log.Debugf("connecting to websocket: %s", path)
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 30 * time.Second,
TLSClientConfig: tlsConfig,
}
dialerHeaders := http.Header{}
c.authHeaders(&dialerHeaders)
conn, _, err := dialer.Dial(path, dialerHeaders)
if err != nil {
return nil, nil, nil, nil, err
}
send := make(chan []byte)
recv := make(chan []byte)
errs := make(chan error)
done := make(chan struct{})
closer := func() error {
close(done)
time.Sleep(1 * time.Second)
close(send)
close(recv)
close(errs)
return conn.Close()
}
go func() {
for {
select {
case <-done:
return
default:
_, msg, err := conn.ReadMessage()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
if !websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
return
}
errs <- err
}
recv <- msg
}
}
}()
go func() {
for {
select {
case <-done:
if err := conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
errs <- err
}
return
case msg := <-send:
c.log.Debugf("sending: %s", msg)
if err := conn.WriteMessage(websocket.BinaryMessage, msg); err != nil {
errs <- err
}
}
}
}()
return send, recv, errs, closer, nil
}