summaryrefslogtreecommitdiff
path: root/src/helsinki.at/rhimportd/ctrlTelnet.go
blob: ff94d49566dd756c8c5646792adbfc014bed542a (plain)
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
//
//  rhimportd
//
//  The Radio Helsinki Rivendell Import Daemon
//
//
//  Copyright (C) 2015 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of rhimportd.
//
//  rhimportd is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  rhimportd is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with rhimportd. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"helsinki.at/rhimport"
	"net"
	"net/http"
	"strconv"
	"strings"
)

const (
	prompt = "> "
	EOT    = byte(4)
	IP     = byte(244)
	WILL   = byte(251)
	WONT   = byte(252)
	DO     = byte(253)
	DONT   = byte(254)
	IAC    = byte(255)
)

type TelnetClient struct {
	conn    net.Conn
	scanner *bufio.Scanner
	writer  *bufio.Writer
	conf    *rhimport.Config
	rddb    *rhimport.RdDbChan
	ctx     *rhimport.ImportContext
}

func (c *TelnetClient) write_string(text string) {
	defer c.writer.Flush()

	data := []byte(text)
	for {
		idx := bytes.IndexByte(data, IAC)
		if idx >= 0 {
			c.writer.Write(data[:idx+1])
			c.writer.WriteByte(IAC)
			data = data[idx+1:]
		} else {
			c.writer.Write(data)
			return
		}
	}
}

func (c *TelnetClient) say(format string, a ...interface{}) {
	c.write_string(fmt.Sprintf(format, a...) + "\n")
}

func (c *TelnetClient) handle_cmd_help(args []string) {
	switch len(args) {
	case 1:
		switch args[0] {
		case "quit":
			c.say("usage: quit")
			c.say("   terminates the client connection. You may also use Ctrl-D to do this.")
			return
		case "help":
			c.say("usage: help [ <cmd> ]")
			c.say("   prints command overview or detailed info to <cmd>.")
			return
		case "set":
			c.say("usage: set <param> <value>")
			c.say("   this sets the import parameter <param> to <value>.")
			c.say("")
			c.say("  available parameters:")
			c.say("    UserName             string   username to use for rdxport interface")
			c.say("    Password             string   password to use for rdxport interface")
			c.say("    SourceUri            string   uri to the file to import")
			c.say("    ShowId               uint     the RHRD show id to import to")
			c.say("    ClearShowCarts       bool     clear all show-carts before importing?")
			c.say("    GroupName            string   name of music-pool group to import to")
			c.say("    Cart                 uint     cart to import to")
			c.say("    ClearCart            bool     remove/add cart before import")
			c.say("    Cut                  uint     cut to import to")
			c.say("    Channels             uint     number of audio channels (default: %v)", c.conf.ImportParamDefaults.Channels)
			c.say("    NormalizationLevel   int      normalization level in dB (default: %v)", c.conf.ImportParamDefaults.NormalizationLevel)
			c.say("    AutotrimLevel        int      autotrim level in dB (default: %v)", c.conf.ImportParamDefaults.AutotrimLevel)
			c.say("    UseMetaData          bool     extract meta data from file (default: %v)", c.conf.ImportParamDefaults.UseMetaData)
			c.say("")
			c.say("  UserName, Password and SourceUri are mandatory parameters.")
			c.say("")
			c.say("  If ShowId is supplied GroupName, Channels, NomalizationLevel, AutorimLevel,")
			c.say("  UseMetaData and Cut will be ignored. The values from the shows' dropbox will")
			c.say("  be used instead. Cart may be specified but must point to an empty cart within")
			c.say("  that show. If ClearCut is true the specified cart will get deleted before")
			c.say("  importing. If Cart is 0 the next free cart in the show will be used. Show")
			c.say("  carts will always be imported into cut 1.")
			c.say("")
			c.say("  If GroupName is supplied Channels, NomalizationLevel, AutorimLevel,")
			c.say("  UseMetaData, Cut, Cart and ClearCart will be ignored. The values from")
			c.say("  the music pools' dropbox will be used instead. The file will always be")
			c.say("  imported into cut 1 of the first free cart within the music pool.")
			c.say("")
			c.say("  If ShowId and GroupName are omitted a Cart must be specified. Cut may be")
			c.say("  supplied in which case both cart and cut must already exist. The import will")
			c.say("  then replace the contents of the current data stored in Cart/Cut. If only Cart")
			c.say("  and no Cut is supplied and ClearCut is false the file will either get imported")
			c.say("  into the next cut of an existing cart or the cart will be created and the file")
			c.say("  will be imported into cut 1 of this cart.")
			c.say("")
			c.say("  In case of an error carts/cuts which might got created will be removed. Carts")
			c.say("  which got deleted because of ClearShowCarts or ClearCart are however gone for")
			c.say("  good.")
			return
		case "show":
			c.say("usage: show")
			c.say("   this prints the current values of all import parameters.")
			return
		case "reset":
			c.say("usage: reset")
			c.say("   this resets all import parameters to default values.")
			return
		case "run":
			c.say("usage: run")
			c.say("   this starts the fetch/import process according to the current")
			c.say("   import parameters.")
			return
		}
		fallthrough
	default:
		c.say("usage: <cmd> [ [ <arg1> ] ... ]")
		c.say("  available commands:")
		c.say("    quit                   close connection (or use Ctrl-D)")
		c.say("    help [ <cmd> ]         print this, or help for specific command")
		c.say("    set <param> <value>    sets parameter <param> on current import context")
		c.say("    show                   shows current import context")
		c.say("    reset                  resets current import context")
		c.say("    run                    runs fetch/import using current import context")
	}
}

func (c *TelnetClient) handle_cmd_set_string(param *string, val string) {
	if val == "\"\"" || val == "''" {
		*param = ""
	} else {
		*param = val
	}
}

func (c *TelnetClient) handle_cmd_set_int(param *int, val string) {
	if vint, err := strconv.ParseInt(val, 10, 32); err != nil {
		c.say("invalid value (must be an integer)")
	} else {
		*param = int(vint)
	}
}

func (c *TelnetClient) handle_cmd_set_uint(param *uint, val string) {
	if vuint, err := strconv.ParseUint(val, 10, 32); err != nil {
		c.say("invalid value (must be a positive integer)")
	} else {
		*param = uint(vuint)
	}
}

func (c *TelnetClient) handle_cmd_set_bool(param *bool, val string) {
	if vbool, err := strconv.ParseBool(val); err != nil {
		c.say("invalid value (must be true or false)")
	} else {
		*param = vbool
	}
}

func (c *TelnetClient) handle_cmd_set(args []string) {
	if len(args) != 2 {
		c.say("wrong number of arguments")
		return
	}
	if c.ctx == nil {
		c.ctx = rhimport.NewImportContext(c.conf, c.rddb, "")
		c.ctx.Trusted = true
	}
	switch strings.ToLower(args[0]) {
	case "username":
		c.handle_cmd_set_string(&c.ctx.UserName, args[1])
	case "password":
		c.handle_cmd_set_string(&c.ctx.Password, args[1])
	case "sourceuri":
		c.handle_cmd_set_string(&c.ctx.SourceUri, args[1])
	case "showid":
		c.handle_cmd_set_uint(&c.ctx.ShowId, args[1])
	case "clearshowcarts":
		c.handle_cmd_set_bool(&c.ctx.ClearShowCarts, args[1])
	case "groupname":
		c.handle_cmd_set_string(&c.ctx.GroupName, args[1])
	case "cart":
		c.handle_cmd_set_uint(&c.ctx.Cart, args[1])
	case "clearcart":
		c.handle_cmd_set_bool(&c.ctx.ClearCart, args[1])
	case "cut":
		c.handle_cmd_set_uint(&c.ctx.Cut, args[1])
	case "channels":
		c.handle_cmd_set_uint(&c.ctx.Channels, args[1])
	case "normalizationlevel":
		c.handle_cmd_set_int(&c.ctx.NormalizationLevel, args[1])
	case "autotrimlevel":
		c.handle_cmd_set_int(&c.ctx.AutotrimLevel, args[1])
	case "usemetadata":
		c.handle_cmd_set_bool(&c.ctx.UseMetaData, args[1])
	default:
		c.say("unknown parameter, use 'help set' for a list of available parameters")
	}
}

func (c *TelnetClient) handle_cmd_reset(args []string) {
	if len(args) > 0 {
		c.say("too many arguments")
		return
	}
	c.ctx = nil
}

func (c *TelnetClient) handle_cmd_show(args []string) {
	if len(args) > 0 {
		c.say("too many arguments")
		return
	}
	if c.ctx != nil {
		c.say(" UserName: %v", c.ctx.UserName)
		c.say(" Password: %v", c.ctx.Password)
		c.say(" SourceUri: %v", c.ctx.SourceUri)
		c.say(" ShowId: %v", c.ctx.ShowId)
		c.say(" ClearShowCarts: %v", c.ctx.ClearShowCarts)
		c.say(" GroupName: %v", c.ctx.GroupName)
		c.say(" Cart: %v", c.ctx.Cart)
		c.say(" ClearCart: %v", c.ctx.ClearCart)
		c.say(" Cut: %v", c.ctx.Cut)
		c.say(" Channels: %v", c.ctx.Channels)
		c.say(" NormalizationLevel: %v", c.ctx.NormalizationLevel)
		c.say(" AutotrimLevel: %v", c.ctx.AutotrimLevel)
		c.say(" UseMetaData: %v", c.ctx.UseMetaData)
	} else {
		c.say("context is empty")
	}
}

func telnet_progress_callback(step int, step_name string, progress float64, userdata interface{}) {
	out := userdata.(chan<- string)
	out <- fmt.Sprintf("%s: %3.2f%%\r", step_name, progress*100)
}

func telnet_cmd_run(ctx rhimport.ImportContext, out chan<- string) {
	defer close(out)

	out <- fmt.Sprintf("fetching file from '%s'\n", ctx.SourceUri)
	if res, err := rhimport.FetchFile(&ctx); err != nil {
		out <- fmt.Sprintf("fetch file error: %s\n", err)
		return
	} else if res.ResponseCode != http.StatusOK {
		out <- fmt.Sprintf("fetch file error: %s\n", res.ErrorString)
		return
	}

	out <- fmt.Sprintf("\nimporting file '%s'\n", ctx.SourceFile)
	if res, err := rhimport.ImportFile(&ctx); err != nil {
		out <- fmt.Sprintf("import file error: %s\n", err)
		return
	} else {
		if res.ResponseCode == http.StatusOK {
			out <- fmt.Sprintf("\nFile got succesfully imported into Cart/Cut %d/%d\n", res.Cart, res.Cut)
			rhl.Printf("File got succesfully imported into Cart/Cut %d/%d", res.Cart, res.Cut)
		} else {
			out <- fmt.Sprintf("Fileimport has failed (Cart/Cut %d/%d): %s\n", res.Cart, res.Cut, res.ErrorString)
			rhl.Printf("Fileimport has failed (Cart/Cut %d/%d): %s", res.Cart, res.Cut, res.ErrorString)
		}
	}
}

func (c *TelnetClient) handle_cmd_run(args []string) {
	if c.ctx == nil {
		c.say("context is empty please set at least one option")
		return
	}

	if err := c.ctx.SanityCheck(); err != nil {
		c.say("sanity check for import context returned: %s", err)
		return
	}

	stdout := make(chan string)
	c.ctx.ProgressCallBack = telnet_progress_callback
	c.ctx.ProgressCallBackData = (chan<- string)(stdout)
	go telnet_cmd_run(*c.ctx, stdout)
	for str := range stdout {
		c.write_string(str)
	}
}

func (c *TelnetClient) handle_cmd(cmdstr string, done chan<- bool) {
	cmdslice := strings.Fields(cmdstr)
	if len(cmdslice) == 0 || cmdslice[0] == "" {
		done <- false
		return
	}
	cmd := cmdslice[0]
	args := cmdslice[1:]

	if cmd == "quit" {
		done <- true
		return
	} else if cmd == "help" {
		c.handle_cmd_help(args)
	} else if cmd == "set" {
		c.handle_cmd_set(args)
	} else if cmd == "reset" {
		c.handle_cmd_reset(args)
	} else if cmd == "show" {
		c.handle_cmd_show(args)
	} else if cmd == "run" {
		c.handle_cmd_run(args)
	} else {
		c.say("unknown command '%s'", cmd)
	}
	done <- false
}

func (c *TelnetClient) handle_iac(iac []byte) bool {
	if len(iac) < 2 {
		return false // this shouldn't happen
	}

	switch iac[1] {
	case WILL, WONT: // Don't accept any proposed options
		iac[1] = DONT
	case DO, DONT:
		iac[1] = WONT
	case IP:
		// TODO: cancel running command (if any)
		rhdl.Printf("canceling running process - is not yet implemented!")
		return false
	default:
		rhdl.Printf("ignoring unimplemented telnet command: %X", iac[1])
		return false
	}
	c.writer.Write(iac)
	c.writer.Flush()

	return false
}

func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

func compare_idx(a, b int) int {
	if a < 0 {
		a = int(^uint(0) >> 1)
	}
	if b < 0 {
		b = int(^uint(0) >> 1)
	}
	return a - b
}

func ScanLinesTelnet(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	inl := bytes.IndexByte(data, '\n') // index of first newline character
	ieot := bytes.IndexByte(data, EOT) // index of first End of Transmission
	iiac := bytes.IndexByte(data, IAC) // index of first telnet IAC

	if inl >= 0 && compare_idx(inl, ieot) < 0 && compare_idx(inl, iiac) < 0 {
		return inl + 1, dropCR(data[0:inl]), nil // found a complete line
	}
	if ieot >= 0 && compare_idx(ieot, iiac) < 0 {
		return ieot + 1, data[ieot : ieot+1], nil // found a EOT (aka Ctrl-D)
	}
	if iiac >= 0 {
		l := 2
		if (len(data) - iiac) < 2 {
			return 0, nil, nil // data does not yet contain the telnet command code -> need more data
		}
		switch data[iiac+1] {
		case DONT, DO, WONT, WILL:
			if (len(data) - iiac) < 3 {
				return 0, nil, nil // this is a 3-byte command and data does not yet contain the option code -> need more data
			}
			l = 3
		}
		// TODO: this doesn't handle escaped IAC bytes correctly: this means utf-8 might be broken...
		return iiac + l, data[iiac : iiac+l], nil // found a Telnet Command
	}
	if atEOF {
		return len(data), dropCR(data), nil // allow last line to have no new line
	}
	return 0, nil, nil // we have found none of the escape codes -> need more data
}

func (c *TelnetClient) recv(in chan<- string) {
	defer close(in)

	for c.scanner.Scan() {
		b := c.scanner.Bytes()
		if len(b) > 0 && b[0] == EOT {
			rhdl.Printf("telnet-ctrl(%s): Ctrl-D received, closing", c.conn.RemoteAddr())
			return
		}
		in <- string(b)
	}
	if err := c.scanner.Err(); err != nil {
		rhdl.Printf("telnet-ctrl(%s): recv() error: %s", c.conn.RemoteAddr(), err)
	} else {
		rhdl.Printf("telnet-ctrl(%s): Connection closed by foreign host", c.conn.RemoteAddr())
	}
}

func (c *TelnetClient) handle() {
	defer c.conn.Close()

	in := make(chan string)
	go c.recv(in)

	done := make(chan bool)
	c.write_string(prompt)
	for {
		select {
		case cmd, ok := <-in:
			if !ok {
				return
			}
			if len(cmd) > 0 {
				switch cmd[0] {
				case IAC:
					c.handle_iac([]byte(cmd))
				default:
					go c.handle_cmd(cmd, done)
				}
			} else {
				c.write_string(prompt)
			}
		case exit := <-done:
			if exit {
				return
			}
			c.write_string(prompt)
		}
	}
}

func newTelnetClient(conn net.Conn, conf *rhimport.Config, rddb *rhimport.RdDbChan) (c *TelnetClient) {
	rhl.Println("telnet-ctrl: new client from:", conn.RemoteAddr())
	c = &TelnetClient{}
	c.conn = conn
	c.scanner = bufio.NewScanner(conn)
	c.scanner.Split(ScanLinesTelnet)
	c.writer = bufio.NewWriter(conn)
	c.conf = conf
	c.rddb = rddb
	c.ctx = nil
	return c
}

func StartControlTelnet(addr_s string, conf *rhimport.Config, rddb *rhimport.RdDbChan) {
	rhl.Println("telnet-ctrl: listening on", addr_s)

	server, err := net.Listen("tcp", addr_s)
	if err != nil {
		rhl.Println("telnet-ctrl: Listen() Error:", err)
		return
	}

	for {
		conn, err := server.Accept()
		if err != nil {
			rhl.Println("telnet-ctrl: Accept() Error:", err)
			return
		}

		c := newTelnetClient(conn, conf, rddb)
		go c.handle()
	}
}