// // rhimportd // // The Radio Helsinki Rivendell Import Daemon // // // Copyright (C) 2015 Christian Pointner // // 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 . // 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 [ ]") c.say(" prints command overview or detailed info to .") return case "set": c.say("usage: set ") c.say(" this sets the import parameter to .") 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: [ [ ] ... ]") c.say(" available commands:") c.say(" quit close connection (or use Ctrl-D)") c.say(" help [ ] print this, or help for specific command") c.say(" set sets parameter 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("\nimport 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) } else { out <- fmt.Sprintf("\nFileimport has failed (Cart/Cut %d/%d): %s\n", res.Cart, res.Cut, res.ErrorString) } } } func (c *TelnetClient) handle_cmd_run(args []string, cancel <-chan bool) { 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 } select { case <-cancel: // consume potentially pending cancel request default: } stdout := make(chan string) c.ctx.ProgressCallBack = telnet_progress_callback c.ctx.ProgressCallBackData = (chan<- string)(stdout) c.ctx.Cancel = cancel 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, cancel <-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, cancel) } else { c.say("unknown command '%s'", cmd) } done <- false } func (c *TelnetClient) handle_iac(iac []byte, cancel chan<- bool) 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: select { case cancel <- true: default: // process got canceled already } 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) cancel := make(chan bool, 1) defer func() { // make sure to cancel possible running job when closing connection select { case cancel <- true: default: } }() 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), cancel) default: go c.handle_cmd(cmd, done, cancel) } } 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() } }